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    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
  460enum InlineCompletion {
  461    Edit(Vec<(Range<Anchor>, String)>),
  462    Move(Anchor),
  463}
  464
  465struct InlineCompletionState {
  466    inlay_ids: Vec<InlayId>,
  467    completion: InlineCompletion,
  468    invalidation_range: Range<Anchor>,
  469}
  470
  471enum InlineCompletionHighlight {}
  472
  473#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  474struct EditorActionId(usize);
  475
  476impl EditorActionId {
  477    pub fn post_inc(&mut self) -> Self {
  478        let answer = self.0;
  479
  480        *self = Self(answer + 1);
  481
  482        Self(answer)
  483    }
  484}
  485
  486// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  487// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  488
  489type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  490type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  491
  492#[derive(Default)]
  493struct ScrollbarMarkerState {
  494    scrollbar_size: Size<Pixels>,
  495    dirty: bool,
  496    markers: Arc<[PaintQuad]>,
  497    pending_refresh: Option<Task<Result<()>>>,
  498}
  499
  500impl ScrollbarMarkerState {
  501    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  502        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  503    }
  504}
  505
  506#[derive(Clone, Debug)]
  507struct RunnableTasks {
  508    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  509    offset: MultiBufferOffset,
  510    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  511    column: u32,
  512    // Values of all named captures, including those starting with '_'
  513    extra_variables: HashMap<String, String>,
  514    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  515    context_range: Range<BufferOffset>,
  516}
  517
  518impl RunnableTasks {
  519    fn resolve<'a>(
  520        &'a self,
  521        cx: &'a task::TaskContext,
  522    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  523        self.templates.iter().filter_map(|(kind, template)| {
  524            template
  525                .resolve_task(&kind.to_id_base(), cx)
  526                .map(|task| (kind.clone(), task))
  527        })
  528    }
  529}
  530
  531#[derive(Clone)]
  532struct ResolvedTasks {
  533    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  534    position: Anchor,
  535}
  536#[derive(Copy, Clone, Debug)]
  537struct MultiBufferOffset(usize);
  538#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  539struct BufferOffset(usize);
  540
  541// Addons allow storing per-editor state in other crates (e.g. Vim)
  542pub trait Addon: 'static {
  543    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  544
  545    fn to_any(&self) -> &dyn std::any::Any;
  546}
  547
  548#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  549pub enum IsVimMode {
  550    Yes,
  551    No,
  552}
  553
  554/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  555///
  556/// See the [module level documentation](self) for more information.
  557pub struct Editor {
  558    focus_handle: FocusHandle,
  559    last_focused_descendant: Option<WeakFocusHandle>,
  560    /// The text buffer being edited
  561    buffer: Model<MultiBuffer>,
  562    /// Map of how text in the buffer should be displayed.
  563    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  564    pub display_map: Model<DisplayMap>,
  565    pub selections: SelectionsCollection,
  566    pub scroll_manager: ScrollManager,
  567    /// When inline assist editors are linked, they all render cursors because
  568    /// typing enters text into each of them, even the ones that aren't focused.
  569    pub(crate) show_cursor_when_unfocused: bool,
  570    columnar_selection_tail: Option<Anchor>,
  571    add_selections_state: Option<AddSelectionsState>,
  572    select_next_state: Option<SelectNextState>,
  573    select_prev_state: Option<SelectNextState>,
  574    selection_history: SelectionHistory,
  575    autoclose_regions: Vec<AutocloseRegion>,
  576    snippet_stack: InvalidationStack<SnippetState>,
  577    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  578    ime_transaction: Option<TransactionId>,
  579    active_diagnostics: Option<ActiveDiagnosticGroup>,
  580    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  581
  582    project: Option<Model<Project>>,
  583    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  584    completion_provider: Option<Box<dyn CompletionProvider>>,
  585    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  586    blink_manager: Model<BlinkManager>,
  587    show_cursor_names: bool,
  588    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  589    pub show_local_selections: bool,
  590    mode: EditorMode,
  591    show_breadcrumbs: bool,
  592    show_gutter: bool,
  593    show_line_numbers: Option<bool>,
  594    use_relative_line_numbers: Option<bool>,
  595    show_git_diff_gutter: Option<bool>,
  596    show_code_actions: Option<bool>,
  597    show_runnables: Option<bool>,
  598    show_wrap_guides: Option<bool>,
  599    show_indent_guides: Option<bool>,
  600    placeholder_text: Option<Arc<str>>,
  601    highlight_order: usize,
  602    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  603    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  604    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  605    scrollbar_marker_state: ScrollbarMarkerState,
  606    active_indent_guides_state: ActiveIndentGuidesState,
  607    nav_history: Option<ItemNavHistory>,
  608    context_menu: RefCell<Option<CodeContextMenu>>,
  609    mouse_context_menu: Option<MouseContextMenu>,
  610    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  611    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  612    signature_help_state: SignatureHelpState,
  613    auto_signature_help: Option<bool>,
  614    find_all_references_task_sources: Vec<Anchor>,
  615    next_completion_id: CompletionId,
  616    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  617    code_actions_task: Option<Task<Result<()>>>,
  618    document_highlights_task: Option<Task<()>>,
  619    linked_editing_range_task: Option<Task<Option<()>>>,
  620    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  621    pending_rename: Option<RenameState>,
  622    searchable: bool,
  623    cursor_shape: CursorShape,
  624    current_line_highlight: Option<CurrentLineHighlight>,
  625    collapse_matches: bool,
  626    autoindent_mode: Option<AutoindentMode>,
  627    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  628    input_enabled: bool,
  629    use_modal_editing: bool,
  630    read_only: bool,
  631    leader_peer_id: Option<PeerId>,
  632    remote_id: Option<ViewId>,
  633    hover_state: HoverState,
  634    gutter_hovered: bool,
  635    hovered_link_state: Option<HoveredLinkState>,
  636    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  637    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  638    active_inline_completion: Option<InlineCompletionState>,
  639    // enable_inline_completions is a switch that Vim can use to disable
  640    // inline completions based on its mode.
  641    enable_inline_completions: bool,
  642    show_inline_completions_override: Option<bool>,
  643    inlay_hint_cache: InlayHintCache,
  644    diff_map: DiffMap,
  645    next_inlay_id: usize,
  646    _subscriptions: Vec<Subscription>,
  647    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  648    gutter_dimensions: GutterDimensions,
  649    style: Option<EditorStyle>,
  650    text_style_refinement: Option<TextStyleRefinement>,
  651    next_editor_action_id: EditorActionId,
  652    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  653    use_autoclose: bool,
  654    use_auto_surround: bool,
  655    auto_replace_emoji_shortcode: bool,
  656    show_git_blame_gutter: bool,
  657    show_git_blame_inline: bool,
  658    show_git_blame_inline_delay_task: Option<Task<()>>,
  659    git_blame_inline_enabled: bool,
  660    serialize_dirty_buffers: bool,
  661    show_selection_menu: Option<bool>,
  662    blame: Option<Model<GitBlame>>,
  663    blame_subscription: Option<Subscription>,
  664    custom_context_menu: Option<
  665        Box<
  666            dyn 'static
  667                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  668        >,
  669    >,
  670    last_bounds: Option<Bounds<Pixels>>,
  671    expect_bounds_change: Option<Bounds<Pixels>>,
  672    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  673    tasks_update_task: Option<Task<()>>,
  674    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  675    breadcrumb_header: Option<String>,
  676    focused_block: Option<FocusedBlock>,
  677    next_scroll_position: NextScrollCursorCenterTopBottom,
  678    addons: HashMap<TypeId, Box<dyn Addon>>,
  679    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  680    toggle_fold_multiple_buffers: Task<()>,
  681    _scroll_cursor_center_top_bottom_task: Task<()>,
  682}
  683
  684#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  685enum NextScrollCursorCenterTopBottom {
  686    #[default]
  687    Center,
  688    Top,
  689    Bottom,
  690}
  691
  692impl NextScrollCursorCenterTopBottom {
  693    fn next(&self) -> Self {
  694        match self {
  695            Self::Center => Self::Top,
  696            Self::Top => Self::Bottom,
  697            Self::Bottom => Self::Center,
  698        }
  699    }
  700}
  701
  702#[derive(Clone)]
  703pub struct EditorSnapshot {
  704    pub mode: EditorMode,
  705    show_gutter: bool,
  706    show_line_numbers: Option<bool>,
  707    show_git_diff_gutter: Option<bool>,
  708    show_code_actions: Option<bool>,
  709    show_runnables: Option<bool>,
  710    git_blame_gutter_max_author_length: Option<usize>,
  711    pub display_snapshot: DisplaySnapshot,
  712    pub placeholder_text: Option<Arc<str>>,
  713    diff_map: DiffMapSnapshot,
  714    is_focused: bool,
  715    scroll_anchor: ScrollAnchor,
  716    ongoing_scroll: OngoingScroll,
  717    current_line_highlight: CurrentLineHighlight,
  718    gutter_hovered: bool,
  719}
  720
  721const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  722
  723#[derive(Default, Debug, Clone, Copy)]
  724pub struct GutterDimensions {
  725    pub left_padding: Pixels,
  726    pub right_padding: Pixels,
  727    pub width: Pixels,
  728    pub margin: Pixels,
  729    pub git_blame_entries_width: Option<Pixels>,
  730}
  731
  732impl GutterDimensions {
  733    /// The full width of the space taken up by the gutter.
  734    pub fn full_width(&self) -> Pixels {
  735        self.margin + self.width
  736    }
  737
  738    /// The width of the space reserved for the fold indicators,
  739    /// use alongside 'justify_end' and `gutter_width` to
  740    /// right align content with the line numbers
  741    pub fn fold_area_width(&self) -> Pixels {
  742        self.margin + self.right_padding
  743    }
  744}
  745
  746#[derive(Debug)]
  747pub struct RemoteSelection {
  748    pub replica_id: ReplicaId,
  749    pub selection: Selection<Anchor>,
  750    pub cursor_shape: CursorShape,
  751    pub peer_id: PeerId,
  752    pub line_mode: bool,
  753    pub participant_index: Option<ParticipantIndex>,
  754    pub user_name: Option<SharedString>,
  755}
  756
  757#[derive(Clone, Debug)]
  758struct SelectionHistoryEntry {
  759    selections: Arc<[Selection<Anchor>]>,
  760    select_next_state: Option<SelectNextState>,
  761    select_prev_state: Option<SelectNextState>,
  762    add_selections_state: Option<AddSelectionsState>,
  763}
  764
  765enum SelectionHistoryMode {
  766    Normal,
  767    Undoing,
  768    Redoing,
  769}
  770
  771#[derive(Clone, PartialEq, Eq, Hash)]
  772struct HoveredCursor {
  773    replica_id: u16,
  774    selection_id: usize,
  775}
  776
  777impl Default for SelectionHistoryMode {
  778    fn default() -> Self {
  779        Self::Normal
  780    }
  781}
  782
  783#[derive(Default)]
  784struct SelectionHistory {
  785    #[allow(clippy::type_complexity)]
  786    selections_by_transaction:
  787        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  788    mode: SelectionHistoryMode,
  789    undo_stack: VecDeque<SelectionHistoryEntry>,
  790    redo_stack: VecDeque<SelectionHistoryEntry>,
  791}
  792
  793impl SelectionHistory {
  794    fn insert_transaction(
  795        &mut self,
  796        transaction_id: TransactionId,
  797        selections: Arc<[Selection<Anchor>]>,
  798    ) {
  799        self.selections_by_transaction
  800            .insert(transaction_id, (selections, None));
  801    }
  802
  803    #[allow(clippy::type_complexity)]
  804    fn transaction(
  805        &self,
  806        transaction_id: TransactionId,
  807    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  808        self.selections_by_transaction.get(&transaction_id)
  809    }
  810
  811    #[allow(clippy::type_complexity)]
  812    fn transaction_mut(
  813        &mut self,
  814        transaction_id: TransactionId,
  815    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  816        self.selections_by_transaction.get_mut(&transaction_id)
  817    }
  818
  819    fn push(&mut self, entry: SelectionHistoryEntry) {
  820        if !entry.selections.is_empty() {
  821            match self.mode {
  822                SelectionHistoryMode::Normal => {
  823                    self.push_undo(entry);
  824                    self.redo_stack.clear();
  825                }
  826                SelectionHistoryMode::Undoing => self.push_redo(entry),
  827                SelectionHistoryMode::Redoing => self.push_undo(entry),
  828            }
  829        }
  830    }
  831
  832    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  833        if self
  834            .undo_stack
  835            .back()
  836            .map_or(true, |e| e.selections != entry.selections)
  837        {
  838            self.undo_stack.push_back(entry);
  839            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  840                self.undo_stack.pop_front();
  841            }
  842        }
  843    }
  844
  845    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  846        if self
  847            .redo_stack
  848            .back()
  849            .map_or(true, |e| e.selections != entry.selections)
  850        {
  851            self.redo_stack.push_back(entry);
  852            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  853                self.redo_stack.pop_front();
  854            }
  855        }
  856    }
  857}
  858
  859struct RowHighlight {
  860    index: usize,
  861    range: Range<Anchor>,
  862    color: Hsla,
  863    should_autoscroll: bool,
  864}
  865
  866#[derive(Clone, Debug)]
  867struct AddSelectionsState {
  868    above: bool,
  869    stack: Vec<usize>,
  870}
  871
  872#[derive(Clone)]
  873struct SelectNextState {
  874    query: AhoCorasick,
  875    wordwise: bool,
  876    done: bool,
  877}
  878
  879impl std::fmt::Debug for SelectNextState {
  880    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  881        f.debug_struct(std::any::type_name::<Self>())
  882            .field("wordwise", &self.wordwise)
  883            .field("done", &self.done)
  884            .finish()
  885    }
  886}
  887
  888#[derive(Debug)]
  889struct AutocloseRegion {
  890    selection_id: usize,
  891    range: Range<Anchor>,
  892    pair: BracketPair,
  893}
  894
  895#[derive(Debug)]
  896struct SnippetState {
  897    ranges: Vec<Vec<Range<Anchor>>>,
  898    active_index: usize,
  899    choices: Vec<Option<Vec<String>>>,
  900}
  901
  902#[doc(hidden)]
  903pub struct RenameState {
  904    pub range: Range<Anchor>,
  905    pub old_name: Arc<str>,
  906    pub editor: View<Editor>,
  907    block_id: CustomBlockId,
  908}
  909
  910struct InvalidationStack<T>(Vec<T>);
  911
  912struct RegisteredInlineCompletionProvider {
  913    provider: Arc<dyn InlineCompletionProviderHandle>,
  914    _subscription: Subscription,
  915}
  916
  917#[derive(Debug)]
  918struct ActiveDiagnosticGroup {
  919    primary_range: Range<Anchor>,
  920    primary_message: String,
  921    group_id: usize,
  922    blocks: HashMap<CustomBlockId, Diagnostic>,
  923    is_valid: bool,
  924}
  925
  926#[derive(Serialize, Deserialize, Clone, Debug)]
  927pub struct ClipboardSelection {
  928    pub len: usize,
  929    pub is_entire_line: bool,
  930    pub first_line_indent: u32,
  931}
  932
  933#[derive(Debug)]
  934pub(crate) struct NavigationData {
  935    cursor_anchor: Anchor,
  936    cursor_position: Point,
  937    scroll_anchor: ScrollAnchor,
  938    scroll_top_row: u32,
  939}
  940
  941#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  942pub enum GotoDefinitionKind {
  943    Symbol,
  944    Declaration,
  945    Type,
  946    Implementation,
  947}
  948
  949#[derive(Debug, Clone)]
  950enum InlayHintRefreshReason {
  951    Toggle(bool),
  952    SettingsChange(InlayHintSettings),
  953    NewLinesShown,
  954    BufferEdited(HashSet<Arc<Language>>),
  955    RefreshRequested,
  956    ExcerptsRemoved(Vec<ExcerptId>),
  957}
  958
  959impl InlayHintRefreshReason {
  960    fn description(&self) -> &'static str {
  961        match self {
  962            Self::Toggle(_) => "toggle",
  963            Self::SettingsChange(_) => "settings change",
  964            Self::NewLinesShown => "new lines shown",
  965            Self::BufferEdited(_) => "buffer edited",
  966            Self::RefreshRequested => "refresh requested",
  967            Self::ExcerptsRemoved(_) => "excerpts removed",
  968        }
  969    }
  970}
  971
  972pub(crate) struct FocusedBlock {
  973    id: BlockId,
  974    focus_handle: WeakFocusHandle,
  975}
  976
  977#[derive(Clone)]
  978struct JumpData {
  979    excerpt_id: ExcerptId,
  980    position: Point,
  981    anchor: text::Anchor,
  982    path: Option<project::ProjectPath>,
  983    line_offset_from_top: u32,
  984}
  985
  986impl Editor {
  987    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
  988        let buffer = cx.new_model(|cx| Buffer::local("", cx));
  989        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
  990        Self::new(
  991            EditorMode::SingleLine { auto_width: false },
  992            buffer,
  993            None,
  994            false,
  995            cx,
  996        )
  997    }
  998
  999    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1000        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1001        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1002        Self::new(EditorMode::Full, buffer, None, false, cx)
 1003    }
 1004
 1005    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1006        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1007        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1008        Self::new(
 1009            EditorMode::SingleLine { auto_width: true },
 1010            buffer,
 1011            None,
 1012            false,
 1013            cx,
 1014        )
 1015    }
 1016
 1017    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1018        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1019        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1020        Self::new(
 1021            EditorMode::AutoHeight { max_lines },
 1022            buffer,
 1023            None,
 1024            false,
 1025            cx,
 1026        )
 1027    }
 1028
 1029    pub fn for_buffer(
 1030        buffer: Model<Buffer>,
 1031        project: Option<Model<Project>>,
 1032        cx: &mut ViewContext<Self>,
 1033    ) -> Self {
 1034        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1035        Self::new(EditorMode::Full, buffer, project, false, cx)
 1036    }
 1037
 1038    pub fn for_multibuffer(
 1039        buffer: Model<MultiBuffer>,
 1040        project: Option<Model<Project>>,
 1041        show_excerpt_controls: bool,
 1042        cx: &mut ViewContext<Self>,
 1043    ) -> Self {
 1044        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1045    }
 1046
 1047    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1048        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1049        let mut clone = Self::new(
 1050            self.mode,
 1051            self.buffer.clone(),
 1052            self.project.clone(),
 1053            show_excerpt_controls,
 1054            cx,
 1055        );
 1056        self.display_map.update(cx, |display_map, cx| {
 1057            let snapshot = display_map.snapshot(cx);
 1058            clone.display_map.update(cx, |display_map, cx| {
 1059                display_map.set_state(&snapshot, cx);
 1060            });
 1061        });
 1062        clone.selections.clone_state(&self.selections);
 1063        clone.scroll_manager.clone_state(&self.scroll_manager);
 1064        clone.searchable = self.searchable;
 1065        clone
 1066    }
 1067
 1068    pub fn new(
 1069        mode: EditorMode,
 1070        buffer: Model<MultiBuffer>,
 1071        project: Option<Model<Project>>,
 1072        show_excerpt_controls: bool,
 1073        cx: &mut ViewContext<Self>,
 1074    ) -> Self {
 1075        let style = cx.text_style();
 1076        let font_size = style.font_size.to_pixels(cx.rem_size());
 1077        let editor = cx.view().downgrade();
 1078        let fold_placeholder = FoldPlaceholder {
 1079            constrain_width: true,
 1080            render: Arc::new(move |fold_id, fold_range, cx| {
 1081                let editor = editor.clone();
 1082                div()
 1083                    .id(fold_id)
 1084                    .bg(cx.theme().colors().ghost_element_background)
 1085                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1086                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1087                    .rounded_sm()
 1088                    .size_full()
 1089                    .cursor_pointer()
 1090                    .child("")
 1091                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1092                    .on_click(move |_, cx| {
 1093                        editor
 1094                            .update(cx, |editor, cx| {
 1095                                editor.unfold_ranges(
 1096                                    &[fold_range.start..fold_range.end],
 1097                                    true,
 1098                                    false,
 1099                                    cx,
 1100                                );
 1101                                cx.stop_propagation();
 1102                            })
 1103                            .ok();
 1104                    })
 1105                    .into_any()
 1106            }),
 1107            merge_adjacent: true,
 1108            ..Default::default()
 1109        };
 1110        let display_map = cx.new_model(|cx| {
 1111            DisplayMap::new(
 1112                buffer.clone(),
 1113                style.font(),
 1114                font_size,
 1115                None,
 1116                show_excerpt_controls,
 1117                FILE_HEADER_HEIGHT,
 1118                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1119                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1120                fold_placeholder,
 1121                cx,
 1122            )
 1123        });
 1124
 1125        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1126
 1127        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1128
 1129        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1130            .then(|| language_settings::SoftWrap::None);
 1131
 1132        let mut project_subscriptions = Vec::new();
 1133        if mode == EditorMode::Full {
 1134            if let Some(project) = project.as_ref() {
 1135                if buffer.read(cx).is_singleton() {
 1136                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1137                        cx.emit(EditorEvent::TitleChanged);
 1138                    }));
 1139                }
 1140                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1141                    if let project::Event::RefreshInlayHints = event {
 1142                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1143                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1144                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1145                            let focus_handle = editor.focus_handle(cx);
 1146                            if focus_handle.is_focused(cx) {
 1147                                let snapshot = buffer.read(cx).snapshot();
 1148                                for (range, snippet) in snippet_edits {
 1149                                    let editor_range =
 1150                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1151                                    editor
 1152                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1153                                        .ok();
 1154                                }
 1155                            }
 1156                        }
 1157                    }
 1158                }));
 1159                if let Some(task_inventory) = project
 1160                    .read(cx)
 1161                    .task_store()
 1162                    .read(cx)
 1163                    .task_inventory()
 1164                    .cloned()
 1165                {
 1166                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1167                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1168                    }));
 1169                }
 1170            }
 1171        }
 1172
 1173        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1174
 1175        let inlay_hint_settings =
 1176            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1177        let focus_handle = cx.focus_handle();
 1178        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1179        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1180            .detach();
 1181        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1182            .detach();
 1183        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1184
 1185        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1186            Some(false)
 1187        } else {
 1188            None
 1189        };
 1190
 1191        let mut code_action_providers = Vec::new();
 1192        if let Some(project) = project.clone() {
 1193            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1194            code_action_providers.push(Rc::new(project) as Rc<_>);
 1195        }
 1196
 1197        let mut this = Self {
 1198            focus_handle,
 1199            show_cursor_when_unfocused: false,
 1200            last_focused_descendant: None,
 1201            buffer: buffer.clone(),
 1202            display_map: display_map.clone(),
 1203            selections,
 1204            scroll_manager: ScrollManager::new(cx),
 1205            columnar_selection_tail: None,
 1206            add_selections_state: None,
 1207            select_next_state: None,
 1208            select_prev_state: None,
 1209            selection_history: Default::default(),
 1210            autoclose_regions: Default::default(),
 1211            snippet_stack: Default::default(),
 1212            select_larger_syntax_node_stack: Vec::new(),
 1213            ime_transaction: Default::default(),
 1214            active_diagnostics: None,
 1215            soft_wrap_mode_override,
 1216            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1217            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1218            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1219            project,
 1220            blink_manager: blink_manager.clone(),
 1221            show_local_selections: true,
 1222            mode,
 1223            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1224            show_gutter: mode == EditorMode::Full,
 1225            show_line_numbers: None,
 1226            use_relative_line_numbers: None,
 1227            show_git_diff_gutter: None,
 1228            show_code_actions: None,
 1229            show_runnables: None,
 1230            show_wrap_guides: None,
 1231            show_indent_guides,
 1232            placeholder_text: None,
 1233            highlight_order: 0,
 1234            highlighted_rows: HashMap::default(),
 1235            background_highlights: Default::default(),
 1236            gutter_highlights: TreeMap::default(),
 1237            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1238            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1239            nav_history: None,
 1240            context_menu: RefCell::new(None),
 1241            mouse_context_menu: None,
 1242            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1243            completion_tasks: Default::default(),
 1244            signature_help_state: SignatureHelpState::default(),
 1245            auto_signature_help: None,
 1246            find_all_references_task_sources: Vec::new(),
 1247            next_completion_id: 0,
 1248            next_inlay_id: 0,
 1249            code_action_providers,
 1250            available_code_actions: Default::default(),
 1251            code_actions_task: Default::default(),
 1252            document_highlights_task: Default::default(),
 1253            linked_editing_range_task: Default::default(),
 1254            pending_rename: Default::default(),
 1255            searchable: true,
 1256            cursor_shape: EditorSettings::get_global(cx)
 1257                .cursor_shape
 1258                .unwrap_or_default(),
 1259            current_line_highlight: None,
 1260            autoindent_mode: Some(AutoindentMode::EachLine),
 1261            collapse_matches: false,
 1262            workspace: None,
 1263            input_enabled: true,
 1264            use_modal_editing: mode == EditorMode::Full,
 1265            read_only: false,
 1266            use_autoclose: true,
 1267            use_auto_surround: true,
 1268            auto_replace_emoji_shortcode: false,
 1269            leader_peer_id: None,
 1270            remote_id: None,
 1271            hover_state: Default::default(),
 1272            hovered_link_state: Default::default(),
 1273            inline_completion_provider: None,
 1274            active_inline_completion: None,
 1275            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1276            diff_map: DiffMap::default(),
 1277            gutter_hovered: false,
 1278            pixel_position_of_newest_cursor: None,
 1279            last_bounds: None,
 1280            expect_bounds_change: None,
 1281            gutter_dimensions: GutterDimensions::default(),
 1282            style: None,
 1283            show_cursor_names: false,
 1284            hovered_cursors: Default::default(),
 1285            next_editor_action_id: EditorActionId::default(),
 1286            editor_actions: Rc::default(),
 1287            show_inline_completions_override: None,
 1288            enable_inline_completions: true,
 1289            custom_context_menu: None,
 1290            show_git_blame_gutter: false,
 1291            show_git_blame_inline: false,
 1292            show_selection_menu: None,
 1293            show_git_blame_inline_delay_task: None,
 1294            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1295            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1296                .session
 1297                .restore_unsaved_buffers,
 1298            blame: None,
 1299            blame_subscription: None,
 1300            tasks: Default::default(),
 1301            _subscriptions: vec![
 1302                cx.observe(&buffer, Self::on_buffer_changed),
 1303                cx.subscribe(&buffer, Self::on_buffer_event),
 1304                cx.observe(&display_map, Self::on_display_map_changed),
 1305                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1306                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1307                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1308                cx.observe_window_activation(|editor, cx| {
 1309                    let active = cx.is_window_active();
 1310                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1311                        if active {
 1312                            blink_manager.enable(cx);
 1313                        } else {
 1314                            blink_manager.disable(cx);
 1315                        }
 1316                    });
 1317                }),
 1318            ],
 1319            tasks_update_task: None,
 1320            linked_edit_ranges: Default::default(),
 1321            previous_search_ranges: None,
 1322            breadcrumb_header: None,
 1323            focused_block: None,
 1324            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1325            addons: HashMap::default(),
 1326            registered_buffers: HashMap::default(),
 1327            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1328            toggle_fold_multiple_buffers: Task::ready(()),
 1329            text_style_refinement: None,
 1330        };
 1331        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1332        this._subscriptions.extend(project_subscriptions);
 1333
 1334        this.end_selection(cx);
 1335        this.scroll_manager.show_scrollbar(cx);
 1336
 1337        if mode == EditorMode::Full {
 1338            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1339            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1340
 1341            if this.git_blame_inline_enabled {
 1342                this.git_blame_inline_enabled = true;
 1343                this.start_git_blame_inline(false, cx);
 1344            }
 1345
 1346            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1347                if let Some(project) = this.project.as_ref() {
 1348                    let lsp_store = project.read(cx).lsp_store();
 1349                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1350                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1351                    });
 1352                    this.registered_buffers
 1353                        .insert(buffer.read(cx).remote_id(), handle);
 1354                }
 1355            }
 1356        }
 1357
 1358        this.report_editor_event("open", None, cx);
 1359        this
 1360    }
 1361
 1362    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1363        self.mouse_context_menu
 1364            .as_ref()
 1365            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1366    }
 1367
 1368    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1369        let mut key_context = KeyContext::new_with_defaults();
 1370        key_context.add("Editor");
 1371        let mode = match self.mode {
 1372            EditorMode::SingleLine { .. } => "single_line",
 1373            EditorMode::AutoHeight { .. } => "auto_height",
 1374            EditorMode::Full => "full",
 1375        };
 1376
 1377        if EditorSettings::jupyter_enabled(cx) {
 1378            key_context.add("jupyter");
 1379        }
 1380
 1381        key_context.set("mode", mode);
 1382        if self.pending_rename.is_some() {
 1383            key_context.add("renaming");
 1384        }
 1385        match self.context_menu.borrow().as_ref() {
 1386            Some(CodeContextMenu::Completions(_)) => {
 1387                key_context.add("menu");
 1388                key_context.add("showing_completions")
 1389            }
 1390            Some(CodeContextMenu::CodeActions(_)) => {
 1391                key_context.add("menu");
 1392                key_context.add("showing_code_actions")
 1393            }
 1394            None => {}
 1395        }
 1396
 1397        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1398        if !self.focus_handle(cx).contains_focused(cx)
 1399            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1400        {
 1401            for addon in self.addons.values() {
 1402                addon.extend_key_context(&mut key_context, cx)
 1403            }
 1404        }
 1405
 1406        if let Some(extension) = self
 1407            .buffer
 1408            .read(cx)
 1409            .as_singleton()
 1410            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1411        {
 1412            key_context.set("extension", extension.to_string());
 1413        }
 1414
 1415        if self.has_active_inline_completion() {
 1416            key_context.add("copilot_suggestion");
 1417            key_context.add("inline_completion");
 1418        }
 1419
 1420        if !self
 1421            .selections
 1422            .disjoint
 1423            .iter()
 1424            .all(|selection| selection.start == selection.end)
 1425        {
 1426            key_context.add("selection");
 1427        }
 1428
 1429        key_context
 1430    }
 1431
 1432    pub fn new_file(
 1433        workspace: &mut Workspace,
 1434        _: &workspace::NewFile,
 1435        cx: &mut ViewContext<Workspace>,
 1436    ) {
 1437        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1438            "Failed to create buffer",
 1439            cx,
 1440            |e, _| match e.error_code() {
 1441                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1442                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1443                e.error_tag("required").unwrap_or("the latest version")
 1444            )),
 1445                _ => None,
 1446            },
 1447        );
 1448    }
 1449
 1450    pub fn new_in_workspace(
 1451        workspace: &mut Workspace,
 1452        cx: &mut ViewContext<Workspace>,
 1453    ) -> Task<Result<View<Editor>>> {
 1454        let project = workspace.project().clone();
 1455        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1456
 1457        cx.spawn(|workspace, mut cx| async move {
 1458            let buffer = create.await?;
 1459            workspace.update(&mut cx, |workspace, cx| {
 1460                let editor =
 1461                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1462                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1463                editor
 1464            })
 1465        })
 1466    }
 1467
 1468    fn new_file_vertical(
 1469        workspace: &mut Workspace,
 1470        _: &workspace::NewFileSplitVertical,
 1471        cx: &mut ViewContext<Workspace>,
 1472    ) {
 1473        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1474    }
 1475
 1476    fn new_file_horizontal(
 1477        workspace: &mut Workspace,
 1478        _: &workspace::NewFileSplitHorizontal,
 1479        cx: &mut ViewContext<Workspace>,
 1480    ) {
 1481        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1482    }
 1483
 1484    fn new_file_in_direction(
 1485        workspace: &mut Workspace,
 1486        direction: SplitDirection,
 1487        cx: &mut ViewContext<Workspace>,
 1488    ) {
 1489        let project = workspace.project().clone();
 1490        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1491
 1492        cx.spawn(|workspace, mut cx| async move {
 1493            let buffer = create.await?;
 1494            workspace.update(&mut cx, move |workspace, cx| {
 1495                workspace.split_item(
 1496                    direction,
 1497                    Box::new(
 1498                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1499                    ),
 1500                    cx,
 1501                )
 1502            })?;
 1503            anyhow::Ok(())
 1504        })
 1505        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1506            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1507                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1508                e.error_tag("required").unwrap_or("the latest version")
 1509            )),
 1510            _ => None,
 1511        });
 1512    }
 1513
 1514    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1515        self.leader_peer_id
 1516    }
 1517
 1518    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1519        &self.buffer
 1520    }
 1521
 1522    pub fn workspace(&self) -> Option<View<Workspace>> {
 1523        self.workspace.as_ref()?.0.upgrade()
 1524    }
 1525
 1526    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1527        self.buffer().read(cx).title(cx)
 1528    }
 1529
 1530    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1531        let git_blame_gutter_max_author_length = self
 1532            .render_git_blame_gutter(cx)
 1533            .then(|| {
 1534                if let Some(blame) = self.blame.as_ref() {
 1535                    let max_author_length =
 1536                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1537                    Some(max_author_length)
 1538                } else {
 1539                    None
 1540                }
 1541            })
 1542            .flatten();
 1543
 1544        EditorSnapshot {
 1545            mode: self.mode,
 1546            show_gutter: self.show_gutter,
 1547            show_line_numbers: self.show_line_numbers,
 1548            show_git_diff_gutter: self.show_git_diff_gutter,
 1549            show_code_actions: self.show_code_actions,
 1550            show_runnables: self.show_runnables,
 1551            git_blame_gutter_max_author_length,
 1552            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1553            scroll_anchor: self.scroll_manager.anchor(),
 1554            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1555            placeholder_text: self.placeholder_text.clone(),
 1556            diff_map: self.diff_map.snapshot(),
 1557            is_focused: self.focus_handle.is_focused(cx),
 1558            current_line_highlight: self
 1559                .current_line_highlight
 1560                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1561            gutter_hovered: self.gutter_hovered,
 1562        }
 1563    }
 1564
 1565    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1566        self.buffer.read(cx).language_at(point, cx)
 1567    }
 1568
 1569    pub fn file_at<T: ToOffset>(
 1570        &self,
 1571        point: T,
 1572        cx: &AppContext,
 1573    ) -> Option<Arc<dyn language::File>> {
 1574        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1575    }
 1576
 1577    pub fn active_excerpt(
 1578        &self,
 1579        cx: &AppContext,
 1580    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1581        self.buffer
 1582            .read(cx)
 1583            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1584    }
 1585
 1586    pub fn mode(&self) -> EditorMode {
 1587        self.mode
 1588    }
 1589
 1590    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1591        self.collaboration_hub.as_deref()
 1592    }
 1593
 1594    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1595        self.collaboration_hub = Some(hub);
 1596    }
 1597
 1598    pub fn set_custom_context_menu(
 1599        &mut self,
 1600        f: impl 'static
 1601            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1602    ) {
 1603        self.custom_context_menu = Some(Box::new(f))
 1604    }
 1605
 1606    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1607        self.completion_provider = provider;
 1608    }
 1609
 1610    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1611        self.semantics_provider.clone()
 1612    }
 1613
 1614    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1615        self.semantics_provider = provider;
 1616    }
 1617
 1618    pub fn set_inline_completion_provider<T>(
 1619        &mut self,
 1620        provider: Option<Model<T>>,
 1621        cx: &mut ViewContext<Self>,
 1622    ) where
 1623        T: InlineCompletionProvider,
 1624    {
 1625        self.inline_completion_provider =
 1626            provider.map(|provider| RegisteredInlineCompletionProvider {
 1627                _subscription: cx.observe(&provider, |this, _, cx| {
 1628                    if this.focus_handle.is_focused(cx) {
 1629                        this.update_visible_inline_completion(cx);
 1630                    }
 1631                }),
 1632                provider: Arc::new(provider),
 1633            });
 1634        self.refresh_inline_completion(false, false, cx);
 1635    }
 1636
 1637    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1638        self.placeholder_text.as_deref()
 1639    }
 1640
 1641    pub fn set_placeholder_text(
 1642        &mut self,
 1643        placeholder_text: impl Into<Arc<str>>,
 1644        cx: &mut ViewContext<Self>,
 1645    ) {
 1646        let placeholder_text = Some(placeholder_text.into());
 1647        if self.placeholder_text != placeholder_text {
 1648            self.placeholder_text = placeholder_text;
 1649            cx.notify();
 1650        }
 1651    }
 1652
 1653    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1654        self.cursor_shape = cursor_shape;
 1655
 1656        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1657        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1658
 1659        cx.notify();
 1660    }
 1661
 1662    pub fn set_current_line_highlight(
 1663        &mut self,
 1664        current_line_highlight: Option<CurrentLineHighlight>,
 1665    ) {
 1666        self.current_line_highlight = current_line_highlight;
 1667    }
 1668
 1669    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1670        self.collapse_matches = collapse_matches;
 1671    }
 1672
 1673    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1674        let buffers = self.buffer.read(cx).all_buffers();
 1675        let Some(lsp_store) = self.lsp_store(cx) else {
 1676            return;
 1677        };
 1678        lsp_store.update(cx, |lsp_store, cx| {
 1679            for buffer in buffers {
 1680                self.registered_buffers
 1681                    .entry(buffer.read(cx).remote_id())
 1682                    .or_insert_with(|| {
 1683                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1684                    });
 1685            }
 1686        })
 1687    }
 1688
 1689    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1690        if self.collapse_matches {
 1691            return range.start..range.start;
 1692        }
 1693        range.clone()
 1694    }
 1695
 1696    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1697        if self.display_map.read(cx).clip_at_line_ends != clip {
 1698            self.display_map
 1699                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1700        }
 1701    }
 1702
 1703    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1704        self.input_enabled = input_enabled;
 1705    }
 1706
 1707    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1708        self.enable_inline_completions = enabled;
 1709    }
 1710
 1711    pub fn set_autoindent(&mut self, autoindent: bool) {
 1712        if autoindent {
 1713            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1714        } else {
 1715            self.autoindent_mode = None;
 1716        }
 1717    }
 1718
 1719    pub fn read_only(&self, cx: &AppContext) -> bool {
 1720        self.read_only || self.buffer.read(cx).read_only()
 1721    }
 1722
 1723    pub fn set_read_only(&mut self, read_only: bool) {
 1724        self.read_only = read_only;
 1725    }
 1726
 1727    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1728        self.use_autoclose = autoclose;
 1729    }
 1730
 1731    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1732        self.use_auto_surround = auto_surround;
 1733    }
 1734
 1735    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1736        self.auto_replace_emoji_shortcode = auto_replace;
 1737    }
 1738
 1739    pub fn toggle_inline_completions(
 1740        &mut self,
 1741        _: &ToggleInlineCompletions,
 1742        cx: &mut ViewContext<Self>,
 1743    ) {
 1744        if self.show_inline_completions_override.is_some() {
 1745            self.set_show_inline_completions(None, cx);
 1746        } else {
 1747            let cursor = self.selections.newest_anchor().head();
 1748            if let Some((buffer, cursor_buffer_position)) =
 1749                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1750            {
 1751                let show_inline_completions =
 1752                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1753                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1754            }
 1755        }
 1756    }
 1757
 1758    pub fn set_show_inline_completions(
 1759        &mut self,
 1760        show_inline_completions: Option<bool>,
 1761        cx: &mut ViewContext<Self>,
 1762    ) {
 1763        self.show_inline_completions_override = show_inline_completions;
 1764        self.refresh_inline_completion(false, true, cx);
 1765    }
 1766
 1767    fn should_show_inline_completions(
 1768        &self,
 1769        buffer: &Model<Buffer>,
 1770        buffer_position: language::Anchor,
 1771        cx: &AppContext,
 1772    ) -> bool {
 1773        if !self.snippet_stack.is_empty() {
 1774            return false;
 1775        }
 1776
 1777        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1778            return false;
 1779        }
 1780
 1781        if let Some(provider) = self.inline_completion_provider() {
 1782            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1783                show_inline_completions
 1784            } else {
 1785                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1786            }
 1787        } else {
 1788            false
 1789        }
 1790    }
 1791
 1792    fn inline_completions_disabled_in_scope(
 1793        &self,
 1794        buffer: &Model<Buffer>,
 1795        buffer_position: language::Anchor,
 1796        cx: &AppContext,
 1797    ) -> bool {
 1798        let snapshot = buffer.read(cx).snapshot();
 1799        let settings = snapshot.settings_at(buffer_position, cx);
 1800
 1801        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1802            return false;
 1803        };
 1804
 1805        scope.override_name().map_or(false, |scope_name| {
 1806            settings
 1807                .inline_completions_disabled_in
 1808                .iter()
 1809                .any(|s| s == scope_name)
 1810        })
 1811    }
 1812
 1813    pub fn set_use_modal_editing(&mut self, to: bool) {
 1814        self.use_modal_editing = to;
 1815    }
 1816
 1817    pub fn use_modal_editing(&self) -> bool {
 1818        self.use_modal_editing
 1819    }
 1820
 1821    fn selections_did_change(
 1822        &mut self,
 1823        local: bool,
 1824        old_cursor_position: &Anchor,
 1825        show_completions: bool,
 1826        cx: &mut ViewContext<Self>,
 1827    ) {
 1828        cx.invalidate_character_coordinates();
 1829
 1830        // Copy selections to primary selection buffer
 1831        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1832        if local {
 1833            let selections = self.selections.all::<usize>(cx);
 1834            let buffer_handle = self.buffer.read(cx).read(cx);
 1835
 1836            let mut text = String::new();
 1837            for (index, selection) in selections.iter().enumerate() {
 1838                let text_for_selection = buffer_handle
 1839                    .text_for_range(selection.start..selection.end)
 1840                    .collect::<String>();
 1841
 1842                text.push_str(&text_for_selection);
 1843                if index != selections.len() - 1 {
 1844                    text.push('\n');
 1845                }
 1846            }
 1847
 1848            if !text.is_empty() {
 1849                cx.write_to_primary(ClipboardItem::new_string(text));
 1850            }
 1851        }
 1852
 1853        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1854            self.buffer.update(cx, |buffer, cx| {
 1855                buffer.set_active_selections(
 1856                    &self.selections.disjoint_anchors(),
 1857                    self.selections.line_mode,
 1858                    self.cursor_shape,
 1859                    cx,
 1860                )
 1861            });
 1862        }
 1863        let display_map = self
 1864            .display_map
 1865            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1866        let buffer = &display_map.buffer_snapshot;
 1867        self.add_selections_state = None;
 1868        self.select_next_state = None;
 1869        self.select_prev_state = None;
 1870        self.select_larger_syntax_node_stack.clear();
 1871        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1872        self.snippet_stack
 1873            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1874        self.take_rename(false, cx);
 1875
 1876        let new_cursor_position = self.selections.newest_anchor().head();
 1877
 1878        self.push_to_nav_history(
 1879            *old_cursor_position,
 1880            Some(new_cursor_position.to_point(buffer)),
 1881            cx,
 1882        );
 1883
 1884        if local {
 1885            let new_cursor_position = self.selections.newest_anchor().head();
 1886            let mut context_menu = self.context_menu.borrow_mut();
 1887            let completion_menu = match context_menu.as_ref() {
 1888                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1889                _ => {
 1890                    *context_menu = None;
 1891                    None
 1892                }
 1893            };
 1894
 1895            if let Some(completion_menu) = completion_menu {
 1896                let cursor_position = new_cursor_position.to_offset(buffer);
 1897                let (word_range, kind) =
 1898                    buffer.surrounding_word(completion_menu.initial_position, true);
 1899                if kind == Some(CharKind::Word)
 1900                    && word_range.to_inclusive().contains(&cursor_position)
 1901                {
 1902                    let mut completion_menu = completion_menu.clone();
 1903                    drop(context_menu);
 1904
 1905                    let query = Self::completion_query(buffer, cursor_position);
 1906                    cx.spawn(move |this, mut cx| async move {
 1907                        completion_menu
 1908                            .filter(query.as_deref(), cx.background_executor().clone())
 1909                            .await;
 1910
 1911                        this.update(&mut cx, |this, cx| {
 1912                            let mut context_menu = this.context_menu.borrow_mut();
 1913                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1914                            else {
 1915                                return;
 1916                            };
 1917
 1918                            if menu.id > completion_menu.id {
 1919                                return;
 1920                            }
 1921
 1922                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1923                            drop(context_menu);
 1924                            cx.notify();
 1925                        })
 1926                    })
 1927                    .detach();
 1928
 1929                    if show_completions {
 1930                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1931                    }
 1932                } else {
 1933                    drop(context_menu);
 1934                    self.hide_context_menu(cx);
 1935                }
 1936            } else {
 1937                drop(context_menu);
 1938            }
 1939
 1940            hide_hover(self, cx);
 1941
 1942            if old_cursor_position.to_display_point(&display_map).row()
 1943                != new_cursor_position.to_display_point(&display_map).row()
 1944            {
 1945                self.available_code_actions.take();
 1946            }
 1947            self.refresh_code_actions(cx);
 1948            self.refresh_document_highlights(cx);
 1949            refresh_matching_bracket_highlights(self, cx);
 1950            self.update_visible_inline_completion(cx);
 1951            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1952            if self.git_blame_inline_enabled {
 1953                self.start_inline_blame_timer(cx);
 1954            }
 1955        }
 1956
 1957        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1958        cx.emit(EditorEvent::SelectionsChanged { local });
 1959
 1960        if self.selections.disjoint_anchors().len() == 1 {
 1961            cx.emit(SearchEvent::ActiveMatchChanged)
 1962        }
 1963        cx.notify();
 1964    }
 1965
 1966    pub fn change_selections<R>(
 1967        &mut self,
 1968        autoscroll: Option<Autoscroll>,
 1969        cx: &mut ViewContext<Self>,
 1970        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1971    ) -> R {
 1972        self.change_selections_inner(autoscroll, true, cx, change)
 1973    }
 1974
 1975    pub fn change_selections_inner<R>(
 1976        &mut self,
 1977        autoscroll: Option<Autoscroll>,
 1978        request_completions: bool,
 1979        cx: &mut ViewContext<Self>,
 1980        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1981    ) -> R {
 1982        let old_cursor_position = self.selections.newest_anchor().head();
 1983        self.push_to_selection_history();
 1984
 1985        let (changed, result) = self.selections.change_with(cx, change);
 1986
 1987        if changed {
 1988            if let Some(autoscroll) = autoscroll {
 1989                self.request_autoscroll(autoscroll, cx);
 1990            }
 1991            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 1992
 1993            if self.should_open_signature_help_automatically(
 1994                &old_cursor_position,
 1995                self.signature_help_state.backspace_pressed(),
 1996                cx,
 1997            ) {
 1998                self.show_signature_help(&ShowSignatureHelp, cx);
 1999            }
 2000            self.signature_help_state.set_backspace_pressed(false);
 2001        }
 2002
 2003        result
 2004    }
 2005
 2006    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2007    where
 2008        I: IntoIterator<Item = (Range<S>, T)>,
 2009        S: ToOffset,
 2010        T: Into<Arc<str>>,
 2011    {
 2012        if self.read_only(cx) {
 2013            return;
 2014        }
 2015
 2016        self.buffer
 2017            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2018    }
 2019
 2020    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2021    where
 2022        I: IntoIterator<Item = (Range<S>, T)>,
 2023        S: ToOffset,
 2024        T: Into<Arc<str>>,
 2025    {
 2026        if self.read_only(cx) {
 2027            return;
 2028        }
 2029
 2030        self.buffer.update(cx, |buffer, cx| {
 2031            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2032        });
 2033    }
 2034
 2035    pub fn edit_with_block_indent<I, S, T>(
 2036        &mut self,
 2037        edits: I,
 2038        original_indent_columns: Vec<u32>,
 2039        cx: &mut ViewContext<Self>,
 2040    ) where
 2041        I: IntoIterator<Item = (Range<S>, T)>,
 2042        S: ToOffset,
 2043        T: Into<Arc<str>>,
 2044    {
 2045        if self.read_only(cx) {
 2046            return;
 2047        }
 2048
 2049        self.buffer.update(cx, |buffer, cx| {
 2050            buffer.edit(
 2051                edits,
 2052                Some(AutoindentMode::Block {
 2053                    original_indent_columns,
 2054                }),
 2055                cx,
 2056            )
 2057        });
 2058    }
 2059
 2060    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2061        self.hide_context_menu(cx);
 2062
 2063        match phase {
 2064            SelectPhase::Begin {
 2065                position,
 2066                add,
 2067                click_count,
 2068            } => self.begin_selection(position, add, click_count, cx),
 2069            SelectPhase::BeginColumnar {
 2070                position,
 2071                goal_column,
 2072                reset,
 2073            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2074            SelectPhase::Extend {
 2075                position,
 2076                click_count,
 2077            } => self.extend_selection(position, click_count, cx),
 2078            SelectPhase::Update {
 2079                position,
 2080                goal_column,
 2081                scroll_delta,
 2082            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2083            SelectPhase::End => self.end_selection(cx),
 2084        }
 2085    }
 2086
 2087    fn extend_selection(
 2088        &mut self,
 2089        position: DisplayPoint,
 2090        click_count: usize,
 2091        cx: &mut ViewContext<Self>,
 2092    ) {
 2093        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2094        let tail = self.selections.newest::<usize>(cx).tail();
 2095        self.begin_selection(position, false, click_count, cx);
 2096
 2097        let position = position.to_offset(&display_map, Bias::Left);
 2098        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2099
 2100        let mut pending_selection = self
 2101            .selections
 2102            .pending_anchor()
 2103            .expect("extend_selection not called with pending selection");
 2104        if position >= tail {
 2105            pending_selection.start = tail_anchor;
 2106        } else {
 2107            pending_selection.end = tail_anchor;
 2108            pending_selection.reversed = true;
 2109        }
 2110
 2111        let mut pending_mode = self.selections.pending_mode().unwrap();
 2112        match &mut pending_mode {
 2113            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2114            _ => {}
 2115        }
 2116
 2117        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2118            s.set_pending(pending_selection, pending_mode)
 2119        });
 2120    }
 2121
 2122    fn begin_selection(
 2123        &mut self,
 2124        position: DisplayPoint,
 2125        add: bool,
 2126        click_count: usize,
 2127        cx: &mut ViewContext<Self>,
 2128    ) {
 2129        if !self.focus_handle.is_focused(cx) {
 2130            self.last_focused_descendant = None;
 2131            cx.focus(&self.focus_handle);
 2132        }
 2133
 2134        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2135        let buffer = &display_map.buffer_snapshot;
 2136        let newest_selection = self.selections.newest_anchor().clone();
 2137        let position = display_map.clip_point(position, Bias::Left);
 2138
 2139        let start;
 2140        let end;
 2141        let mode;
 2142        let mut auto_scroll;
 2143        match click_count {
 2144            1 => {
 2145                start = buffer.anchor_before(position.to_point(&display_map));
 2146                end = start;
 2147                mode = SelectMode::Character;
 2148                auto_scroll = true;
 2149            }
 2150            2 => {
 2151                let range = movement::surrounding_word(&display_map, position);
 2152                start = buffer.anchor_before(range.start.to_point(&display_map));
 2153                end = buffer.anchor_before(range.end.to_point(&display_map));
 2154                mode = SelectMode::Word(start..end);
 2155                auto_scroll = true;
 2156            }
 2157            3 => {
 2158                let position = display_map
 2159                    .clip_point(position, Bias::Left)
 2160                    .to_point(&display_map);
 2161                let line_start = display_map.prev_line_boundary(position).0;
 2162                let next_line_start = buffer.clip_point(
 2163                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2164                    Bias::Left,
 2165                );
 2166                start = buffer.anchor_before(line_start);
 2167                end = buffer.anchor_before(next_line_start);
 2168                mode = SelectMode::Line(start..end);
 2169                auto_scroll = true;
 2170            }
 2171            _ => {
 2172                start = buffer.anchor_before(0);
 2173                end = buffer.anchor_before(buffer.len());
 2174                mode = SelectMode::All;
 2175                auto_scroll = false;
 2176            }
 2177        }
 2178        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2179
 2180        let point_to_delete: Option<usize> = {
 2181            let selected_points: Vec<Selection<Point>> =
 2182                self.selections.disjoint_in_range(start..end, cx);
 2183
 2184            if !add || click_count > 1 {
 2185                None
 2186            } else if !selected_points.is_empty() {
 2187                Some(selected_points[0].id)
 2188            } else {
 2189                let clicked_point_already_selected =
 2190                    self.selections.disjoint.iter().find(|selection| {
 2191                        selection.start.to_point(buffer) == start.to_point(buffer)
 2192                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2193                    });
 2194
 2195                clicked_point_already_selected.map(|selection| selection.id)
 2196            }
 2197        };
 2198
 2199        let selections_count = self.selections.count();
 2200
 2201        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2202            if let Some(point_to_delete) = point_to_delete {
 2203                s.delete(point_to_delete);
 2204
 2205                if selections_count == 1 {
 2206                    s.set_pending_anchor_range(start..end, mode);
 2207                }
 2208            } else {
 2209                if !add {
 2210                    s.clear_disjoint();
 2211                } else if click_count > 1 {
 2212                    s.delete(newest_selection.id)
 2213                }
 2214
 2215                s.set_pending_anchor_range(start..end, mode);
 2216            }
 2217        });
 2218    }
 2219
 2220    fn begin_columnar_selection(
 2221        &mut self,
 2222        position: DisplayPoint,
 2223        goal_column: u32,
 2224        reset: bool,
 2225        cx: &mut ViewContext<Self>,
 2226    ) {
 2227        if !self.focus_handle.is_focused(cx) {
 2228            self.last_focused_descendant = None;
 2229            cx.focus(&self.focus_handle);
 2230        }
 2231
 2232        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2233
 2234        if reset {
 2235            let pointer_position = display_map
 2236                .buffer_snapshot
 2237                .anchor_before(position.to_point(&display_map));
 2238
 2239            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2240                s.clear_disjoint();
 2241                s.set_pending_anchor_range(
 2242                    pointer_position..pointer_position,
 2243                    SelectMode::Character,
 2244                );
 2245            });
 2246        }
 2247
 2248        let tail = self.selections.newest::<Point>(cx).tail();
 2249        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2250
 2251        if !reset {
 2252            self.select_columns(
 2253                tail.to_display_point(&display_map),
 2254                position,
 2255                goal_column,
 2256                &display_map,
 2257                cx,
 2258            );
 2259        }
 2260    }
 2261
 2262    fn update_selection(
 2263        &mut self,
 2264        position: DisplayPoint,
 2265        goal_column: u32,
 2266        scroll_delta: gpui::Point<f32>,
 2267        cx: &mut ViewContext<Self>,
 2268    ) {
 2269        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2270
 2271        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2272            let tail = tail.to_display_point(&display_map);
 2273            self.select_columns(tail, position, goal_column, &display_map, cx);
 2274        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2275            let buffer = self.buffer.read(cx).snapshot(cx);
 2276            let head;
 2277            let tail;
 2278            let mode = self.selections.pending_mode().unwrap();
 2279            match &mode {
 2280                SelectMode::Character => {
 2281                    head = position.to_point(&display_map);
 2282                    tail = pending.tail().to_point(&buffer);
 2283                }
 2284                SelectMode::Word(original_range) => {
 2285                    let original_display_range = original_range.start.to_display_point(&display_map)
 2286                        ..original_range.end.to_display_point(&display_map);
 2287                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2288                        ..original_display_range.end.to_point(&display_map);
 2289                    if movement::is_inside_word(&display_map, position)
 2290                        || original_display_range.contains(&position)
 2291                    {
 2292                        let word_range = movement::surrounding_word(&display_map, position);
 2293                        if word_range.start < original_display_range.start {
 2294                            head = word_range.start.to_point(&display_map);
 2295                        } else {
 2296                            head = word_range.end.to_point(&display_map);
 2297                        }
 2298                    } else {
 2299                        head = position.to_point(&display_map);
 2300                    }
 2301
 2302                    if head <= original_buffer_range.start {
 2303                        tail = original_buffer_range.end;
 2304                    } else {
 2305                        tail = original_buffer_range.start;
 2306                    }
 2307                }
 2308                SelectMode::Line(original_range) => {
 2309                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2310
 2311                    let position = display_map
 2312                        .clip_point(position, Bias::Left)
 2313                        .to_point(&display_map);
 2314                    let line_start = display_map.prev_line_boundary(position).0;
 2315                    let next_line_start = buffer.clip_point(
 2316                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2317                        Bias::Left,
 2318                    );
 2319
 2320                    if line_start < original_range.start {
 2321                        head = line_start
 2322                    } else {
 2323                        head = next_line_start
 2324                    }
 2325
 2326                    if head <= original_range.start {
 2327                        tail = original_range.end;
 2328                    } else {
 2329                        tail = original_range.start;
 2330                    }
 2331                }
 2332                SelectMode::All => {
 2333                    return;
 2334                }
 2335            };
 2336
 2337            if head < tail {
 2338                pending.start = buffer.anchor_before(head);
 2339                pending.end = buffer.anchor_before(tail);
 2340                pending.reversed = true;
 2341            } else {
 2342                pending.start = buffer.anchor_before(tail);
 2343                pending.end = buffer.anchor_before(head);
 2344                pending.reversed = false;
 2345            }
 2346
 2347            self.change_selections(None, cx, |s| {
 2348                s.set_pending(pending, mode);
 2349            });
 2350        } else {
 2351            log::error!("update_selection dispatched with no pending selection");
 2352            return;
 2353        }
 2354
 2355        self.apply_scroll_delta(scroll_delta, cx);
 2356        cx.notify();
 2357    }
 2358
 2359    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2360        self.columnar_selection_tail.take();
 2361        if self.selections.pending_anchor().is_some() {
 2362            let selections = self.selections.all::<usize>(cx);
 2363            self.change_selections(None, cx, |s| {
 2364                s.select(selections);
 2365                s.clear_pending();
 2366            });
 2367        }
 2368    }
 2369
 2370    fn select_columns(
 2371        &mut self,
 2372        tail: DisplayPoint,
 2373        head: DisplayPoint,
 2374        goal_column: u32,
 2375        display_map: &DisplaySnapshot,
 2376        cx: &mut ViewContext<Self>,
 2377    ) {
 2378        let start_row = cmp::min(tail.row(), head.row());
 2379        let end_row = cmp::max(tail.row(), head.row());
 2380        let start_column = cmp::min(tail.column(), goal_column);
 2381        let end_column = cmp::max(tail.column(), goal_column);
 2382        let reversed = start_column < tail.column();
 2383
 2384        let selection_ranges = (start_row.0..=end_row.0)
 2385            .map(DisplayRow)
 2386            .filter_map(|row| {
 2387                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2388                    let start = display_map
 2389                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2390                        .to_point(display_map);
 2391                    let end = display_map
 2392                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2393                        .to_point(display_map);
 2394                    if reversed {
 2395                        Some(end..start)
 2396                    } else {
 2397                        Some(start..end)
 2398                    }
 2399                } else {
 2400                    None
 2401                }
 2402            })
 2403            .collect::<Vec<_>>();
 2404
 2405        self.change_selections(None, cx, |s| {
 2406            s.select_ranges(selection_ranges);
 2407        });
 2408        cx.notify();
 2409    }
 2410
 2411    pub fn has_pending_nonempty_selection(&self) -> bool {
 2412        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2413            Some(Selection { start, end, .. }) => start != end,
 2414            None => false,
 2415        };
 2416
 2417        pending_nonempty_selection
 2418            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2419    }
 2420
 2421    pub fn has_pending_selection(&self) -> bool {
 2422        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2423    }
 2424
 2425    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2426        if self.clear_expanded_diff_hunks(cx) {
 2427            cx.notify();
 2428            return;
 2429        }
 2430        if self.dismiss_menus_and_popups(true, cx) {
 2431            return;
 2432        }
 2433
 2434        if self.mode == EditorMode::Full
 2435            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2436        {
 2437            return;
 2438        }
 2439
 2440        cx.propagate();
 2441    }
 2442
 2443    pub fn dismiss_menus_and_popups(
 2444        &mut self,
 2445        should_report_inline_completion_event: bool,
 2446        cx: &mut ViewContext<Self>,
 2447    ) -> bool {
 2448        if self.take_rename(false, cx).is_some() {
 2449            return true;
 2450        }
 2451
 2452        if hide_hover(self, cx) {
 2453            return true;
 2454        }
 2455
 2456        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2457            return true;
 2458        }
 2459
 2460        if self.hide_context_menu(cx).is_some() {
 2461            return true;
 2462        }
 2463
 2464        if self.mouse_context_menu.take().is_some() {
 2465            return true;
 2466        }
 2467
 2468        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2469            return true;
 2470        }
 2471
 2472        if self.snippet_stack.pop().is_some() {
 2473            return true;
 2474        }
 2475
 2476        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2477            self.dismiss_diagnostics(cx);
 2478            return true;
 2479        }
 2480
 2481        false
 2482    }
 2483
 2484    fn linked_editing_ranges_for(
 2485        &self,
 2486        selection: Range<text::Anchor>,
 2487        cx: &AppContext,
 2488    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2489        if self.linked_edit_ranges.is_empty() {
 2490            return None;
 2491        }
 2492        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2493            selection.end.buffer_id.and_then(|end_buffer_id| {
 2494                if selection.start.buffer_id != Some(end_buffer_id) {
 2495                    return None;
 2496                }
 2497                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2498                let snapshot = buffer.read(cx).snapshot();
 2499                self.linked_edit_ranges
 2500                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2501                    .map(|ranges| (ranges, snapshot, buffer))
 2502            })?;
 2503        use text::ToOffset as TO;
 2504        // find offset from the start of current range to current cursor position
 2505        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2506
 2507        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2508        let start_difference = start_offset - start_byte_offset;
 2509        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2510        let end_difference = end_offset - start_byte_offset;
 2511        // Current range has associated linked ranges.
 2512        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2513        for range in linked_ranges.iter() {
 2514            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2515            let end_offset = start_offset + end_difference;
 2516            let start_offset = start_offset + start_difference;
 2517            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2518                continue;
 2519            }
 2520            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2521                if s.start.buffer_id != selection.start.buffer_id
 2522                    || s.end.buffer_id != selection.end.buffer_id
 2523                {
 2524                    return false;
 2525                }
 2526                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2527                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2528            }) {
 2529                continue;
 2530            }
 2531            let start = buffer_snapshot.anchor_after(start_offset);
 2532            let end = buffer_snapshot.anchor_after(end_offset);
 2533            linked_edits
 2534                .entry(buffer.clone())
 2535                .or_default()
 2536                .push(start..end);
 2537        }
 2538        Some(linked_edits)
 2539    }
 2540
 2541    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2542        let text: Arc<str> = text.into();
 2543
 2544        if self.read_only(cx) {
 2545            return;
 2546        }
 2547
 2548        let selections = self.selections.all_adjusted(cx);
 2549        let mut bracket_inserted = false;
 2550        let mut edits = Vec::new();
 2551        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2552        let mut new_selections = Vec::with_capacity(selections.len());
 2553        let mut new_autoclose_regions = Vec::new();
 2554        let snapshot = self.buffer.read(cx).read(cx);
 2555
 2556        for (selection, autoclose_region) in
 2557            self.selections_with_autoclose_regions(selections, &snapshot)
 2558        {
 2559            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2560                // Determine if the inserted text matches the opening or closing
 2561                // bracket of any of this language's bracket pairs.
 2562                let mut bracket_pair = None;
 2563                let mut is_bracket_pair_start = false;
 2564                let mut is_bracket_pair_end = false;
 2565                if !text.is_empty() {
 2566                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2567                    //  and they are removing the character that triggered IME popup.
 2568                    for (pair, enabled) in scope.brackets() {
 2569                        if !pair.close && !pair.surround {
 2570                            continue;
 2571                        }
 2572
 2573                        if enabled && pair.start.ends_with(text.as_ref()) {
 2574                            let prefix_len = pair.start.len() - text.len();
 2575                            let preceding_text_matches_prefix = prefix_len == 0
 2576                                || (selection.start.column >= (prefix_len as u32)
 2577                                    && snapshot.contains_str_at(
 2578                                        Point::new(
 2579                                            selection.start.row,
 2580                                            selection.start.column - (prefix_len as u32),
 2581                                        ),
 2582                                        &pair.start[..prefix_len],
 2583                                    ));
 2584                            if preceding_text_matches_prefix {
 2585                                bracket_pair = Some(pair.clone());
 2586                                is_bracket_pair_start = true;
 2587                                break;
 2588                            }
 2589                        }
 2590                        if pair.end.as_str() == text.as_ref() {
 2591                            bracket_pair = Some(pair.clone());
 2592                            is_bracket_pair_end = true;
 2593                            break;
 2594                        }
 2595                    }
 2596                }
 2597
 2598                if let Some(bracket_pair) = bracket_pair {
 2599                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2600                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2601                    let auto_surround =
 2602                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2603                    if selection.is_empty() {
 2604                        if is_bracket_pair_start {
 2605                            // If the inserted text is a suffix of an opening bracket and the
 2606                            // selection is preceded by the rest of the opening bracket, then
 2607                            // insert the closing bracket.
 2608                            let following_text_allows_autoclose = snapshot
 2609                                .chars_at(selection.start)
 2610                                .next()
 2611                                .map_or(true, |c| scope.should_autoclose_before(c));
 2612
 2613                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2614                                && bracket_pair.start.len() == 1
 2615                            {
 2616                                let target = bracket_pair.start.chars().next().unwrap();
 2617                                let current_line_count = snapshot
 2618                                    .reversed_chars_at(selection.start)
 2619                                    .take_while(|&c| c != '\n')
 2620                                    .filter(|&c| c == target)
 2621                                    .count();
 2622                                current_line_count % 2 == 1
 2623                            } else {
 2624                                false
 2625                            };
 2626
 2627                            if autoclose
 2628                                && bracket_pair.close
 2629                                && following_text_allows_autoclose
 2630                                && !is_closing_quote
 2631                            {
 2632                                let anchor = snapshot.anchor_before(selection.end);
 2633                                new_selections.push((selection.map(|_| anchor), text.len()));
 2634                                new_autoclose_regions.push((
 2635                                    anchor,
 2636                                    text.len(),
 2637                                    selection.id,
 2638                                    bracket_pair.clone(),
 2639                                ));
 2640                                edits.push((
 2641                                    selection.range(),
 2642                                    format!("{}{}", text, bracket_pair.end).into(),
 2643                                ));
 2644                                bracket_inserted = true;
 2645                                continue;
 2646                            }
 2647                        }
 2648
 2649                        if let Some(region) = autoclose_region {
 2650                            // If the selection is followed by an auto-inserted closing bracket,
 2651                            // then don't insert that closing bracket again; just move the selection
 2652                            // past the closing bracket.
 2653                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2654                                && text.as_ref() == region.pair.end.as_str();
 2655                            if should_skip {
 2656                                let anchor = snapshot.anchor_after(selection.end);
 2657                                new_selections
 2658                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2659                                continue;
 2660                            }
 2661                        }
 2662
 2663                        let always_treat_brackets_as_autoclosed = snapshot
 2664                            .settings_at(selection.start, cx)
 2665                            .always_treat_brackets_as_autoclosed;
 2666                        if always_treat_brackets_as_autoclosed
 2667                            && is_bracket_pair_end
 2668                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2669                        {
 2670                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2671                            // and the inserted text is a closing bracket and the selection is followed
 2672                            // by the closing bracket then move the selection past the closing bracket.
 2673                            let anchor = snapshot.anchor_after(selection.end);
 2674                            new_selections.push((selection.map(|_| anchor), text.len()));
 2675                            continue;
 2676                        }
 2677                    }
 2678                    // If an opening bracket is 1 character long and is typed while
 2679                    // text is selected, then surround that text with the bracket pair.
 2680                    else if auto_surround
 2681                        && bracket_pair.surround
 2682                        && is_bracket_pair_start
 2683                        && bracket_pair.start.chars().count() == 1
 2684                    {
 2685                        edits.push((selection.start..selection.start, text.clone()));
 2686                        edits.push((
 2687                            selection.end..selection.end,
 2688                            bracket_pair.end.as_str().into(),
 2689                        ));
 2690                        bracket_inserted = true;
 2691                        new_selections.push((
 2692                            Selection {
 2693                                id: selection.id,
 2694                                start: snapshot.anchor_after(selection.start),
 2695                                end: snapshot.anchor_before(selection.end),
 2696                                reversed: selection.reversed,
 2697                                goal: selection.goal,
 2698                            },
 2699                            0,
 2700                        ));
 2701                        continue;
 2702                    }
 2703                }
 2704            }
 2705
 2706            if self.auto_replace_emoji_shortcode
 2707                && selection.is_empty()
 2708                && text.as_ref().ends_with(':')
 2709            {
 2710                if let Some(possible_emoji_short_code) =
 2711                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2712                {
 2713                    if !possible_emoji_short_code.is_empty() {
 2714                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2715                            let emoji_shortcode_start = Point::new(
 2716                                selection.start.row,
 2717                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2718                            );
 2719
 2720                            // Remove shortcode from buffer
 2721                            edits.push((
 2722                                emoji_shortcode_start..selection.start,
 2723                                "".to_string().into(),
 2724                            ));
 2725                            new_selections.push((
 2726                                Selection {
 2727                                    id: selection.id,
 2728                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2729                                    end: snapshot.anchor_before(selection.start),
 2730                                    reversed: selection.reversed,
 2731                                    goal: selection.goal,
 2732                                },
 2733                                0,
 2734                            ));
 2735
 2736                            // Insert emoji
 2737                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2738                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2739                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2740
 2741                            continue;
 2742                        }
 2743                    }
 2744                }
 2745            }
 2746
 2747            // If not handling any auto-close operation, then just replace the selected
 2748            // text with the given input and move the selection to the end of the
 2749            // newly inserted text.
 2750            let anchor = snapshot.anchor_after(selection.end);
 2751            if !self.linked_edit_ranges.is_empty() {
 2752                let start_anchor = snapshot.anchor_before(selection.start);
 2753
 2754                let is_word_char = text.chars().next().map_or(true, |char| {
 2755                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2756                    classifier.is_word(char)
 2757                });
 2758
 2759                if is_word_char {
 2760                    if let Some(ranges) = self
 2761                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2762                    {
 2763                        for (buffer, edits) in ranges {
 2764                            linked_edits
 2765                                .entry(buffer.clone())
 2766                                .or_default()
 2767                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2768                        }
 2769                    }
 2770                }
 2771            }
 2772
 2773            new_selections.push((selection.map(|_| anchor), 0));
 2774            edits.push((selection.start..selection.end, text.clone()));
 2775        }
 2776
 2777        drop(snapshot);
 2778
 2779        self.transact(cx, |this, cx| {
 2780            this.buffer.update(cx, |buffer, cx| {
 2781                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2782            });
 2783            for (buffer, edits) in linked_edits {
 2784                buffer.update(cx, |buffer, cx| {
 2785                    let snapshot = buffer.snapshot();
 2786                    let edits = edits
 2787                        .into_iter()
 2788                        .map(|(range, text)| {
 2789                            use text::ToPoint as TP;
 2790                            let end_point = TP::to_point(&range.end, &snapshot);
 2791                            let start_point = TP::to_point(&range.start, &snapshot);
 2792                            (start_point..end_point, text)
 2793                        })
 2794                        .sorted_by_key(|(range, _)| range.start)
 2795                        .collect::<Vec<_>>();
 2796                    buffer.edit(edits, None, cx);
 2797                })
 2798            }
 2799            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2800            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2801            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2802            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2803                .zip(new_selection_deltas)
 2804                .map(|(selection, delta)| Selection {
 2805                    id: selection.id,
 2806                    start: selection.start + delta,
 2807                    end: selection.end + delta,
 2808                    reversed: selection.reversed,
 2809                    goal: SelectionGoal::None,
 2810                })
 2811                .collect::<Vec<_>>();
 2812
 2813            let mut i = 0;
 2814            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2815                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2816                let start = map.buffer_snapshot.anchor_before(position);
 2817                let end = map.buffer_snapshot.anchor_after(position);
 2818                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2819                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2820                        Ordering::Less => i += 1,
 2821                        Ordering::Greater => break,
 2822                        Ordering::Equal => {
 2823                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2824                                Ordering::Less => i += 1,
 2825                                Ordering::Equal => break,
 2826                                Ordering::Greater => break,
 2827                            }
 2828                        }
 2829                    }
 2830                }
 2831                this.autoclose_regions.insert(
 2832                    i,
 2833                    AutocloseRegion {
 2834                        selection_id,
 2835                        range: start..end,
 2836                        pair,
 2837                    },
 2838                );
 2839            }
 2840
 2841            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2842                s.select(new_selections)
 2843            });
 2844
 2845            if !bracket_inserted {
 2846                if let Some(on_type_format_task) =
 2847                    this.trigger_on_type_formatting(text.to_string(), cx)
 2848                {
 2849                    on_type_format_task.detach_and_log_err(cx);
 2850                }
 2851            }
 2852
 2853            let editor_settings = EditorSettings::get_global(cx);
 2854            if bracket_inserted
 2855                && (editor_settings.auto_signature_help
 2856                    || editor_settings.show_signature_help_after_edits)
 2857            {
 2858                this.show_signature_help(&ShowSignatureHelp, cx);
 2859            }
 2860
 2861            this.trigger_completion_on_input(&text, true, cx);
 2862            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2863            this.refresh_inline_completion(true, false, cx);
 2864        });
 2865    }
 2866
 2867    fn find_possible_emoji_shortcode_at_position(
 2868        snapshot: &MultiBufferSnapshot,
 2869        position: Point,
 2870    ) -> Option<String> {
 2871        let mut chars = Vec::new();
 2872        let mut found_colon = false;
 2873        for char in snapshot.reversed_chars_at(position).take(100) {
 2874            // Found a possible emoji shortcode in the middle of the buffer
 2875            if found_colon {
 2876                if char.is_whitespace() {
 2877                    chars.reverse();
 2878                    return Some(chars.iter().collect());
 2879                }
 2880                // If the previous character is not a whitespace, we are in the middle of a word
 2881                // and we only want to complete the shortcode if the word is made up of other emojis
 2882                let mut containing_word = String::new();
 2883                for ch in snapshot
 2884                    .reversed_chars_at(position)
 2885                    .skip(chars.len() + 1)
 2886                    .take(100)
 2887                {
 2888                    if ch.is_whitespace() {
 2889                        break;
 2890                    }
 2891                    containing_word.push(ch);
 2892                }
 2893                let containing_word = containing_word.chars().rev().collect::<String>();
 2894                if util::word_consists_of_emojis(containing_word.as_str()) {
 2895                    chars.reverse();
 2896                    return Some(chars.iter().collect());
 2897                }
 2898            }
 2899
 2900            if char.is_whitespace() || !char.is_ascii() {
 2901                return None;
 2902            }
 2903            if char == ':' {
 2904                found_colon = true;
 2905            } else {
 2906                chars.push(char);
 2907            }
 2908        }
 2909        // Found a possible emoji shortcode at the beginning of the buffer
 2910        chars.reverse();
 2911        Some(chars.iter().collect())
 2912    }
 2913
 2914    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2915        self.transact(cx, |this, cx| {
 2916            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2917                let selections = this.selections.all::<usize>(cx);
 2918                let multi_buffer = this.buffer.read(cx);
 2919                let buffer = multi_buffer.snapshot(cx);
 2920                selections
 2921                    .iter()
 2922                    .map(|selection| {
 2923                        let start_point = selection.start.to_point(&buffer);
 2924                        let mut indent =
 2925                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2926                        indent.len = cmp::min(indent.len, start_point.column);
 2927                        let start = selection.start;
 2928                        let end = selection.end;
 2929                        let selection_is_empty = start == end;
 2930                        let language_scope = buffer.language_scope_at(start);
 2931                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2932                            &language_scope
 2933                        {
 2934                            let leading_whitespace_len = buffer
 2935                                .reversed_chars_at(start)
 2936                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2937                                .map(|c| c.len_utf8())
 2938                                .sum::<usize>();
 2939
 2940                            let trailing_whitespace_len = buffer
 2941                                .chars_at(end)
 2942                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2943                                .map(|c| c.len_utf8())
 2944                                .sum::<usize>();
 2945
 2946                            let insert_extra_newline =
 2947                                language.brackets().any(|(pair, enabled)| {
 2948                                    let pair_start = pair.start.trim_end();
 2949                                    let pair_end = pair.end.trim_start();
 2950
 2951                                    enabled
 2952                                        && pair.newline
 2953                                        && buffer.contains_str_at(
 2954                                            end + trailing_whitespace_len,
 2955                                            pair_end,
 2956                                        )
 2957                                        && buffer.contains_str_at(
 2958                                            (start - leading_whitespace_len)
 2959                                                .saturating_sub(pair_start.len()),
 2960                                            pair_start,
 2961                                        )
 2962                                });
 2963
 2964                            // Comment extension on newline is allowed only for cursor selections
 2965                            let comment_delimiter = maybe!({
 2966                                if !selection_is_empty {
 2967                                    return None;
 2968                                }
 2969
 2970                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 2971                                    return None;
 2972                                }
 2973
 2974                                let delimiters = language.line_comment_prefixes();
 2975                                let max_len_of_delimiter =
 2976                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 2977                                let (snapshot, range) =
 2978                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 2979
 2980                                let mut index_of_first_non_whitespace = 0;
 2981                                let comment_candidate = snapshot
 2982                                    .chars_for_range(range)
 2983                                    .skip_while(|c| {
 2984                                        let should_skip = c.is_whitespace();
 2985                                        if should_skip {
 2986                                            index_of_first_non_whitespace += 1;
 2987                                        }
 2988                                        should_skip
 2989                                    })
 2990                                    .take(max_len_of_delimiter)
 2991                                    .collect::<String>();
 2992                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 2993                                    comment_candidate.starts_with(comment_prefix.as_ref())
 2994                                })?;
 2995                                let cursor_is_placed_after_comment_marker =
 2996                                    index_of_first_non_whitespace + comment_prefix.len()
 2997                                        <= start_point.column as usize;
 2998                                if cursor_is_placed_after_comment_marker {
 2999                                    Some(comment_prefix.clone())
 3000                                } else {
 3001                                    None
 3002                                }
 3003                            });
 3004                            (comment_delimiter, insert_extra_newline)
 3005                        } else {
 3006                            (None, false)
 3007                        };
 3008
 3009                        let capacity_for_delimiter = comment_delimiter
 3010                            .as_deref()
 3011                            .map(str::len)
 3012                            .unwrap_or_default();
 3013                        let mut new_text =
 3014                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3015                        new_text.push('\n');
 3016                        new_text.extend(indent.chars());
 3017                        if let Some(delimiter) = &comment_delimiter {
 3018                            new_text.push_str(delimiter);
 3019                        }
 3020                        if insert_extra_newline {
 3021                            new_text = new_text.repeat(2);
 3022                        }
 3023
 3024                        let anchor = buffer.anchor_after(end);
 3025                        let new_selection = selection.map(|_| anchor);
 3026                        (
 3027                            (start..end, new_text),
 3028                            (insert_extra_newline, new_selection),
 3029                        )
 3030                    })
 3031                    .unzip()
 3032            };
 3033
 3034            this.edit_with_autoindent(edits, cx);
 3035            let buffer = this.buffer.read(cx).snapshot(cx);
 3036            let new_selections = selection_fixup_info
 3037                .into_iter()
 3038                .map(|(extra_newline_inserted, new_selection)| {
 3039                    let mut cursor = new_selection.end.to_point(&buffer);
 3040                    if extra_newline_inserted {
 3041                        cursor.row -= 1;
 3042                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3043                    }
 3044                    new_selection.map(|_| cursor)
 3045                })
 3046                .collect();
 3047
 3048            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3049            this.refresh_inline_completion(true, false, cx);
 3050        });
 3051    }
 3052
 3053    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3054        let buffer = self.buffer.read(cx);
 3055        let snapshot = buffer.snapshot(cx);
 3056
 3057        let mut edits = Vec::new();
 3058        let mut rows = Vec::new();
 3059
 3060        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3061            let cursor = selection.head();
 3062            let row = cursor.row;
 3063
 3064            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3065
 3066            let newline = "\n".to_string();
 3067            edits.push((start_of_line..start_of_line, newline));
 3068
 3069            rows.push(row + rows_inserted as u32);
 3070        }
 3071
 3072        self.transact(cx, |editor, cx| {
 3073            editor.edit(edits, cx);
 3074
 3075            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3076                let mut index = 0;
 3077                s.move_cursors_with(|map, _, _| {
 3078                    let row = rows[index];
 3079                    index += 1;
 3080
 3081                    let point = Point::new(row, 0);
 3082                    let boundary = map.next_line_boundary(point).1;
 3083                    let clipped = map.clip_point(boundary, Bias::Left);
 3084
 3085                    (clipped, SelectionGoal::None)
 3086                });
 3087            });
 3088
 3089            let mut indent_edits = Vec::new();
 3090            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3091            for row in rows {
 3092                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3093                for (row, indent) in indents {
 3094                    if indent.len == 0 {
 3095                        continue;
 3096                    }
 3097
 3098                    let text = match indent.kind {
 3099                        IndentKind::Space => " ".repeat(indent.len as usize),
 3100                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3101                    };
 3102                    let point = Point::new(row.0, 0);
 3103                    indent_edits.push((point..point, text));
 3104                }
 3105            }
 3106            editor.edit(indent_edits, cx);
 3107        });
 3108    }
 3109
 3110    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3111        let buffer = self.buffer.read(cx);
 3112        let snapshot = buffer.snapshot(cx);
 3113
 3114        let mut edits = Vec::new();
 3115        let mut rows = Vec::new();
 3116        let mut rows_inserted = 0;
 3117
 3118        for selection in self.selections.all_adjusted(cx) {
 3119            let cursor = selection.head();
 3120            let row = cursor.row;
 3121
 3122            let point = Point::new(row + 1, 0);
 3123            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3124
 3125            let newline = "\n".to_string();
 3126            edits.push((start_of_line..start_of_line, newline));
 3127
 3128            rows_inserted += 1;
 3129            rows.push(row + rows_inserted);
 3130        }
 3131
 3132        self.transact(cx, |editor, cx| {
 3133            editor.edit(edits, cx);
 3134
 3135            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3136                let mut index = 0;
 3137                s.move_cursors_with(|map, _, _| {
 3138                    let row = rows[index];
 3139                    index += 1;
 3140
 3141                    let point = Point::new(row, 0);
 3142                    let boundary = map.next_line_boundary(point).1;
 3143                    let clipped = map.clip_point(boundary, Bias::Left);
 3144
 3145                    (clipped, SelectionGoal::None)
 3146                });
 3147            });
 3148
 3149            let mut indent_edits = Vec::new();
 3150            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3151            for row in rows {
 3152                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3153                for (row, indent) in indents {
 3154                    if indent.len == 0 {
 3155                        continue;
 3156                    }
 3157
 3158                    let text = match indent.kind {
 3159                        IndentKind::Space => " ".repeat(indent.len as usize),
 3160                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3161                    };
 3162                    let point = Point::new(row.0, 0);
 3163                    indent_edits.push((point..point, text));
 3164                }
 3165            }
 3166            editor.edit(indent_edits, cx);
 3167        });
 3168    }
 3169
 3170    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3171        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3172            original_indent_columns: Vec::new(),
 3173        });
 3174        self.insert_with_autoindent_mode(text, autoindent, cx);
 3175    }
 3176
 3177    fn insert_with_autoindent_mode(
 3178        &mut self,
 3179        text: &str,
 3180        autoindent_mode: Option<AutoindentMode>,
 3181        cx: &mut ViewContext<Self>,
 3182    ) {
 3183        if self.read_only(cx) {
 3184            return;
 3185        }
 3186
 3187        let text: Arc<str> = text.into();
 3188        self.transact(cx, |this, cx| {
 3189            let old_selections = this.selections.all_adjusted(cx);
 3190            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3191                let anchors = {
 3192                    let snapshot = buffer.read(cx);
 3193                    old_selections
 3194                        .iter()
 3195                        .map(|s| {
 3196                            let anchor = snapshot.anchor_after(s.head());
 3197                            s.map(|_| anchor)
 3198                        })
 3199                        .collect::<Vec<_>>()
 3200                };
 3201                buffer.edit(
 3202                    old_selections
 3203                        .iter()
 3204                        .map(|s| (s.start..s.end, text.clone())),
 3205                    autoindent_mode,
 3206                    cx,
 3207                );
 3208                anchors
 3209            });
 3210
 3211            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3212                s.select_anchors(selection_anchors);
 3213            })
 3214        });
 3215    }
 3216
 3217    fn trigger_completion_on_input(
 3218        &mut self,
 3219        text: &str,
 3220        trigger_in_words: bool,
 3221        cx: &mut ViewContext<Self>,
 3222    ) {
 3223        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3224            self.show_completions(
 3225                &ShowCompletions {
 3226                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3227                },
 3228                cx,
 3229            );
 3230        } else {
 3231            self.hide_context_menu(cx);
 3232        }
 3233    }
 3234
 3235    fn is_completion_trigger(
 3236        &self,
 3237        text: &str,
 3238        trigger_in_words: bool,
 3239        cx: &mut ViewContext<Self>,
 3240    ) -> bool {
 3241        let position = self.selections.newest_anchor().head();
 3242        let multibuffer = self.buffer.read(cx);
 3243        let Some(buffer) = position
 3244            .buffer_id
 3245            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3246        else {
 3247            return false;
 3248        };
 3249
 3250        if let Some(completion_provider) = &self.completion_provider {
 3251            completion_provider.is_completion_trigger(
 3252                &buffer,
 3253                position.text_anchor,
 3254                text,
 3255                trigger_in_words,
 3256                cx,
 3257            )
 3258        } else {
 3259            false
 3260        }
 3261    }
 3262
 3263    /// If any empty selections is touching the start of its innermost containing autoclose
 3264    /// region, expand it to select the brackets.
 3265    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3266        let selections = self.selections.all::<usize>(cx);
 3267        let buffer = self.buffer.read(cx).read(cx);
 3268        let new_selections = self
 3269            .selections_with_autoclose_regions(selections, &buffer)
 3270            .map(|(mut selection, region)| {
 3271                if !selection.is_empty() {
 3272                    return selection;
 3273                }
 3274
 3275                if let Some(region) = region {
 3276                    let mut range = region.range.to_offset(&buffer);
 3277                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3278                        range.start -= region.pair.start.len();
 3279                        if buffer.contains_str_at(range.start, &region.pair.start)
 3280                            && buffer.contains_str_at(range.end, &region.pair.end)
 3281                        {
 3282                            range.end += region.pair.end.len();
 3283                            selection.start = range.start;
 3284                            selection.end = range.end;
 3285
 3286                            return selection;
 3287                        }
 3288                    }
 3289                }
 3290
 3291                let always_treat_brackets_as_autoclosed = buffer
 3292                    .settings_at(selection.start, cx)
 3293                    .always_treat_brackets_as_autoclosed;
 3294
 3295                if !always_treat_brackets_as_autoclosed {
 3296                    return selection;
 3297                }
 3298
 3299                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3300                    for (pair, enabled) in scope.brackets() {
 3301                        if !enabled || !pair.close {
 3302                            continue;
 3303                        }
 3304
 3305                        if buffer.contains_str_at(selection.start, &pair.end) {
 3306                            let pair_start_len = pair.start.len();
 3307                            if buffer.contains_str_at(
 3308                                selection.start.saturating_sub(pair_start_len),
 3309                                &pair.start,
 3310                            ) {
 3311                                selection.start -= pair_start_len;
 3312                                selection.end += pair.end.len();
 3313
 3314                                return selection;
 3315                            }
 3316                        }
 3317                    }
 3318                }
 3319
 3320                selection
 3321            })
 3322            .collect();
 3323
 3324        drop(buffer);
 3325        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3326    }
 3327
 3328    /// Iterate the given selections, and for each one, find the smallest surrounding
 3329    /// autoclose region. This uses the ordering of the selections and the autoclose
 3330    /// regions to avoid repeated comparisons.
 3331    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3332        &'a self,
 3333        selections: impl IntoIterator<Item = Selection<D>>,
 3334        buffer: &'a MultiBufferSnapshot,
 3335    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3336        let mut i = 0;
 3337        let mut regions = self.autoclose_regions.as_slice();
 3338        selections.into_iter().map(move |selection| {
 3339            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3340
 3341            let mut enclosing = None;
 3342            while let Some(pair_state) = regions.get(i) {
 3343                if pair_state.range.end.to_offset(buffer) < range.start {
 3344                    regions = &regions[i + 1..];
 3345                    i = 0;
 3346                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3347                    break;
 3348                } else {
 3349                    if pair_state.selection_id == selection.id {
 3350                        enclosing = Some(pair_state);
 3351                    }
 3352                    i += 1;
 3353                }
 3354            }
 3355
 3356            (selection, enclosing)
 3357        })
 3358    }
 3359
 3360    /// Remove any autoclose regions that no longer contain their selection.
 3361    fn invalidate_autoclose_regions(
 3362        &mut self,
 3363        mut selections: &[Selection<Anchor>],
 3364        buffer: &MultiBufferSnapshot,
 3365    ) {
 3366        self.autoclose_regions.retain(|state| {
 3367            let mut i = 0;
 3368            while let Some(selection) = selections.get(i) {
 3369                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3370                    selections = &selections[1..];
 3371                    continue;
 3372                }
 3373                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3374                    break;
 3375                }
 3376                if selection.id == state.selection_id {
 3377                    return true;
 3378                } else {
 3379                    i += 1;
 3380                }
 3381            }
 3382            false
 3383        });
 3384    }
 3385
 3386    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3387        let offset = position.to_offset(buffer);
 3388        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3389        if offset > word_range.start && kind == Some(CharKind::Word) {
 3390            Some(
 3391                buffer
 3392                    .text_for_range(word_range.start..offset)
 3393                    .collect::<String>(),
 3394            )
 3395        } else {
 3396            None
 3397        }
 3398    }
 3399
 3400    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3401        self.refresh_inlay_hints(
 3402            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3403            cx,
 3404        );
 3405    }
 3406
 3407    pub fn inlay_hints_enabled(&self) -> bool {
 3408        self.inlay_hint_cache.enabled
 3409    }
 3410
 3411    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3412        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3413            return;
 3414        }
 3415
 3416        let reason_description = reason.description();
 3417        let ignore_debounce = matches!(
 3418            reason,
 3419            InlayHintRefreshReason::SettingsChange(_)
 3420                | InlayHintRefreshReason::Toggle(_)
 3421                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3422        );
 3423        let (invalidate_cache, required_languages) = match reason {
 3424            InlayHintRefreshReason::Toggle(enabled) => {
 3425                self.inlay_hint_cache.enabled = enabled;
 3426                if enabled {
 3427                    (InvalidationStrategy::RefreshRequested, None)
 3428                } else {
 3429                    self.inlay_hint_cache.clear();
 3430                    self.splice_inlays(
 3431                        self.visible_inlay_hints(cx)
 3432                            .iter()
 3433                            .map(|inlay| inlay.id)
 3434                            .collect(),
 3435                        Vec::new(),
 3436                        cx,
 3437                    );
 3438                    return;
 3439                }
 3440            }
 3441            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3442                match self.inlay_hint_cache.update_settings(
 3443                    &self.buffer,
 3444                    new_settings,
 3445                    self.visible_inlay_hints(cx),
 3446                    cx,
 3447                ) {
 3448                    ControlFlow::Break(Some(InlaySplice {
 3449                        to_remove,
 3450                        to_insert,
 3451                    })) => {
 3452                        self.splice_inlays(to_remove, to_insert, cx);
 3453                        return;
 3454                    }
 3455                    ControlFlow::Break(None) => return,
 3456                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3457                }
 3458            }
 3459            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3460                if let Some(InlaySplice {
 3461                    to_remove,
 3462                    to_insert,
 3463                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3464                {
 3465                    self.splice_inlays(to_remove, to_insert, cx);
 3466                }
 3467                return;
 3468            }
 3469            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3470            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3471                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3472            }
 3473            InlayHintRefreshReason::RefreshRequested => {
 3474                (InvalidationStrategy::RefreshRequested, None)
 3475            }
 3476        };
 3477
 3478        if let Some(InlaySplice {
 3479            to_remove,
 3480            to_insert,
 3481        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3482            reason_description,
 3483            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3484            invalidate_cache,
 3485            ignore_debounce,
 3486            cx,
 3487        ) {
 3488            self.splice_inlays(to_remove, to_insert, cx);
 3489        }
 3490    }
 3491
 3492    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3493        self.display_map
 3494            .read(cx)
 3495            .current_inlays()
 3496            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3497            .cloned()
 3498            .collect()
 3499    }
 3500
 3501    pub fn excerpts_for_inlay_hints_query(
 3502        &self,
 3503        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3504        cx: &mut ViewContext<Editor>,
 3505    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3506        let Some(project) = self.project.as_ref() else {
 3507            return HashMap::default();
 3508        };
 3509        let project = project.read(cx);
 3510        let multi_buffer = self.buffer().read(cx);
 3511        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3512        let multi_buffer_visible_start = self
 3513            .scroll_manager
 3514            .anchor()
 3515            .anchor
 3516            .to_point(&multi_buffer_snapshot);
 3517        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3518            multi_buffer_visible_start
 3519                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3520            Bias::Left,
 3521        );
 3522        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3523        multi_buffer
 3524            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3525            .into_iter()
 3526            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3527            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3528                let buffer = buffer_handle.read(cx);
 3529                let buffer_file = project::File::from_dyn(buffer.file())?;
 3530                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3531                let worktree_entry = buffer_worktree
 3532                    .read(cx)
 3533                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3534                if worktree_entry.is_ignored {
 3535                    return None;
 3536                }
 3537
 3538                let language = buffer.language()?;
 3539                if let Some(restrict_to_languages) = restrict_to_languages {
 3540                    if !restrict_to_languages.contains(language) {
 3541                        return None;
 3542                    }
 3543                }
 3544                Some((
 3545                    excerpt_id,
 3546                    (
 3547                        buffer_handle,
 3548                        buffer.version().clone(),
 3549                        excerpt_visible_range,
 3550                    ),
 3551                ))
 3552            })
 3553            .collect()
 3554    }
 3555
 3556    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3557        TextLayoutDetails {
 3558            text_system: cx.text_system().clone(),
 3559            editor_style: self.style.clone().unwrap(),
 3560            rem_size: cx.rem_size(),
 3561            scroll_anchor: self.scroll_manager.anchor(),
 3562            visible_rows: self.visible_line_count(),
 3563            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3564        }
 3565    }
 3566
 3567    fn splice_inlays(
 3568        &self,
 3569        to_remove: Vec<InlayId>,
 3570        to_insert: Vec<Inlay>,
 3571        cx: &mut ViewContext<Self>,
 3572    ) {
 3573        self.display_map.update(cx, |display_map, cx| {
 3574            display_map.splice_inlays(to_remove, to_insert, cx)
 3575        });
 3576        cx.notify();
 3577    }
 3578
 3579    fn trigger_on_type_formatting(
 3580        &self,
 3581        input: String,
 3582        cx: &mut ViewContext<Self>,
 3583    ) -> Option<Task<Result<()>>> {
 3584        if input.len() != 1 {
 3585            return None;
 3586        }
 3587
 3588        let project = self.project.as_ref()?;
 3589        let position = self.selections.newest_anchor().head();
 3590        let (buffer, buffer_position) = self
 3591            .buffer
 3592            .read(cx)
 3593            .text_anchor_for_position(position, cx)?;
 3594
 3595        let settings = language_settings::language_settings(
 3596            buffer
 3597                .read(cx)
 3598                .language_at(buffer_position)
 3599                .map(|l| l.name()),
 3600            buffer.read(cx).file(),
 3601            cx,
 3602        );
 3603        if !settings.use_on_type_format {
 3604            return None;
 3605        }
 3606
 3607        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3608        // hence we do LSP request & edit on host side only — add formats to host's history.
 3609        let push_to_lsp_host_history = true;
 3610        // If this is not the host, append its history with new edits.
 3611        let push_to_client_history = project.read(cx).is_via_collab();
 3612
 3613        let on_type_formatting = project.update(cx, |project, cx| {
 3614            project.on_type_format(
 3615                buffer.clone(),
 3616                buffer_position,
 3617                input,
 3618                push_to_lsp_host_history,
 3619                cx,
 3620            )
 3621        });
 3622        Some(cx.spawn(|editor, mut cx| async move {
 3623            if let Some(transaction) = on_type_formatting.await? {
 3624                if push_to_client_history {
 3625                    buffer
 3626                        .update(&mut cx, |buffer, _| {
 3627                            buffer.push_transaction(transaction, Instant::now());
 3628                        })
 3629                        .ok();
 3630                }
 3631                editor.update(&mut cx, |editor, cx| {
 3632                    editor.refresh_document_highlights(cx);
 3633                })?;
 3634            }
 3635            Ok(())
 3636        }))
 3637    }
 3638
 3639    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3640        if self.pending_rename.is_some() {
 3641            return;
 3642        }
 3643
 3644        let Some(provider) = self.completion_provider.as_ref() else {
 3645            return;
 3646        };
 3647
 3648        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3649            return;
 3650        }
 3651
 3652        let position = self.selections.newest_anchor().head();
 3653        let (buffer, buffer_position) =
 3654            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3655                output
 3656            } else {
 3657                return;
 3658            };
 3659        let show_completion_documentation = buffer
 3660            .read(cx)
 3661            .snapshot()
 3662            .settings_at(buffer_position, cx)
 3663            .show_completion_documentation;
 3664
 3665        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3666
 3667        let aside_was_displayed = match self.context_menu.borrow().deref() {
 3668            Some(CodeContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
 3669            _ => false,
 3670        };
 3671        let trigger_kind = match &options.trigger {
 3672            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3673                CompletionTriggerKind::TRIGGER_CHARACTER
 3674            }
 3675            _ => CompletionTriggerKind::INVOKED,
 3676        };
 3677        let completion_context = CompletionContext {
 3678            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3679                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3680                    Some(String::from(trigger))
 3681                } else {
 3682                    None
 3683                }
 3684            }),
 3685            trigger_kind,
 3686        };
 3687        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3688        let sort_completions = provider.sort_completions();
 3689
 3690        let id = post_inc(&mut self.next_completion_id);
 3691        let task = cx.spawn(|editor, mut cx| {
 3692            async move {
 3693                editor.update(&mut cx, |this, _| {
 3694                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3695                })?;
 3696                let completions = completions.await.log_err();
 3697                let menu = if let Some(completions) = completions {
 3698                    let mut menu = CompletionsMenu::new(
 3699                        id,
 3700                        sort_completions,
 3701                        show_completion_documentation,
 3702                        position,
 3703                        buffer.clone(),
 3704                        completions.into(),
 3705                        aside_was_displayed,
 3706                    );
 3707                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3708                        .await;
 3709
 3710                    if menu.matches.is_empty() {
 3711                        None
 3712                    } else {
 3713                        Some(menu)
 3714                    }
 3715                } else {
 3716                    None
 3717                };
 3718
 3719                editor.update(&mut cx, |editor, cx| {
 3720                    let mut context_menu = editor.context_menu.borrow_mut();
 3721                    match context_menu.as_ref() {
 3722                        None => {}
 3723                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3724                            if prev_menu.id > id {
 3725                                return;
 3726                            }
 3727                        }
 3728                        _ => return,
 3729                    }
 3730
 3731                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3732                        let mut menu = menu.unwrap();
 3733                        menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
 3734                        *context_menu = Some(CodeContextMenu::Completions(menu));
 3735                        drop(context_menu);
 3736                        cx.notify();
 3737                    } else if editor.completion_tasks.len() <= 1 {
 3738                        // If there are no more completion tasks and the last menu was
 3739                        // empty, we should hide it. If it was already hidden, we should
 3740                        // also show the copilot completion when available.
 3741                        drop(context_menu);
 3742                        editor.hide_context_menu(cx);
 3743                    }
 3744                })?;
 3745
 3746                Ok::<_, anyhow::Error>(())
 3747            }
 3748            .log_err()
 3749        });
 3750
 3751        self.completion_tasks.push((id, task));
 3752    }
 3753
 3754    pub fn confirm_completion(
 3755        &mut self,
 3756        action: &ConfirmCompletion,
 3757        cx: &mut ViewContext<Self>,
 3758    ) -> Option<Task<Result<()>>> {
 3759        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3760    }
 3761
 3762    pub fn compose_completion(
 3763        &mut self,
 3764        action: &ComposeCompletion,
 3765        cx: &mut ViewContext<Self>,
 3766    ) -> Option<Task<Result<()>>> {
 3767        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3768    }
 3769
 3770    fn do_completion(
 3771        &mut self,
 3772        item_ix: Option<usize>,
 3773        intent: CompletionIntent,
 3774        cx: &mut ViewContext<Editor>,
 3775    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3776        use language::ToOffset as _;
 3777
 3778        self.discard_inline_completion(true, cx);
 3779        let completions_menu =
 3780            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3781                menu
 3782            } else {
 3783                return None;
 3784            };
 3785
 3786        let mat = completions_menu
 3787            .matches
 3788            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3789        let buffer_handle = completions_menu.buffer;
 3790        let completions = completions_menu.completions.borrow_mut();
 3791        let completion = completions.get(mat.candidate_id)?;
 3792        cx.stop_propagation();
 3793
 3794        let snippet;
 3795        let text;
 3796
 3797        if completion.is_snippet() {
 3798            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3799            text = snippet.as_ref().unwrap().text.clone();
 3800        } else {
 3801            snippet = None;
 3802            text = completion.new_text.clone();
 3803        };
 3804        let selections = self.selections.all::<usize>(cx);
 3805        let buffer = buffer_handle.read(cx);
 3806        let old_range = completion.old_range.to_offset(buffer);
 3807        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3808
 3809        let newest_selection = self.selections.newest_anchor();
 3810        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3811            return None;
 3812        }
 3813
 3814        let lookbehind = newest_selection
 3815            .start
 3816            .text_anchor
 3817            .to_offset(buffer)
 3818            .saturating_sub(old_range.start);
 3819        let lookahead = old_range
 3820            .end
 3821            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3822        let mut common_prefix_len = old_text
 3823            .bytes()
 3824            .zip(text.bytes())
 3825            .take_while(|(a, b)| a == b)
 3826            .count();
 3827
 3828        let snapshot = self.buffer.read(cx).snapshot(cx);
 3829        let mut range_to_replace: Option<Range<isize>> = None;
 3830        let mut ranges = Vec::new();
 3831        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3832        for selection in &selections {
 3833            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3834                let start = selection.start.saturating_sub(lookbehind);
 3835                let end = selection.end + lookahead;
 3836                if selection.id == newest_selection.id {
 3837                    range_to_replace = Some(
 3838                        ((start + common_prefix_len) as isize - selection.start as isize)
 3839                            ..(end as isize - selection.start as isize),
 3840                    );
 3841                }
 3842                ranges.push(start + common_prefix_len..end);
 3843            } else {
 3844                common_prefix_len = 0;
 3845                ranges.clear();
 3846                ranges.extend(selections.iter().map(|s| {
 3847                    if s.id == newest_selection.id {
 3848                        range_to_replace = Some(
 3849                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3850                                - selection.start as isize
 3851                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3852                                    - selection.start as isize,
 3853                        );
 3854                        old_range.clone()
 3855                    } else {
 3856                        s.start..s.end
 3857                    }
 3858                }));
 3859                break;
 3860            }
 3861            if !self.linked_edit_ranges.is_empty() {
 3862                let start_anchor = snapshot.anchor_before(selection.head());
 3863                let end_anchor = snapshot.anchor_after(selection.tail());
 3864                if let Some(ranges) = self
 3865                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3866                {
 3867                    for (buffer, edits) in ranges {
 3868                        linked_edits.entry(buffer.clone()).or_default().extend(
 3869                            edits
 3870                                .into_iter()
 3871                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3872                        );
 3873                    }
 3874                }
 3875            }
 3876        }
 3877        let text = &text[common_prefix_len..];
 3878
 3879        cx.emit(EditorEvent::InputHandled {
 3880            utf16_range_to_replace: range_to_replace,
 3881            text: text.into(),
 3882        });
 3883
 3884        self.transact(cx, |this, cx| {
 3885            if let Some(mut snippet) = snippet {
 3886                snippet.text = text.to_string();
 3887                for tabstop in snippet
 3888                    .tabstops
 3889                    .iter_mut()
 3890                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3891                {
 3892                    tabstop.start -= common_prefix_len as isize;
 3893                    tabstop.end -= common_prefix_len as isize;
 3894                }
 3895
 3896                this.insert_snippet(&ranges, snippet, cx).log_err();
 3897            } else {
 3898                this.buffer.update(cx, |buffer, cx| {
 3899                    buffer.edit(
 3900                        ranges.iter().map(|range| (range.clone(), text)),
 3901                        this.autoindent_mode.clone(),
 3902                        cx,
 3903                    );
 3904                });
 3905            }
 3906            for (buffer, edits) in linked_edits {
 3907                buffer.update(cx, |buffer, cx| {
 3908                    let snapshot = buffer.snapshot();
 3909                    let edits = edits
 3910                        .into_iter()
 3911                        .map(|(range, text)| {
 3912                            use text::ToPoint as TP;
 3913                            let end_point = TP::to_point(&range.end, &snapshot);
 3914                            let start_point = TP::to_point(&range.start, &snapshot);
 3915                            (start_point..end_point, text)
 3916                        })
 3917                        .sorted_by_key(|(range, _)| range.start)
 3918                        .collect::<Vec<_>>();
 3919                    buffer.edit(edits, None, cx);
 3920                })
 3921            }
 3922
 3923            this.refresh_inline_completion(true, false, cx);
 3924        });
 3925
 3926        let show_new_completions_on_confirm = completion
 3927            .confirm
 3928            .as_ref()
 3929            .map_or(false, |confirm| confirm(intent, cx));
 3930        if show_new_completions_on_confirm {
 3931            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3932        }
 3933
 3934        let provider = self.completion_provider.as_ref()?;
 3935        let apply_edits = provider.apply_additional_edits_for_completion(
 3936            buffer_handle,
 3937            completion.clone(),
 3938            true,
 3939            cx,
 3940        );
 3941
 3942        let editor_settings = EditorSettings::get_global(cx);
 3943        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3944            // After the code completion is finished, users often want to know what signatures are needed.
 3945            // so we should automatically call signature_help
 3946            self.show_signature_help(&ShowSignatureHelp, cx);
 3947        }
 3948
 3949        Some(cx.foreground_executor().spawn(async move {
 3950            apply_edits.await?;
 3951            Ok(())
 3952        }))
 3953    }
 3954
 3955    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3956        let mut context_menu = self.context_menu.borrow_mut();
 3957        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 3958            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 3959                // Toggle if we're selecting the same one
 3960                *context_menu = None;
 3961                cx.notify();
 3962                return;
 3963            } else {
 3964                // Otherwise, clear it and start a new one
 3965                *context_menu = None;
 3966                cx.notify();
 3967            }
 3968        }
 3969        drop(context_menu);
 3970        let snapshot = self.snapshot(cx);
 3971        let deployed_from_indicator = action.deployed_from_indicator;
 3972        let mut task = self.code_actions_task.take();
 3973        let action = action.clone();
 3974        cx.spawn(|editor, mut cx| async move {
 3975            while let Some(prev_task) = task {
 3976                prev_task.await.log_err();
 3977                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 3978            }
 3979
 3980            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 3981                if editor.focus_handle.is_focused(cx) {
 3982                    let multibuffer_point = action
 3983                        .deployed_from_indicator
 3984                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 3985                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 3986                    let (buffer, buffer_row) = snapshot
 3987                        .buffer_snapshot
 3988                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 3989                        .and_then(|(buffer_snapshot, range)| {
 3990                            editor
 3991                                .buffer
 3992                                .read(cx)
 3993                                .buffer(buffer_snapshot.remote_id())
 3994                                .map(|buffer| (buffer, range.start.row))
 3995                        })?;
 3996                    let (_, code_actions) = editor
 3997                        .available_code_actions
 3998                        .clone()
 3999                        .and_then(|(location, code_actions)| {
 4000                            let snapshot = location.buffer.read(cx).snapshot();
 4001                            let point_range = location.range.to_point(&snapshot);
 4002                            let point_range = point_range.start.row..=point_range.end.row;
 4003                            if point_range.contains(&buffer_row) {
 4004                                Some((location, code_actions))
 4005                            } else {
 4006                                None
 4007                            }
 4008                        })
 4009                        .unzip();
 4010                    let buffer_id = buffer.read(cx).remote_id();
 4011                    let tasks = editor
 4012                        .tasks
 4013                        .get(&(buffer_id, buffer_row))
 4014                        .map(|t| Arc::new(t.to_owned()));
 4015                    if tasks.is_none() && code_actions.is_none() {
 4016                        return None;
 4017                    }
 4018
 4019                    editor.completion_tasks.clear();
 4020                    editor.discard_inline_completion(false, cx);
 4021                    let task_context =
 4022                        tasks
 4023                            .as_ref()
 4024                            .zip(editor.project.clone())
 4025                            .map(|(tasks, project)| {
 4026                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4027                            });
 4028
 4029                    Some(cx.spawn(|editor, mut cx| async move {
 4030                        let task_context = match task_context {
 4031                            Some(task_context) => task_context.await,
 4032                            None => None,
 4033                        };
 4034                        let resolved_tasks =
 4035                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4036                                Rc::new(ResolvedTasks {
 4037                                    templates: tasks.resolve(&task_context).collect(),
 4038                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4039                                        multibuffer_point.row,
 4040                                        tasks.column,
 4041                                    )),
 4042                                })
 4043                            });
 4044                        let spawn_straight_away = resolved_tasks
 4045                            .as_ref()
 4046                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4047                            && code_actions
 4048                                .as_ref()
 4049                                .map_or(true, |actions| actions.is_empty());
 4050                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4051                            *editor.context_menu.borrow_mut() =
 4052                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4053                                    buffer,
 4054                                    actions: CodeActionContents {
 4055                                        tasks: resolved_tasks,
 4056                                        actions: code_actions,
 4057                                    },
 4058                                    selected_item: Default::default(),
 4059                                    scroll_handle: UniformListScrollHandle::default(),
 4060                                    deployed_from_indicator,
 4061                                }));
 4062                            if spawn_straight_away {
 4063                                if let Some(task) = editor.confirm_code_action(
 4064                                    &ConfirmCodeAction { item_ix: Some(0) },
 4065                                    cx,
 4066                                ) {
 4067                                    cx.notify();
 4068                                    return task;
 4069                                }
 4070                            }
 4071                            cx.notify();
 4072                            Task::ready(Ok(()))
 4073                        }) {
 4074                            task.await
 4075                        } else {
 4076                            Ok(())
 4077                        }
 4078                    }))
 4079                } else {
 4080                    Some(Task::ready(Ok(())))
 4081                }
 4082            })?;
 4083            if let Some(task) = spawned_test_task {
 4084                task.await?;
 4085            }
 4086
 4087            Ok::<_, anyhow::Error>(())
 4088        })
 4089        .detach_and_log_err(cx);
 4090    }
 4091
 4092    pub fn confirm_code_action(
 4093        &mut self,
 4094        action: &ConfirmCodeAction,
 4095        cx: &mut ViewContext<Self>,
 4096    ) -> Option<Task<Result<()>>> {
 4097        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4098            menu
 4099        } else {
 4100            return None;
 4101        };
 4102        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4103        let action = actions_menu.actions.get(action_ix)?;
 4104        let title = action.label();
 4105        let buffer = actions_menu.buffer;
 4106        let workspace = self.workspace()?;
 4107
 4108        match action {
 4109            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4110                workspace.update(cx, |workspace, cx| {
 4111                    workspace::tasks::schedule_resolved_task(
 4112                        workspace,
 4113                        task_source_kind,
 4114                        resolved_task,
 4115                        false,
 4116                        cx,
 4117                    );
 4118
 4119                    Some(Task::ready(Ok(())))
 4120                })
 4121            }
 4122            CodeActionsItem::CodeAction {
 4123                excerpt_id,
 4124                action,
 4125                provider,
 4126            } => {
 4127                let apply_code_action =
 4128                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4129                let workspace = workspace.downgrade();
 4130                Some(cx.spawn(|editor, cx| async move {
 4131                    let project_transaction = apply_code_action.await?;
 4132                    Self::open_project_transaction(
 4133                        &editor,
 4134                        workspace,
 4135                        project_transaction,
 4136                        title,
 4137                        cx,
 4138                    )
 4139                    .await
 4140                }))
 4141            }
 4142        }
 4143    }
 4144
 4145    pub async fn open_project_transaction(
 4146        this: &WeakView<Editor>,
 4147        workspace: WeakView<Workspace>,
 4148        transaction: ProjectTransaction,
 4149        title: String,
 4150        mut cx: AsyncWindowContext,
 4151    ) -> Result<()> {
 4152        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4153        cx.update(|cx| {
 4154            entries.sort_unstable_by_key(|(buffer, _)| {
 4155                buffer.read(cx).file().map(|f| f.path().clone())
 4156            });
 4157        })?;
 4158
 4159        // If the project transaction's edits are all contained within this editor, then
 4160        // avoid opening a new editor to display them.
 4161
 4162        if let Some((buffer, transaction)) = entries.first() {
 4163            if entries.len() == 1 {
 4164                let excerpt = this.update(&mut cx, |editor, cx| {
 4165                    editor
 4166                        .buffer()
 4167                        .read(cx)
 4168                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4169                })?;
 4170                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4171                    if excerpted_buffer == *buffer {
 4172                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4173                            let excerpt_range = excerpt_range.to_offset(buffer);
 4174                            buffer
 4175                                .edited_ranges_for_transaction::<usize>(transaction)
 4176                                .all(|range| {
 4177                                    excerpt_range.start <= range.start
 4178                                        && excerpt_range.end >= range.end
 4179                                })
 4180                        })?;
 4181
 4182                        if all_edits_within_excerpt {
 4183                            return Ok(());
 4184                        }
 4185                    }
 4186                }
 4187            }
 4188        } else {
 4189            return Ok(());
 4190        }
 4191
 4192        let mut ranges_to_highlight = Vec::new();
 4193        let excerpt_buffer = cx.new_model(|cx| {
 4194            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4195            for (buffer_handle, transaction) in &entries {
 4196                let buffer = buffer_handle.read(cx);
 4197                ranges_to_highlight.extend(
 4198                    multibuffer.push_excerpts_with_context_lines(
 4199                        buffer_handle.clone(),
 4200                        buffer
 4201                            .edited_ranges_for_transaction::<usize>(transaction)
 4202                            .collect(),
 4203                        DEFAULT_MULTIBUFFER_CONTEXT,
 4204                        cx,
 4205                    ),
 4206                );
 4207            }
 4208            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4209            multibuffer
 4210        })?;
 4211
 4212        workspace.update(&mut cx, |workspace, cx| {
 4213            let project = workspace.project().clone();
 4214            let editor =
 4215                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4216            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4217            editor.update(cx, |editor, cx| {
 4218                editor.highlight_background::<Self>(
 4219                    &ranges_to_highlight,
 4220                    |theme| theme.editor_highlighted_line_background,
 4221                    cx,
 4222                );
 4223            });
 4224        })?;
 4225
 4226        Ok(())
 4227    }
 4228
 4229    pub fn clear_code_action_providers(&mut self) {
 4230        self.code_action_providers.clear();
 4231        self.available_code_actions.take();
 4232    }
 4233
 4234    pub fn push_code_action_provider(
 4235        &mut self,
 4236        provider: Rc<dyn CodeActionProvider>,
 4237        cx: &mut ViewContext<Self>,
 4238    ) {
 4239        self.code_action_providers.push(provider);
 4240        self.refresh_code_actions(cx);
 4241    }
 4242
 4243    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4244        let buffer = self.buffer.read(cx);
 4245        let newest_selection = self.selections.newest_anchor().clone();
 4246        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4247        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4248        if start_buffer != end_buffer {
 4249            return None;
 4250        }
 4251
 4252        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4253            cx.background_executor()
 4254                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4255                .await;
 4256
 4257            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4258                let providers = this.code_action_providers.clone();
 4259                let tasks = this
 4260                    .code_action_providers
 4261                    .iter()
 4262                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4263                    .collect::<Vec<_>>();
 4264                (providers, tasks)
 4265            })?;
 4266
 4267            let mut actions = Vec::new();
 4268            for (provider, provider_actions) in
 4269                providers.into_iter().zip(future::join_all(tasks).await)
 4270            {
 4271                if let Some(provider_actions) = provider_actions.log_err() {
 4272                    actions.extend(provider_actions.into_iter().map(|action| {
 4273                        AvailableCodeAction {
 4274                            excerpt_id: newest_selection.start.excerpt_id,
 4275                            action,
 4276                            provider: provider.clone(),
 4277                        }
 4278                    }));
 4279                }
 4280            }
 4281
 4282            this.update(&mut cx, |this, cx| {
 4283                this.available_code_actions = if actions.is_empty() {
 4284                    None
 4285                } else {
 4286                    Some((
 4287                        Location {
 4288                            buffer: start_buffer,
 4289                            range: start..end,
 4290                        },
 4291                        actions.into(),
 4292                    ))
 4293                };
 4294                cx.notify();
 4295            })
 4296        }));
 4297        None
 4298    }
 4299
 4300    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4301        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4302            self.show_git_blame_inline = false;
 4303
 4304            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4305                cx.background_executor().timer(delay).await;
 4306
 4307                this.update(&mut cx, |this, cx| {
 4308                    this.show_git_blame_inline = true;
 4309                    cx.notify();
 4310                })
 4311                .log_err();
 4312            }));
 4313        }
 4314    }
 4315
 4316    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4317        if self.pending_rename.is_some() {
 4318            return None;
 4319        }
 4320
 4321        let provider = self.semantics_provider.clone()?;
 4322        let buffer = self.buffer.read(cx);
 4323        let newest_selection = self.selections.newest_anchor().clone();
 4324        let cursor_position = newest_selection.head();
 4325        let (cursor_buffer, cursor_buffer_position) =
 4326            buffer.text_anchor_for_position(cursor_position, cx)?;
 4327        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4328        if cursor_buffer != tail_buffer {
 4329            return None;
 4330        }
 4331        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4332        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4333            cx.background_executor()
 4334                .timer(Duration::from_millis(debounce))
 4335                .await;
 4336
 4337            let highlights = if let Some(highlights) = cx
 4338                .update(|cx| {
 4339                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4340                })
 4341                .ok()
 4342                .flatten()
 4343            {
 4344                highlights.await.log_err()
 4345            } else {
 4346                None
 4347            };
 4348
 4349            if let Some(highlights) = highlights {
 4350                this.update(&mut cx, |this, cx| {
 4351                    if this.pending_rename.is_some() {
 4352                        return;
 4353                    }
 4354
 4355                    let buffer_id = cursor_position.buffer_id;
 4356                    let buffer = this.buffer.read(cx);
 4357                    if !buffer
 4358                        .text_anchor_for_position(cursor_position, cx)
 4359                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4360                    {
 4361                        return;
 4362                    }
 4363
 4364                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4365                    let mut write_ranges = Vec::new();
 4366                    let mut read_ranges = Vec::new();
 4367                    for highlight in highlights {
 4368                        for (excerpt_id, excerpt_range) in
 4369                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4370                        {
 4371                            let start = highlight
 4372                                .range
 4373                                .start
 4374                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4375                            let end = highlight
 4376                                .range
 4377                                .end
 4378                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4379                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4380                                continue;
 4381                            }
 4382
 4383                            let range = Anchor {
 4384                                buffer_id,
 4385                                excerpt_id,
 4386                                text_anchor: start,
 4387                            }..Anchor {
 4388                                buffer_id,
 4389                                excerpt_id,
 4390                                text_anchor: end,
 4391                            };
 4392                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4393                                write_ranges.push(range);
 4394                            } else {
 4395                                read_ranges.push(range);
 4396                            }
 4397                        }
 4398                    }
 4399
 4400                    this.highlight_background::<DocumentHighlightRead>(
 4401                        &read_ranges,
 4402                        |theme| theme.editor_document_highlight_read_background,
 4403                        cx,
 4404                    );
 4405                    this.highlight_background::<DocumentHighlightWrite>(
 4406                        &write_ranges,
 4407                        |theme| theme.editor_document_highlight_write_background,
 4408                        cx,
 4409                    );
 4410                    cx.notify();
 4411                })
 4412                .log_err();
 4413            }
 4414        }));
 4415        None
 4416    }
 4417
 4418    pub fn refresh_inline_completion(
 4419        &mut self,
 4420        debounce: bool,
 4421        user_requested: bool,
 4422        cx: &mut ViewContext<Self>,
 4423    ) -> Option<()> {
 4424        let provider = self.inline_completion_provider()?;
 4425        let cursor = self.selections.newest_anchor().head();
 4426        let (buffer, cursor_buffer_position) =
 4427            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4428
 4429        if !user_requested
 4430            && (!self.enable_inline_completions
 4431                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4432                || !self.is_focused(cx))
 4433        {
 4434            self.discard_inline_completion(false, cx);
 4435            return None;
 4436        }
 4437
 4438        self.update_visible_inline_completion(cx);
 4439        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4440        Some(())
 4441    }
 4442
 4443    fn cycle_inline_completion(
 4444        &mut self,
 4445        direction: Direction,
 4446        cx: &mut ViewContext<Self>,
 4447    ) -> Option<()> {
 4448        let provider = self.inline_completion_provider()?;
 4449        let cursor = self.selections.newest_anchor().head();
 4450        let (buffer, cursor_buffer_position) =
 4451            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4452        if !self.enable_inline_completions
 4453            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4454        {
 4455            return None;
 4456        }
 4457
 4458        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4459        self.update_visible_inline_completion(cx);
 4460
 4461        Some(())
 4462    }
 4463
 4464    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4465        if !self.has_active_inline_completion() {
 4466            self.refresh_inline_completion(false, true, cx);
 4467            return;
 4468        }
 4469
 4470        self.update_visible_inline_completion(cx);
 4471    }
 4472
 4473    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4474        self.show_cursor_names(cx);
 4475    }
 4476
 4477    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4478        self.show_cursor_names = true;
 4479        cx.notify();
 4480        cx.spawn(|this, mut cx| async move {
 4481            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4482            this.update(&mut cx, |this, cx| {
 4483                this.show_cursor_names = false;
 4484                cx.notify()
 4485            })
 4486            .ok()
 4487        })
 4488        .detach();
 4489    }
 4490
 4491    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4492        if self.has_active_inline_completion() {
 4493            self.cycle_inline_completion(Direction::Next, cx);
 4494        } else {
 4495            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4496            if is_copilot_disabled {
 4497                cx.propagate();
 4498            }
 4499        }
 4500    }
 4501
 4502    pub fn previous_inline_completion(
 4503        &mut self,
 4504        _: &PreviousInlineCompletion,
 4505        cx: &mut ViewContext<Self>,
 4506    ) {
 4507        if self.has_active_inline_completion() {
 4508            self.cycle_inline_completion(Direction::Prev, cx);
 4509        } else {
 4510            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4511            if is_copilot_disabled {
 4512                cx.propagate();
 4513            }
 4514        }
 4515    }
 4516
 4517    pub fn accept_inline_completion(
 4518        &mut self,
 4519        _: &AcceptInlineCompletion,
 4520        cx: &mut ViewContext<Self>,
 4521    ) {
 4522        self.hide_context_menu(cx);
 4523
 4524        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4525            return;
 4526        };
 4527
 4528        self.report_inline_completion_event(true, cx);
 4529
 4530        match &active_inline_completion.completion {
 4531            InlineCompletion::Move(position) => {
 4532                let position = *position;
 4533                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4534                    selections.select_anchor_ranges([position..position]);
 4535                });
 4536            }
 4537            InlineCompletion::Edit(edits) => {
 4538                if let Some(provider) = self.inline_completion_provider() {
 4539                    provider.accept(cx);
 4540                }
 4541
 4542                let snapshot = self.buffer.read(cx).snapshot(cx);
 4543                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4544
 4545                self.buffer.update(cx, |buffer, cx| {
 4546                    buffer.edit(edits.iter().cloned(), None, cx)
 4547                });
 4548
 4549                self.change_selections(None, cx, |s| {
 4550                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4551                });
 4552
 4553                self.update_visible_inline_completion(cx);
 4554                if self.active_inline_completion.is_none() {
 4555                    self.refresh_inline_completion(true, true, cx);
 4556                }
 4557
 4558                cx.notify();
 4559            }
 4560        }
 4561    }
 4562
 4563    pub fn accept_partial_inline_completion(
 4564        &mut self,
 4565        _: &AcceptPartialInlineCompletion,
 4566        cx: &mut ViewContext<Self>,
 4567    ) {
 4568        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4569            return;
 4570        };
 4571        if self.selections.count() != 1 {
 4572            return;
 4573        }
 4574
 4575        self.report_inline_completion_event(true, cx);
 4576
 4577        match &active_inline_completion.completion {
 4578            InlineCompletion::Move(position) => {
 4579                let position = *position;
 4580                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4581                    selections.select_anchor_ranges([position..position]);
 4582                });
 4583            }
 4584            InlineCompletion::Edit(edits) => {
 4585                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4586                    let text = edits[0].1.as_str();
 4587                    let mut partial_completion = text
 4588                        .chars()
 4589                        .by_ref()
 4590                        .take_while(|c| c.is_alphabetic())
 4591                        .collect::<String>();
 4592                    if partial_completion.is_empty() {
 4593                        partial_completion = text
 4594                            .chars()
 4595                            .by_ref()
 4596                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4597                            .collect::<String>();
 4598                    }
 4599
 4600                    cx.emit(EditorEvent::InputHandled {
 4601                        utf16_range_to_replace: None,
 4602                        text: partial_completion.clone().into(),
 4603                    });
 4604
 4605                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4606
 4607                    self.refresh_inline_completion(true, true, cx);
 4608                    cx.notify();
 4609                }
 4610            }
 4611        }
 4612    }
 4613
 4614    fn discard_inline_completion(
 4615        &mut self,
 4616        should_report_inline_completion_event: bool,
 4617        cx: &mut ViewContext<Self>,
 4618    ) -> bool {
 4619        if should_report_inline_completion_event {
 4620            self.report_inline_completion_event(false, cx);
 4621        }
 4622
 4623        if let Some(provider) = self.inline_completion_provider() {
 4624            provider.discard(cx);
 4625        }
 4626
 4627        self.take_active_inline_completion(cx).is_some()
 4628    }
 4629
 4630    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4631        let Some(provider) = self.inline_completion_provider() else {
 4632            return;
 4633        };
 4634        let Some(project) = self.project.as_ref() else {
 4635            return;
 4636        };
 4637        let Some((_, buffer, _)) = self
 4638            .buffer
 4639            .read(cx)
 4640            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4641        else {
 4642            return;
 4643        };
 4644
 4645        let project = project.read(cx);
 4646        let extension = buffer
 4647            .read(cx)
 4648            .file()
 4649            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4650        project.client().telemetry().report_inline_completion_event(
 4651            provider.name().into(),
 4652            accepted,
 4653            extension,
 4654        );
 4655    }
 4656
 4657    pub fn has_active_inline_completion(&self) -> bool {
 4658        self.active_inline_completion.is_some()
 4659    }
 4660
 4661    fn take_active_inline_completion(
 4662        &mut self,
 4663        cx: &mut ViewContext<Self>,
 4664    ) -> Option<InlineCompletion> {
 4665        let active_inline_completion = self.active_inline_completion.take()?;
 4666        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4667        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4668        Some(active_inline_completion.completion)
 4669    }
 4670
 4671    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4672        let selection = self.selections.newest_anchor();
 4673        let cursor = selection.head();
 4674        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4675        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4676        let excerpt_id = cursor.excerpt_id;
 4677
 4678        if !offset_selection.is_empty()
 4679            || self
 4680                .active_inline_completion
 4681                .as_ref()
 4682                .map_or(false, |completion| {
 4683                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4684                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4685                    !invalidation_range.contains(&offset_selection.head())
 4686                })
 4687        {
 4688            self.discard_inline_completion(false, cx);
 4689            return None;
 4690        }
 4691
 4692        self.take_active_inline_completion(cx);
 4693        let provider = self.inline_completion_provider()?;
 4694
 4695        let (buffer, cursor_buffer_position) =
 4696            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4697
 4698        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4699        let edits = completion
 4700            .edits
 4701            .into_iter()
 4702            .map(|(range, new_text)| {
 4703                (
 4704                    multibuffer
 4705                        .anchor_in_excerpt(excerpt_id, range.start)
 4706                        .unwrap()
 4707                        ..multibuffer
 4708                            .anchor_in_excerpt(excerpt_id, range.end)
 4709                            .unwrap(),
 4710                    new_text,
 4711                )
 4712            })
 4713            .collect::<Vec<_>>();
 4714        if edits.is_empty() {
 4715            return None;
 4716        }
 4717
 4718        let first_edit_start = edits.first().unwrap().0.start;
 4719        let edit_start_row = first_edit_start
 4720            .to_point(&multibuffer)
 4721            .row
 4722            .saturating_sub(2);
 4723
 4724        let last_edit_end = edits.last().unwrap().0.end;
 4725        let edit_end_row = cmp::min(
 4726            multibuffer.max_point().row,
 4727            last_edit_end.to_point(&multibuffer).row + 2,
 4728        );
 4729
 4730        let cursor_row = cursor.to_point(&multibuffer).row;
 4731
 4732        let mut inlay_ids = Vec::new();
 4733        let invalidation_row_range;
 4734        let completion;
 4735        if cursor_row < edit_start_row {
 4736            invalidation_row_range = cursor_row..edit_end_row;
 4737            completion = InlineCompletion::Move(first_edit_start);
 4738        } else if cursor_row > edit_end_row {
 4739            invalidation_row_range = edit_start_row..cursor_row;
 4740            completion = InlineCompletion::Move(first_edit_start);
 4741        } else {
 4742            if edits
 4743                .iter()
 4744                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4745            {
 4746                let mut inlays = Vec::new();
 4747                for (range, new_text) in &edits {
 4748                    let inlay = Inlay::inline_completion(
 4749                        post_inc(&mut self.next_inlay_id),
 4750                        range.start,
 4751                        new_text.as_str(),
 4752                    );
 4753                    inlay_ids.push(inlay.id);
 4754                    inlays.push(inlay);
 4755                }
 4756
 4757                self.splice_inlays(vec![], inlays, cx);
 4758            } else {
 4759                let background_color = cx.theme().status().deleted_background;
 4760                self.highlight_text::<InlineCompletionHighlight>(
 4761                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4762                    HighlightStyle {
 4763                        background_color: Some(background_color),
 4764                        ..Default::default()
 4765                    },
 4766                    cx,
 4767                );
 4768            }
 4769
 4770            invalidation_row_range = edit_start_row..edit_end_row;
 4771            completion = InlineCompletion::Edit(edits);
 4772        };
 4773
 4774        let invalidation_range = multibuffer
 4775            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4776            ..multibuffer.anchor_after(Point::new(
 4777                invalidation_row_range.end,
 4778                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4779            ));
 4780
 4781        self.active_inline_completion = Some(InlineCompletionState {
 4782            inlay_ids,
 4783            completion,
 4784            invalidation_range,
 4785        });
 4786        cx.notify();
 4787
 4788        Some(())
 4789    }
 4790
 4791    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4792        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4793    }
 4794
 4795    fn render_code_actions_indicator(
 4796        &self,
 4797        _style: &EditorStyle,
 4798        row: DisplayRow,
 4799        is_active: bool,
 4800        cx: &mut ViewContext<Self>,
 4801    ) -> Option<IconButton> {
 4802        if self.available_code_actions.is_some() {
 4803            Some(
 4804                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4805                    .shape(ui::IconButtonShape::Square)
 4806                    .icon_size(IconSize::XSmall)
 4807                    .icon_color(Color::Muted)
 4808                    .toggle_state(is_active)
 4809                    .tooltip({
 4810                        let focus_handle = self.focus_handle.clone();
 4811                        move |cx| {
 4812                            Tooltip::for_action_in(
 4813                                "Toggle Code Actions",
 4814                                &ToggleCodeActions {
 4815                                    deployed_from_indicator: None,
 4816                                },
 4817                                &focus_handle,
 4818                                cx,
 4819                            )
 4820                        }
 4821                    })
 4822                    .on_click(cx.listener(move |editor, _e, cx| {
 4823                        editor.focus(cx);
 4824                        editor.toggle_code_actions(
 4825                            &ToggleCodeActions {
 4826                                deployed_from_indicator: Some(row),
 4827                            },
 4828                            cx,
 4829                        );
 4830                    })),
 4831            )
 4832        } else {
 4833            None
 4834        }
 4835    }
 4836
 4837    fn clear_tasks(&mut self) {
 4838        self.tasks.clear()
 4839    }
 4840
 4841    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4842        if self.tasks.insert(key, value).is_some() {
 4843            // This case should hopefully be rare, but just in case...
 4844            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4845        }
 4846    }
 4847
 4848    fn build_tasks_context(
 4849        project: &Model<Project>,
 4850        buffer: &Model<Buffer>,
 4851        buffer_row: u32,
 4852        tasks: &Arc<RunnableTasks>,
 4853        cx: &mut ViewContext<Self>,
 4854    ) -> Task<Option<task::TaskContext>> {
 4855        let position = Point::new(buffer_row, tasks.column);
 4856        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4857        let location = Location {
 4858            buffer: buffer.clone(),
 4859            range: range_start..range_start,
 4860        };
 4861        // Fill in the environmental variables from the tree-sitter captures
 4862        let mut captured_task_variables = TaskVariables::default();
 4863        for (capture_name, value) in tasks.extra_variables.clone() {
 4864            captured_task_variables.insert(
 4865                task::VariableName::Custom(capture_name.into()),
 4866                value.clone(),
 4867            );
 4868        }
 4869        project.update(cx, |project, cx| {
 4870            project.task_store().update(cx, |task_store, cx| {
 4871                task_store.task_context_for_location(captured_task_variables, location, cx)
 4872            })
 4873        })
 4874    }
 4875
 4876    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4877        let Some((workspace, _)) = self.workspace.clone() else {
 4878            return;
 4879        };
 4880        let Some(project) = self.project.clone() else {
 4881            return;
 4882        };
 4883
 4884        // Try to find a closest, enclosing node using tree-sitter that has a
 4885        // task
 4886        let Some((buffer, buffer_row, tasks)) = self
 4887            .find_enclosing_node_task(cx)
 4888            // Or find the task that's closest in row-distance.
 4889            .or_else(|| self.find_closest_task(cx))
 4890        else {
 4891            return;
 4892        };
 4893
 4894        let reveal_strategy = action.reveal;
 4895        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 4896        cx.spawn(|_, mut cx| async move {
 4897            let context = task_context.await?;
 4898            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 4899
 4900            let resolved = resolved_task.resolved.as_mut()?;
 4901            resolved.reveal = reveal_strategy;
 4902
 4903            workspace
 4904                .update(&mut cx, |workspace, cx| {
 4905                    workspace::tasks::schedule_resolved_task(
 4906                        workspace,
 4907                        task_source_kind,
 4908                        resolved_task,
 4909                        false,
 4910                        cx,
 4911                    );
 4912                })
 4913                .ok()
 4914        })
 4915        .detach();
 4916    }
 4917
 4918    fn find_closest_task(
 4919        &mut self,
 4920        cx: &mut ViewContext<Self>,
 4921    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4922        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 4923
 4924        let ((buffer_id, row), tasks) = self
 4925            .tasks
 4926            .iter()
 4927            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 4928
 4929        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 4930        let tasks = Arc::new(tasks.to_owned());
 4931        Some((buffer, *row, tasks))
 4932    }
 4933
 4934    fn find_enclosing_node_task(
 4935        &mut self,
 4936        cx: &mut ViewContext<Self>,
 4937    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4938        let snapshot = self.buffer.read(cx).snapshot(cx);
 4939        let offset = self.selections.newest::<usize>(cx).head();
 4940        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 4941        let buffer_id = excerpt.buffer().remote_id();
 4942
 4943        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 4944        let mut cursor = layer.node().walk();
 4945
 4946        while cursor.goto_first_child_for_byte(offset).is_some() {
 4947            if cursor.node().end_byte() == offset {
 4948                cursor.goto_next_sibling();
 4949            }
 4950        }
 4951
 4952        // Ascend to the smallest ancestor that contains the range and has a task.
 4953        loop {
 4954            let node = cursor.node();
 4955            let node_range = node.byte_range();
 4956            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 4957
 4958            // Check if this node contains our offset
 4959            if node_range.start <= offset && node_range.end >= offset {
 4960                // If it contains offset, check for task
 4961                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 4962                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 4963                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 4964                }
 4965            }
 4966
 4967            if !cursor.goto_parent() {
 4968                break;
 4969            }
 4970        }
 4971        None
 4972    }
 4973
 4974    fn render_run_indicator(
 4975        &self,
 4976        _style: &EditorStyle,
 4977        is_active: bool,
 4978        row: DisplayRow,
 4979        cx: &mut ViewContext<Self>,
 4980    ) -> IconButton {
 4981        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 4982            .shape(ui::IconButtonShape::Square)
 4983            .icon_size(IconSize::XSmall)
 4984            .icon_color(Color::Muted)
 4985            .toggle_state(is_active)
 4986            .on_click(cx.listener(move |editor, _e, cx| {
 4987                editor.focus(cx);
 4988                editor.toggle_code_actions(
 4989                    &ToggleCodeActions {
 4990                        deployed_from_indicator: Some(row),
 4991                    },
 4992                    cx,
 4993                );
 4994            }))
 4995    }
 4996
 4997    #[cfg(feature = "test-support")]
 4998    pub fn context_menu_visible(&self) -> bool {
 4999        self.context_menu
 5000            .borrow()
 5001            .as_ref()
 5002            .map_or(false, |menu| menu.visible())
 5003    }
 5004
 5005    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5006        self.context_menu
 5007            .borrow()
 5008            .as_ref()
 5009            .map(|menu| menu.origin(cursor_position))
 5010    }
 5011
 5012    fn render_context_menu(
 5013        &self,
 5014        style: &EditorStyle,
 5015        max_height_in_lines: u32,
 5016        cx: &mut ViewContext<Editor>,
 5017    ) -> Option<AnyElement> {
 5018        self.context_menu.borrow().as_ref().and_then(|menu| {
 5019            if menu.visible() {
 5020                Some(menu.render(
 5021                    style,
 5022                    max_height_in_lines,
 5023                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5024                    cx,
 5025                ))
 5026            } else {
 5027                None
 5028            }
 5029        })
 5030    }
 5031
 5032    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5033        cx.notify();
 5034        self.completion_tasks.clear();
 5035        self.context_menu.borrow_mut().take()
 5036    }
 5037
 5038    fn show_snippet_choices(
 5039        &mut self,
 5040        choices: &Vec<String>,
 5041        selection: Range<Anchor>,
 5042        cx: &mut ViewContext<Self>,
 5043    ) {
 5044        if selection.start.buffer_id.is_none() {
 5045            return;
 5046        }
 5047        let buffer_id = selection.start.buffer_id.unwrap();
 5048        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5049        let id = post_inc(&mut self.next_completion_id);
 5050
 5051        if let Some(buffer) = buffer {
 5052            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5053                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5054            ));
 5055        }
 5056    }
 5057
 5058    pub fn insert_snippet(
 5059        &mut self,
 5060        insertion_ranges: &[Range<usize>],
 5061        snippet: Snippet,
 5062        cx: &mut ViewContext<Self>,
 5063    ) -> Result<()> {
 5064        struct Tabstop<T> {
 5065            is_end_tabstop: bool,
 5066            ranges: Vec<Range<T>>,
 5067            choices: Option<Vec<String>>,
 5068        }
 5069
 5070        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5071            let snippet_text: Arc<str> = snippet.text.clone().into();
 5072            buffer.edit(
 5073                insertion_ranges
 5074                    .iter()
 5075                    .cloned()
 5076                    .map(|range| (range, snippet_text.clone())),
 5077                Some(AutoindentMode::EachLine),
 5078                cx,
 5079            );
 5080
 5081            let snapshot = &*buffer.read(cx);
 5082            let snippet = &snippet;
 5083            snippet
 5084                .tabstops
 5085                .iter()
 5086                .map(|tabstop| {
 5087                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5088                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5089                    });
 5090                    let mut tabstop_ranges = tabstop
 5091                        .ranges
 5092                        .iter()
 5093                        .flat_map(|tabstop_range| {
 5094                            let mut delta = 0_isize;
 5095                            insertion_ranges.iter().map(move |insertion_range| {
 5096                                let insertion_start = insertion_range.start as isize + delta;
 5097                                delta +=
 5098                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5099
 5100                                let start = ((insertion_start + tabstop_range.start) as usize)
 5101                                    .min(snapshot.len());
 5102                                let end = ((insertion_start + tabstop_range.end) as usize)
 5103                                    .min(snapshot.len());
 5104                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5105                            })
 5106                        })
 5107                        .collect::<Vec<_>>();
 5108                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5109
 5110                    Tabstop {
 5111                        is_end_tabstop,
 5112                        ranges: tabstop_ranges,
 5113                        choices: tabstop.choices.clone(),
 5114                    }
 5115                })
 5116                .collect::<Vec<_>>()
 5117        });
 5118        if let Some(tabstop) = tabstops.first() {
 5119            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5120                s.select_ranges(tabstop.ranges.iter().cloned());
 5121            });
 5122
 5123            if let Some(choices) = &tabstop.choices {
 5124                if let Some(selection) = tabstop.ranges.first() {
 5125                    self.show_snippet_choices(choices, selection.clone(), cx)
 5126                }
 5127            }
 5128
 5129            // If we're already at the last tabstop and it's at the end of the snippet,
 5130            // we're done, we don't need to keep the state around.
 5131            if !tabstop.is_end_tabstop {
 5132                let choices = tabstops
 5133                    .iter()
 5134                    .map(|tabstop| tabstop.choices.clone())
 5135                    .collect();
 5136
 5137                let ranges = tabstops
 5138                    .into_iter()
 5139                    .map(|tabstop| tabstop.ranges)
 5140                    .collect::<Vec<_>>();
 5141
 5142                self.snippet_stack.push(SnippetState {
 5143                    active_index: 0,
 5144                    ranges,
 5145                    choices,
 5146                });
 5147            }
 5148
 5149            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5150            if self.autoclose_regions.is_empty() {
 5151                let snapshot = self.buffer.read(cx).snapshot(cx);
 5152                for selection in &mut self.selections.all::<Point>(cx) {
 5153                    let selection_head = selection.head();
 5154                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5155                        continue;
 5156                    };
 5157
 5158                    let mut bracket_pair = None;
 5159                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5160                    let prev_chars = snapshot
 5161                        .reversed_chars_at(selection_head)
 5162                        .collect::<String>();
 5163                    for (pair, enabled) in scope.brackets() {
 5164                        if enabled
 5165                            && pair.close
 5166                            && prev_chars.starts_with(pair.start.as_str())
 5167                            && next_chars.starts_with(pair.end.as_str())
 5168                        {
 5169                            bracket_pair = Some(pair.clone());
 5170                            break;
 5171                        }
 5172                    }
 5173                    if let Some(pair) = bracket_pair {
 5174                        let start = snapshot.anchor_after(selection_head);
 5175                        let end = snapshot.anchor_after(selection_head);
 5176                        self.autoclose_regions.push(AutocloseRegion {
 5177                            selection_id: selection.id,
 5178                            range: start..end,
 5179                            pair,
 5180                        });
 5181                    }
 5182                }
 5183            }
 5184        }
 5185        Ok(())
 5186    }
 5187
 5188    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5189        self.move_to_snippet_tabstop(Bias::Right, cx)
 5190    }
 5191
 5192    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5193        self.move_to_snippet_tabstop(Bias::Left, cx)
 5194    }
 5195
 5196    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5197        if let Some(mut snippet) = self.snippet_stack.pop() {
 5198            match bias {
 5199                Bias::Left => {
 5200                    if snippet.active_index > 0 {
 5201                        snippet.active_index -= 1;
 5202                    } else {
 5203                        self.snippet_stack.push(snippet);
 5204                        return false;
 5205                    }
 5206                }
 5207                Bias::Right => {
 5208                    if snippet.active_index + 1 < snippet.ranges.len() {
 5209                        snippet.active_index += 1;
 5210                    } else {
 5211                        self.snippet_stack.push(snippet);
 5212                        return false;
 5213                    }
 5214                }
 5215            }
 5216            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5217                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5218                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5219                });
 5220
 5221                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5222                    if let Some(selection) = current_ranges.first() {
 5223                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5224                    }
 5225                }
 5226
 5227                // If snippet state is not at the last tabstop, push it back on the stack
 5228                if snippet.active_index + 1 < snippet.ranges.len() {
 5229                    self.snippet_stack.push(snippet);
 5230                }
 5231                return true;
 5232            }
 5233        }
 5234
 5235        false
 5236    }
 5237
 5238    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5239        self.transact(cx, |this, cx| {
 5240            this.select_all(&SelectAll, cx);
 5241            this.insert("", cx);
 5242        });
 5243    }
 5244
 5245    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5246        self.transact(cx, |this, cx| {
 5247            this.select_autoclose_pair(cx);
 5248            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5249            if !this.linked_edit_ranges.is_empty() {
 5250                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5251                let snapshot = this.buffer.read(cx).snapshot(cx);
 5252
 5253                for selection in selections.iter() {
 5254                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5255                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5256                    if selection_start.buffer_id != selection_end.buffer_id {
 5257                        continue;
 5258                    }
 5259                    if let Some(ranges) =
 5260                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5261                    {
 5262                        for (buffer, entries) in ranges {
 5263                            linked_ranges.entry(buffer).or_default().extend(entries);
 5264                        }
 5265                    }
 5266                }
 5267            }
 5268
 5269            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5270            if !this.selections.line_mode {
 5271                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5272                for selection in &mut selections {
 5273                    if selection.is_empty() {
 5274                        let old_head = selection.head();
 5275                        let mut new_head =
 5276                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5277                                .to_point(&display_map);
 5278                        if let Some((buffer, line_buffer_range)) = display_map
 5279                            .buffer_snapshot
 5280                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5281                        {
 5282                            let indent_size =
 5283                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5284                            let indent_len = match indent_size.kind {
 5285                                IndentKind::Space => {
 5286                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5287                                }
 5288                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5289                            };
 5290                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5291                                let indent_len = indent_len.get();
 5292                                new_head = cmp::min(
 5293                                    new_head,
 5294                                    MultiBufferPoint::new(
 5295                                        old_head.row,
 5296                                        ((old_head.column - 1) / indent_len) * indent_len,
 5297                                    ),
 5298                                );
 5299                            }
 5300                        }
 5301
 5302                        selection.set_head(new_head, SelectionGoal::None);
 5303                    }
 5304                }
 5305            }
 5306
 5307            this.signature_help_state.set_backspace_pressed(true);
 5308            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5309            this.insert("", cx);
 5310            let empty_str: Arc<str> = Arc::from("");
 5311            for (buffer, edits) in linked_ranges {
 5312                let snapshot = buffer.read(cx).snapshot();
 5313                use text::ToPoint as TP;
 5314
 5315                let edits = edits
 5316                    .into_iter()
 5317                    .map(|range| {
 5318                        let end_point = TP::to_point(&range.end, &snapshot);
 5319                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5320
 5321                        if end_point == start_point {
 5322                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5323                                .saturating_sub(1);
 5324                            start_point = TP::to_point(&offset, &snapshot);
 5325                        };
 5326
 5327                        (start_point..end_point, empty_str.clone())
 5328                    })
 5329                    .sorted_by_key(|(range, _)| range.start)
 5330                    .collect::<Vec<_>>();
 5331                buffer.update(cx, |this, cx| {
 5332                    this.edit(edits, None, cx);
 5333                })
 5334            }
 5335            this.refresh_inline_completion(true, false, cx);
 5336            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5337        });
 5338    }
 5339
 5340    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5341        self.transact(cx, |this, cx| {
 5342            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5343                let line_mode = s.line_mode;
 5344                s.move_with(|map, selection| {
 5345                    if selection.is_empty() && !line_mode {
 5346                        let cursor = movement::right(map, selection.head());
 5347                        selection.end = cursor;
 5348                        selection.reversed = true;
 5349                        selection.goal = SelectionGoal::None;
 5350                    }
 5351                })
 5352            });
 5353            this.insert("", cx);
 5354            this.refresh_inline_completion(true, false, cx);
 5355        });
 5356    }
 5357
 5358    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5359        if self.move_to_prev_snippet_tabstop(cx) {
 5360            return;
 5361        }
 5362
 5363        self.outdent(&Outdent, cx);
 5364    }
 5365
 5366    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5367        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5368            return;
 5369        }
 5370
 5371        let mut selections = self.selections.all_adjusted(cx);
 5372        let buffer = self.buffer.read(cx);
 5373        let snapshot = buffer.snapshot(cx);
 5374        let rows_iter = selections.iter().map(|s| s.head().row);
 5375        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5376
 5377        let mut edits = Vec::new();
 5378        let mut prev_edited_row = 0;
 5379        let mut row_delta = 0;
 5380        for selection in &mut selections {
 5381            if selection.start.row != prev_edited_row {
 5382                row_delta = 0;
 5383            }
 5384            prev_edited_row = selection.end.row;
 5385
 5386            // If the selection is non-empty, then increase the indentation of the selected lines.
 5387            if !selection.is_empty() {
 5388                row_delta =
 5389                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5390                continue;
 5391            }
 5392
 5393            // If the selection is empty and the cursor is in the leading whitespace before the
 5394            // suggested indentation, then auto-indent the line.
 5395            let cursor = selection.head();
 5396            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5397            if let Some(suggested_indent) =
 5398                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5399            {
 5400                if cursor.column < suggested_indent.len
 5401                    && cursor.column <= current_indent.len
 5402                    && current_indent.len <= suggested_indent.len
 5403                {
 5404                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5405                    selection.end = selection.start;
 5406                    if row_delta == 0 {
 5407                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5408                            cursor.row,
 5409                            current_indent,
 5410                            suggested_indent,
 5411                        ));
 5412                        row_delta = suggested_indent.len - current_indent.len;
 5413                    }
 5414                    continue;
 5415                }
 5416            }
 5417
 5418            // Otherwise, insert a hard or soft tab.
 5419            let settings = buffer.settings_at(cursor, cx);
 5420            let tab_size = if settings.hard_tabs {
 5421                IndentSize::tab()
 5422            } else {
 5423                let tab_size = settings.tab_size.get();
 5424                let char_column = snapshot
 5425                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5426                    .flat_map(str::chars)
 5427                    .count()
 5428                    + row_delta as usize;
 5429                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5430                IndentSize::spaces(chars_to_next_tab_stop)
 5431            };
 5432            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5433            selection.end = selection.start;
 5434            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5435            row_delta += tab_size.len;
 5436        }
 5437
 5438        self.transact(cx, |this, cx| {
 5439            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5440            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5441            this.refresh_inline_completion(true, false, cx);
 5442        });
 5443    }
 5444
 5445    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5446        if self.read_only(cx) {
 5447            return;
 5448        }
 5449        let mut selections = self.selections.all::<Point>(cx);
 5450        let mut prev_edited_row = 0;
 5451        let mut row_delta = 0;
 5452        let mut edits = Vec::new();
 5453        let buffer = self.buffer.read(cx);
 5454        let snapshot = buffer.snapshot(cx);
 5455        for selection in &mut selections {
 5456            if selection.start.row != prev_edited_row {
 5457                row_delta = 0;
 5458            }
 5459            prev_edited_row = selection.end.row;
 5460
 5461            row_delta =
 5462                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5463        }
 5464
 5465        self.transact(cx, |this, cx| {
 5466            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5467            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5468        });
 5469    }
 5470
 5471    fn indent_selection(
 5472        buffer: &MultiBuffer,
 5473        snapshot: &MultiBufferSnapshot,
 5474        selection: &mut Selection<Point>,
 5475        edits: &mut Vec<(Range<Point>, String)>,
 5476        delta_for_start_row: u32,
 5477        cx: &AppContext,
 5478    ) -> u32 {
 5479        let settings = buffer.settings_at(selection.start, cx);
 5480        let tab_size = settings.tab_size.get();
 5481        let indent_kind = if settings.hard_tabs {
 5482            IndentKind::Tab
 5483        } else {
 5484            IndentKind::Space
 5485        };
 5486        let mut start_row = selection.start.row;
 5487        let mut end_row = selection.end.row + 1;
 5488
 5489        // If a selection ends at the beginning of a line, don't indent
 5490        // that last line.
 5491        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5492            end_row -= 1;
 5493        }
 5494
 5495        // Avoid re-indenting a row that has already been indented by a
 5496        // previous selection, but still update this selection's column
 5497        // to reflect that indentation.
 5498        if delta_for_start_row > 0 {
 5499            start_row += 1;
 5500            selection.start.column += delta_for_start_row;
 5501            if selection.end.row == selection.start.row {
 5502                selection.end.column += delta_for_start_row;
 5503            }
 5504        }
 5505
 5506        let mut delta_for_end_row = 0;
 5507        let has_multiple_rows = start_row + 1 != end_row;
 5508        for row in start_row..end_row {
 5509            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5510            let indent_delta = match (current_indent.kind, indent_kind) {
 5511                (IndentKind::Space, IndentKind::Space) => {
 5512                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5513                    IndentSize::spaces(columns_to_next_tab_stop)
 5514                }
 5515                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5516                (_, IndentKind::Tab) => IndentSize::tab(),
 5517            };
 5518
 5519            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5520                0
 5521            } else {
 5522                selection.start.column
 5523            };
 5524            let row_start = Point::new(row, start);
 5525            edits.push((
 5526                row_start..row_start,
 5527                indent_delta.chars().collect::<String>(),
 5528            ));
 5529
 5530            // Update this selection's endpoints to reflect the indentation.
 5531            if row == selection.start.row {
 5532                selection.start.column += indent_delta.len;
 5533            }
 5534            if row == selection.end.row {
 5535                selection.end.column += indent_delta.len;
 5536                delta_for_end_row = indent_delta.len;
 5537            }
 5538        }
 5539
 5540        if selection.start.row == selection.end.row {
 5541            delta_for_start_row + delta_for_end_row
 5542        } else {
 5543            delta_for_end_row
 5544        }
 5545    }
 5546
 5547    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5548        if self.read_only(cx) {
 5549            return;
 5550        }
 5551        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5552        let selections = self.selections.all::<Point>(cx);
 5553        let mut deletion_ranges = Vec::new();
 5554        let mut last_outdent = None;
 5555        {
 5556            let buffer = self.buffer.read(cx);
 5557            let snapshot = buffer.snapshot(cx);
 5558            for selection in &selections {
 5559                let settings = buffer.settings_at(selection.start, cx);
 5560                let tab_size = settings.tab_size.get();
 5561                let mut rows = selection.spanned_rows(false, &display_map);
 5562
 5563                // Avoid re-outdenting a row that has already been outdented by a
 5564                // previous selection.
 5565                if let Some(last_row) = last_outdent {
 5566                    if last_row == rows.start {
 5567                        rows.start = rows.start.next_row();
 5568                    }
 5569                }
 5570                let has_multiple_rows = rows.len() > 1;
 5571                for row in rows.iter_rows() {
 5572                    let indent_size = snapshot.indent_size_for_line(row);
 5573                    if indent_size.len > 0 {
 5574                        let deletion_len = match indent_size.kind {
 5575                            IndentKind::Space => {
 5576                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5577                                if columns_to_prev_tab_stop == 0 {
 5578                                    tab_size
 5579                                } else {
 5580                                    columns_to_prev_tab_stop
 5581                                }
 5582                            }
 5583                            IndentKind::Tab => 1,
 5584                        };
 5585                        let start = if has_multiple_rows
 5586                            || deletion_len > selection.start.column
 5587                            || indent_size.len < selection.start.column
 5588                        {
 5589                            0
 5590                        } else {
 5591                            selection.start.column - deletion_len
 5592                        };
 5593                        deletion_ranges.push(
 5594                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5595                        );
 5596                        last_outdent = Some(row);
 5597                    }
 5598                }
 5599            }
 5600        }
 5601
 5602        self.transact(cx, |this, cx| {
 5603            this.buffer.update(cx, |buffer, cx| {
 5604                let empty_str: Arc<str> = Arc::default();
 5605                buffer.edit(
 5606                    deletion_ranges
 5607                        .into_iter()
 5608                        .map(|range| (range, empty_str.clone())),
 5609                    None,
 5610                    cx,
 5611                );
 5612            });
 5613            let selections = this.selections.all::<usize>(cx);
 5614            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5615        });
 5616    }
 5617
 5618    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5619        if self.read_only(cx) {
 5620            return;
 5621        }
 5622        let selections = self
 5623            .selections
 5624            .all::<usize>(cx)
 5625            .into_iter()
 5626            .map(|s| s.range());
 5627
 5628        self.transact(cx, |this, cx| {
 5629            this.buffer.update(cx, |buffer, cx| {
 5630                buffer.autoindent_ranges(selections, cx);
 5631            });
 5632            let selections = this.selections.all::<usize>(cx);
 5633            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5634        });
 5635    }
 5636
 5637    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5638        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5639        let selections = self.selections.all::<Point>(cx);
 5640
 5641        let mut new_cursors = Vec::new();
 5642        let mut edit_ranges = Vec::new();
 5643        let mut selections = selections.iter().peekable();
 5644        while let Some(selection) = selections.next() {
 5645            let mut rows = selection.spanned_rows(false, &display_map);
 5646            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5647
 5648            // Accumulate contiguous regions of rows that we want to delete.
 5649            while let Some(next_selection) = selections.peek() {
 5650                let next_rows = next_selection.spanned_rows(false, &display_map);
 5651                if next_rows.start <= rows.end {
 5652                    rows.end = next_rows.end;
 5653                    selections.next().unwrap();
 5654                } else {
 5655                    break;
 5656                }
 5657            }
 5658
 5659            let buffer = &display_map.buffer_snapshot;
 5660            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5661            let edit_end;
 5662            let cursor_buffer_row;
 5663            if buffer.max_point().row >= rows.end.0 {
 5664                // If there's a line after the range, delete the \n from the end of the row range
 5665                // and position the cursor on the next line.
 5666                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5667                cursor_buffer_row = rows.end;
 5668            } else {
 5669                // If there isn't a line after the range, delete the \n from the line before the
 5670                // start of the row range and position the cursor there.
 5671                edit_start = edit_start.saturating_sub(1);
 5672                edit_end = buffer.len();
 5673                cursor_buffer_row = rows.start.previous_row();
 5674            }
 5675
 5676            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5677            *cursor.column_mut() =
 5678                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5679
 5680            new_cursors.push((
 5681                selection.id,
 5682                buffer.anchor_after(cursor.to_point(&display_map)),
 5683            ));
 5684            edit_ranges.push(edit_start..edit_end);
 5685        }
 5686
 5687        self.transact(cx, |this, cx| {
 5688            let buffer = this.buffer.update(cx, |buffer, cx| {
 5689                let empty_str: Arc<str> = Arc::default();
 5690                buffer.edit(
 5691                    edit_ranges
 5692                        .into_iter()
 5693                        .map(|range| (range, empty_str.clone())),
 5694                    None,
 5695                    cx,
 5696                );
 5697                buffer.snapshot(cx)
 5698            });
 5699            let new_selections = new_cursors
 5700                .into_iter()
 5701                .map(|(id, cursor)| {
 5702                    let cursor = cursor.to_point(&buffer);
 5703                    Selection {
 5704                        id,
 5705                        start: cursor,
 5706                        end: cursor,
 5707                        reversed: false,
 5708                        goal: SelectionGoal::None,
 5709                    }
 5710                })
 5711                .collect();
 5712
 5713            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5714                s.select(new_selections);
 5715            });
 5716        });
 5717    }
 5718
 5719    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5720        if self.read_only(cx) {
 5721            return;
 5722        }
 5723        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5724        for selection in self.selections.all::<Point>(cx) {
 5725            let start = MultiBufferRow(selection.start.row);
 5726            // Treat single line selections as if they include the next line. Otherwise this action
 5727            // would do nothing for single line selections individual cursors.
 5728            let end = if selection.start.row == selection.end.row {
 5729                MultiBufferRow(selection.start.row + 1)
 5730            } else {
 5731                MultiBufferRow(selection.end.row)
 5732            };
 5733
 5734            if let Some(last_row_range) = row_ranges.last_mut() {
 5735                if start <= last_row_range.end {
 5736                    last_row_range.end = end;
 5737                    continue;
 5738                }
 5739            }
 5740            row_ranges.push(start..end);
 5741        }
 5742
 5743        let snapshot = self.buffer.read(cx).snapshot(cx);
 5744        let mut cursor_positions = Vec::new();
 5745        for row_range in &row_ranges {
 5746            let anchor = snapshot.anchor_before(Point::new(
 5747                row_range.end.previous_row().0,
 5748                snapshot.line_len(row_range.end.previous_row()),
 5749            ));
 5750            cursor_positions.push(anchor..anchor);
 5751        }
 5752
 5753        self.transact(cx, |this, cx| {
 5754            for row_range in row_ranges.into_iter().rev() {
 5755                for row in row_range.iter_rows().rev() {
 5756                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5757                    let next_line_row = row.next_row();
 5758                    let indent = snapshot.indent_size_for_line(next_line_row);
 5759                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5760
 5761                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5762                        " "
 5763                    } else {
 5764                        ""
 5765                    };
 5766
 5767                    this.buffer.update(cx, |buffer, cx| {
 5768                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5769                    });
 5770                }
 5771            }
 5772
 5773            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5774                s.select_anchor_ranges(cursor_positions)
 5775            });
 5776        });
 5777    }
 5778
 5779    pub fn sort_lines_case_sensitive(
 5780        &mut self,
 5781        _: &SortLinesCaseSensitive,
 5782        cx: &mut ViewContext<Self>,
 5783    ) {
 5784        self.manipulate_lines(cx, |lines| lines.sort())
 5785    }
 5786
 5787    pub fn sort_lines_case_insensitive(
 5788        &mut self,
 5789        _: &SortLinesCaseInsensitive,
 5790        cx: &mut ViewContext<Self>,
 5791    ) {
 5792        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5793    }
 5794
 5795    pub fn unique_lines_case_insensitive(
 5796        &mut self,
 5797        _: &UniqueLinesCaseInsensitive,
 5798        cx: &mut ViewContext<Self>,
 5799    ) {
 5800        self.manipulate_lines(cx, |lines| {
 5801            let mut seen = HashSet::default();
 5802            lines.retain(|line| seen.insert(line.to_lowercase()));
 5803        })
 5804    }
 5805
 5806    pub fn unique_lines_case_sensitive(
 5807        &mut self,
 5808        _: &UniqueLinesCaseSensitive,
 5809        cx: &mut ViewContext<Self>,
 5810    ) {
 5811        self.manipulate_lines(cx, |lines| {
 5812            let mut seen = HashSet::default();
 5813            lines.retain(|line| seen.insert(*line));
 5814        })
 5815    }
 5816
 5817    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5818        let mut revert_changes = HashMap::default();
 5819        let snapshot = self.snapshot(cx);
 5820        for hunk in hunks_for_ranges(
 5821            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5822            &snapshot,
 5823        ) {
 5824            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5825        }
 5826        if !revert_changes.is_empty() {
 5827            self.transact(cx, |editor, cx| {
 5828                editor.revert(revert_changes, cx);
 5829            });
 5830        }
 5831    }
 5832
 5833    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5834        let Some(project) = self.project.clone() else {
 5835            return;
 5836        };
 5837        self.reload(project, cx).detach_and_notify_err(cx);
 5838    }
 5839
 5840    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5841        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5842        if !revert_changes.is_empty() {
 5843            self.transact(cx, |editor, cx| {
 5844                editor.revert(revert_changes, cx);
 5845            });
 5846        }
 5847    }
 5848
 5849    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5850        let snapshot = self.buffer.read(cx).read(cx);
 5851        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5852            drop(snapshot);
 5853            let mut revert_changes = HashMap::default();
 5854            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5855            if !revert_changes.is_empty() {
 5856                self.revert(revert_changes, cx)
 5857            }
 5858        }
 5859    }
 5860
 5861    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5862        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5863            let project_path = buffer.read(cx).project_path(cx)?;
 5864            let project = self.project.as_ref()?.read(cx);
 5865            let entry = project.entry_for_path(&project_path, cx)?;
 5866            let parent = match &entry.canonical_path {
 5867                Some(canonical_path) => canonical_path.to_path_buf(),
 5868                None => project.absolute_path(&project_path, cx)?,
 5869            }
 5870            .parent()?
 5871            .to_path_buf();
 5872            Some(parent)
 5873        }) {
 5874            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5875        }
 5876    }
 5877
 5878    fn gather_revert_changes(
 5879        &mut self,
 5880        selections: &[Selection<Point>],
 5881        cx: &mut ViewContext<'_, Editor>,
 5882    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5883        let mut revert_changes = HashMap::default();
 5884        let snapshot = self.snapshot(cx);
 5885        for hunk in hunks_for_selections(&snapshot, selections) {
 5886            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5887        }
 5888        revert_changes
 5889    }
 5890
 5891    pub fn prepare_revert_change(
 5892        &mut self,
 5893        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5894        hunk: &MultiBufferDiffHunk,
 5895        cx: &AppContext,
 5896    ) -> Option<()> {
 5897        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 5898        let buffer = buffer.read(cx);
 5899        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 5900        let original_text = change_set
 5901            .read(cx)
 5902            .base_text
 5903            .as_ref()?
 5904            .read(cx)
 5905            .as_rope()
 5906            .slice(hunk.diff_base_byte_range.clone());
 5907        let buffer_snapshot = buffer.snapshot();
 5908        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5909        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5910            probe
 5911                .0
 5912                .start
 5913                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5914                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5915        }) {
 5916            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5917            Some(())
 5918        } else {
 5919            None
 5920        }
 5921    }
 5922
 5923    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5924        self.manipulate_lines(cx, |lines| lines.reverse())
 5925    }
 5926
 5927    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5928        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5929    }
 5930
 5931    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5932    where
 5933        Fn: FnMut(&mut Vec<&str>),
 5934    {
 5935        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5936        let buffer = self.buffer.read(cx).snapshot(cx);
 5937
 5938        let mut edits = Vec::new();
 5939
 5940        let selections = self.selections.all::<Point>(cx);
 5941        let mut selections = selections.iter().peekable();
 5942        let mut contiguous_row_selections = Vec::new();
 5943        let mut new_selections = Vec::new();
 5944        let mut added_lines = 0;
 5945        let mut removed_lines = 0;
 5946
 5947        while let Some(selection) = selections.next() {
 5948            let (start_row, end_row) = consume_contiguous_rows(
 5949                &mut contiguous_row_selections,
 5950                selection,
 5951                &display_map,
 5952                &mut selections,
 5953            );
 5954
 5955            let start_point = Point::new(start_row.0, 0);
 5956            let end_point = Point::new(
 5957                end_row.previous_row().0,
 5958                buffer.line_len(end_row.previous_row()),
 5959            );
 5960            let text = buffer
 5961                .text_for_range(start_point..end_point)
 5962                .collect::<String>();
 5963
 5964            let mut lines = text.split('\n').collect_vec();
 5965
 5966            let lines_before = lines.len();
 5967            callback(&mut lines);
 5968            let lines_after = lines.len();
 5969
 5970            edits.push((start_point..end_point, lines.join("\n")));
 5971
 5972            // Selections must change based on added and removed line count
 5973            let start_row =
 5974                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5975            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5976            new_selections.push(Selection {
 5977                id: selection.id,
 5978                start: start_row,
 5979                end: end_row,
 5980                goal: SelectionGoal::None,
 5981                reversed: selection.reversed,
 5982            });
 5983
 5984            if lines_after > lines_before {
 5985                added_lines += lines_after - lines_before;
 5986            } else if lines_before > lines_after {
 5987                removed_lines += lines_before - lines_after;
 5988            }
 5989        }
 5990
 5991        self.transact(cx, |this, cx| {
 5992            let buffer = this.buffer.update(cx, |buffer, cx| {
 5993                buffer.edit(edits, None, cx);
 5994                buffer.snapshot(cx)
 5995            });
 5996
 5997            // Recalculate offsets on newly edited buffer
 5998            let new_selections = new_selections
 5999                .iter()
 6000                .map(|s| {
 6001                    let start_point = Point::new(s.start.0, 0);
 6002                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6003                    Selection {
 6004                        id: s.id,
 6005                        start: buffer.point_to_offset(start_point),
 6006                        end: buffer.point_to_offset(end_point),
 6007                        goal: s.goal,
 6008                        reversed: s.reversed,
 6009                    }
 6010                })
 6011                .collect();
 6012
 6013            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6014                s.select(new_selections);
 6015            });
 6016
 6017            this.request_autoscroll(Autoscroll::fit(), cx);
 6018        });
 6019    }
 6020
 6021    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6022        self.manipulate_text(cx, |text| text.to_uppercase())
 6023    }
 6024
 6025    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6026        self.manipulate_text(cx, |text| text.to_lowercase())
 6027    }
 6028
 6029    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6030        self.manipulate_text(cx, |text| {
 6031            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6032            // https://github.com/rutrum/convert-case/issues/16
 6033            text.split('\n')
 6034                .map(|line| line.to_case(Case::Title))
 6035                .join("\n")
 6036        })
 6037    }
 6038
 6039    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6040        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6041    }
 6042
 6043    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6044        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6045    }
 6046
 6047    pub fn convert_to_upper_camel_case(
 6048        &mut self,
 6049        _: &ConvertToUpperCamelCase,
 6050        cx: &mut ViewContext<Self>,
 6051    ) {
 6052        self.manipulate_text(cx, |text| {
 6053            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6054            // https://github.com/rutrum/convert-case/issues/16
 6055            text.split('\n')
 6056                .map(|line| line.to_case(Case::UpperCamel))
 6057                .join("\n")
 6058        })
 6059    }
 6060
 6061    pub fn convert_to_lower_camel_case(
 6062        &mut self,
 6063        _: &ConvertToLowerCamelCase,
 6064        cx: &mut ViewContext<Self>,
 6065    ) {
 6066        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6067    }
 6068
 6069    pub fn convert_to_opposite_case(
 6070        &mut self,
 6071        _: &ConvertToOppositeCase,
 6072        cx: &mut ViewContext<Self>,
 6073    ) {
 6074        self.manipulate_text(cx, |text| {
 6075            text.chars()
 6076                .fold(String::with_capacity(text.len()), |mut t, c| {
 6077                    if c.is_uppercase() {
 6078                        t.extend(c.to_lowercase());
 6079                    } else {
 6080                        t.extend(c.to_uppercase());
 6081                    }
 6082                    t
 6083                })
 6084        })
 6085    }
 6086
 6087    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6088    where
 6089        Fn: FnMut(&str) -> String,
 6090    {
 6091        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6092        let buffer = self.buffer.read(cx).snapshot(cx);
 6093
 6094        let mut new_selections = Vec::new();
 6095        let mut edits = Vec::new();
 6096        let mut selection_adjustment = 0i32;
 6097
 6098        for selection in self.selections.all::<usize>(cx) {
 6099            let selection_is_empty = selection.is_empty();
 6100
 6101            let (start, end) = if selection_is_empty {
 6102                let word_range = movement::surrounding_word(
 6103                    &display_map,
 6104                    selection.start.to_display_point(&display_map),
 6105                );
 6106                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6107                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6108                (start, end)
 6109            } else {
 6110                (selection.start, selection.end)
 6111            };
 6112
 6113            let text = buffer.text_for_range(start..end).collect::<String>();
 6114            let old_length = text.len() as i32;
 6115            let text = callback(&text);
 6116
 6117            new_selections.push(Selection {
 6118                start: (start as i32 - selection_adjustment) as usize,
 6119                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6120                goal: SelectionGoal::None,
 6121                ..selection
 6122            });
 6123
 6124            selection_adjustment += old_length - text.len() as i32;
 6125
 6126            edits.push((start..end, text));
 6127        }
 6128
 6129        self.transact(cx, |this, cx| {
 6130            this.buffer.update(cx, |buffer, cx| {
 6131                buffer.edit(edits, None, cx);
 6132            });
 6133
 6134            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6135                s.select(new_selections);
 6136            });
 6137
 6138            this.request_autoscroll(Autoscroll::fit(), cx);
 6139        });
 6140    }
 6141
 6142    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6143        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6144        let buffer = &display_map.buffer_snapshot;
 6145        let selections = self.selections.all::<Point>(cx);
 6146
 6147        let mut edits = Vec::new();
 6148        let mut selections_iter = selections.iter().peekable();
 6149        while let Some(selection) = selections_iter.next() {
 6150            let mut rows = selection.spanned_rows(false, &display_map);
 6151            // duplicate line-wise
 6152            if whole_lines || selection.start == selection.end {
 6153                // Avoid duplicating the same lines twice.
 6154                while let Some(next_selection) = selections_iter.peek() {
 6155                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6156                    if next_rows.start < rows.end {
 6157                        rows.end = next_rows.end;
 6158                        selections_iter.next().unwrap();
 6159                    } else {
 6160                        break;
 6161                    }
 6162                }
 6163
 6164                // Copy the text from the selected row region and splice it either at the start
 6165                // or end of the region.
 6166                let start = Point::new(rows.start.0, 0);
 6167                let end = Point::new(
 6168                    rows.end.previous_row().0,
 6169                    buffer.line_len(rows.end.previous_row()),
 6170                );
 6171                let text = buffer
 6172                    .text_for_range(start..end)
 6173                    .chain(Some("\n"))
 6174                    .collect::<String>();
 6175                let insert_location = if upwards {
 6176                    Point::new(rows.end.0, 0)
 6177                } else {
 6178                    start
 6179                };
 6180                edits.push((insert_location..insert_location, text));
 6181            } else {
 6182                // duplicate character-wise
 6183                let start = selection.start;
 6184                let end = selection.end;
 6185                let text = buffer.text_for_range(start..end).collect::<String>();
 6186                edits.push((selection.end..selection.end, text));
 6187            }
 6188        }
 6189
 6190        self.transact(cx, |this, cx| {
 6191            this.buffer.update(cx, |buffer, cx| {
 6192                buffer.edit(edits, None, cx);
 6193            });
 6194
 6195            this.request_autoscroll(Autoscroll::fit(), cx);
 6196        });
 6197    }
 6198
 6199    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6200        self.duplicate(true, true, cx);
 6201    }
 6202
 6203    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6204        self.duplicate(false, true, cx);
 6205    }
 6206
 6207    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6208        self.duplicate(false, false, cx);
 6209    }
 6210
 6211    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6212        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6213        let buffer = self.buffer.read(cx).snapshot(cx);
 6214
 6215        let mut edits = Vec::new();
 6216        let mut unfold_ranges = Vec::new();
 6217        let mut refold_creases = Vec::new();
 6218
 6219        let selections = self.selections.all::<Point>(cx);
 6220        let mut selections = selections.iter().peekable();
 6221        let mut contiguous_row_selections = Vec::new();
 6222        let mut new_selections = Vec::new();
 6223
 6224        while let Some(selection) = selections.next() {
 6225            // Find all the selections that span a contiguous row range
 6226            let (start_row, end_row) = consume_contiguous_rows(
 6227                &mut contiguous_row_selections,
 6228                selection,
 6229                &display_map,
 6230                &mut selections,
 6231            );
 6232
 6233            // Move the text spanned by the row range to be before the line preceding the row range
 6234            if start_row.0 > 0 {
 6235                let range_to_move = Point::new(
 6236                    start_row.previous_row().0,
 6237                    buffer.line_len(start_row.previous_row()),
 6238                )
 6239                    ..Point::new(
 6240                        end_row.previous_row().0,
 6241                        buffer.line_len(end_row.previous_row()),
 6242                    );
 6243                let insertion_point = display_map
 6244                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6245                    .0;
 6246
 6247                // Don't move lines across excerpts
 6248                if buffer
 6249                    .excerpt_boundaries_in_range((
 6250                        Bound::Excluded(insertion_point),
 6251                        Bound::Included(range_to_move.end),
 6252                    ))
 6253                    .next()
 6254                    .is_none()
 6255                {
 6256                    let text = buffer
 6257                        .text_for_range(range_to_move.clone())
 6258                        .flat_map(|s| s.chars())
 6259                        .skip(1)
 6260                        .chain(['\n'])
 6261                        .collect::<String>();
 6262
 6263                    edits.push((
 6264                        buffer.anchor_after(range_to_move.start)
 6265                            ..buffer.anchor_before(range_to_move.end),
 6266                        String::new(),
 6267                    ));
 6268                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6269                    edits.push((insertion_anchor..insertion_anchor, text));
 6270
 6271                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6272
 6273                    // Move selections up
 6274                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6275                        |mut selection| {
 6276                            selection.start.row -= row_delta;
 6277                            selection.end.row -= row_delta;
 6278                            selection
 6279                        },
 6280                    ));
 6281
 6282                    // Move folds up
 6283                    unfold_ranges.push(range_to_move.clone());
 6284                    for fold in display_map.folds_in_range(
 6285                        buffer.anchor_before(range_to_move.start)
 6286                            ..buffer.anchor_after(range_to_move.end),
 6287                    ) {
 6288                        let mut start = fold.range.start.to_point(&buffer);
 6289                        let mut end = fold.range.end.to_point(&buffer);
 6290                        start.row -= row_delta;
 6291                        end.row -= row_delta;
 6292                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6293                    }
 6294                }
 6295            }
 6296
 6297            // If we didn't move line(s), preserve the existing selections
 6298            new_selections.append(&mut contiguous_row_selections);
 6299        }
 6300
 6301        self.transact(cx, |this, cx| {
 6302            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6303            this.buffer.update(cx, |buffer, cx| {
 6304                for (range, text) in edits {
 6305                    buffer.edit([(range, text)], None, cx);
 6306                }
 6307            });
 6308            this.fold_creases(refold_creases, true, cx);
 6309            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6310                s.select(new_selections);
 6311            })
 6312        });
 6313    }
 6314
 6315    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6316        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6317        let buffer = self.buffer.read(cx).snapshot(cx);
 6318
 6319        let mut edits = Vec::new();
 6320        let mut unfold_ranges = Vec::new();
 6321        let mut refold_creases = Vec::new();
 6322
 6323        let selections = self.selections.all::<Point>(cx);
 6324        let mut selections = selections.iter().peekable();
 6325        let mut contiguous_row_selections = Vec::new();
 6326        let mut new_selections = Vec::new();
 6327
 6328        while let Some(selection) = selections.next() {
 6329            // Find all the selections that span a contiguous row range
 6330            let (start_row, end_row) = consume_contiguous_rows(
 6331                &mut contiguous_row_selections,
 6332                selection,
 6333                &display_map,
 6334                &mut selections,
 6335            );
 6336
 6337            // Move the text spanned by the row range to be after the last line of the row range
 6338            if end_row.0 <= buffer.max_point().row {
 6339                let range_to_move =
 6340                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6341                let insertion_point = display_map
 6342                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6343                    .0;
 6344
 6345                // Don't move lines across excerpt boundaries
 6346                if buffer
 6347                    .excerpt_boundaries_in_range((
 6348                        Bound::Excluded(range_to_move.start),
 6349                        Bound::Included(insertion_point),
 6350                    ))
 6351                    .next()
 6352                    .is_none()
 6353                {
 6354                    let mut text = String::from("\n");
 6355                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6356                    text.pop(); // Drop trailing newline
 6357                    edits.push((
 6358                        buffer.anchor_after(range_to_move.start)
 6359                            ..buffer.anchor_before(range_to_move.end),
 6360                        String::new(),
 6361                    ));
 6362                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6363                    edits.push((insertion_anchor..insertion_anchor, text));
 6364
 6365                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6366
 6367                    // Move selections down
 6368                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6369                        |mut selection| {
 6370                            selection.start.row += row_delta;
 6371                            selection.end.row += row_delta;
 6372                            selection
 6373                        },
 6374                    ));
 6375
 6376                    // Move folds down
 6377                    unfold_ranges.push(range_to_move.clone());
 6378                    for fold in display_map.folds_in_range(
 6379                        buffer.anchor_before(range_to_move.start)
 6380                            ..buffer.anchor_after(range_to_move.end),
 6381                    ) {
 6382                        let mut start = fold.range.start.to_point(&buffer);
 6383                        let mut end = fold.range.end.to_point(&buffer);
 6384                        start.row += row_delta;
 6385                        end.row += row_delta;
 6386                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6387                    }
 6388                }
 6389            }
 6390
 6391            // If we didn't move line(s), preserve the existing selections
 6392            new_selections.append(&mut contiguous_row_selections);
 6393        }
 6394
 6395        self.transact(cx, |this, cx| {
 6396            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6397            this.buffer.update(cx, |buffer, cx| {
 6398                for (range, text) in edits {
 6399                    buffer.edit([(range, text)], None, cx);
 6400                }
 6401            });
 6402            this.fold_creases(refold_creases, true, cx);
 6403            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6404        });
 6405    }
 6406
 6407    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6408        let text_layout_details = &self.text_layout_details(cx);
 6409        self.transact(cx, |this, cx| {
 6410            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6411                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6412                let line_mode = s.line_mode;
 6413                s.move_with(|display_map, selection| {
 6414                    if !selection.is_empty() || line_mode {
 6415                        return;
 6416                    }
 6417
 6418                    let mut head = selection.head();
 6419                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6420                    if head.column() == display_map.line_len(head.row()) {
 6421                        transpose_offset = display_map
 6422                            .buffer_snapshot
 6423                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6424                    }
 6425
 6426                    if transpose_offset == 0 {
 6427                        return;
 6428                    }
 6429
 6430                    *head.column_mut() += 1;
 6431                    head = display_map.clip_point(head, Bias::Right);
 6432                    let goal = SelectionGoal::HorizontalPosition(
 6433                        display_map
 6434                            .x_for_display_point(head, text_layout_details)
 6435                            .into(),
 6436                    );
 6437                    selection.collapse_to(head, goal);
 6438
 6439                    let transpose_start = display_map
 6440                        .buffer_snapshot
 6441                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6442                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6443                        let transpose_end = display_map
 6444                            .buffer_snapshot
 6445                            .clip_offset(transpose_offset + 1, Bias::Right);
 6446                        if let Some(ch) =
 6447                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6448                        {
 6449                            edits.push((transpose_start..transpose_offset, String::new()));
 6450                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6451                        }
 6452                    }
 6453                });
 6454                edits
 6455            });
 6456            this.buffer
 6457                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6458            let selections = this.selections.all::<usize>(cx);
 6459            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6460                s.select(selections);
 6461            });
 6462        });
 6463    }
 6464
 6465    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6466        self.rewrap_impl(IsVimMode::No, cx)
 6467    }
 6468
 6469    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6470        let buffer = self.buffer.read(cx).snapshot(cx);
 6471        let selections = self.selections.all::<Point>(cx);
 6472        let mut selections = selections.iter().peekable();
 6473
 6474        let mut edits = Vec::new();
 6475        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6476
 6477        while let Some(selection) = selections.next() {
 6478            let mut start_row = selection.start.row;
 6479            let mut end_row = selection.end.row;
 6480
 6481            // Skip selections that overlap with a range that has already been rewrapped.
 6482            let selection_range = start_row..end_row;
 6483            if rewrapped_row_ranges
 6484                .iter()
 6485                .any(|range| range.overlaps(&selection_range))
 6486            {
 6487                continue;
 6488            }
 6489
 6490            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6491
 6492            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6493                match language_scope.language_name().0.as_ref() {
 6494                    "Markdown" | "Plain Text" => {
 6495                        should_rewrap = true;
 6496                    }
 6497                    _ => {}
 6498                }
 6499            }
 6500
 6501            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6502
 6503            // Since not all lines in the selection may be at the same indent
 6504            // level, choose the indent size that is the most common between all
 6505            // of the lines.
 6506            //
 6507            // If there is a tie, we use the deepest indent.
 6508            let (indent_size, indent_end) = {
 6509                let mut indent_size_occurrences = HashMap::default();
 6510                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6511
 6512                for row in start_row..=end_row {
 6513                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6514                    rows_by_indent_size.entry(indent).or_default().push(row);
 6515                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6516                }
 6517
 6518                let indent_size = indent_size_occurrences
 6519                    .into_iter()
 6520                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6521                    .map(|(indent, _)| indent)
 6522                    .unwrap_or_default();
 6523                let row = rows_by_indent_size[&indent_size][0];
 6524                let indent_end = Point::new(row, indent_size.len);
 6525
 6526                (indent_size, indent_end)
 6527            };
 6528
 6529            let mut line_prefix = indent_size.chars().collect::<String>();
 6530
 6531            if let Some(comment_prefix) =
 6532                buffer
 6533                    .language_scope_at(selection.head())
 6534                    .and_then(|language| {
 6535                        language
 6536                            .line_comment_prefixes()
 6537                            .iter()
 6538                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6539                            .cloned()
 6540                    })
 6541            {
 6542                line_prefix.push_str(&comment_prefix);
 6543                should_rewrap = true;
 6544            }
 6545
 6546            if !should_rewrap {
 6547                continue;
 6548            }
 6549
 6550            if selection.is_empty() {
 6551                'expand_upwards: while start_row > 0 {
 6552                    let prev_row = start_row - 1;
 6553                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6554                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6555                    {
 6556                        start_row = prev_row;
 6557                    } else {
 6558                        break 'expand_upwards;
 6559                    }
 6560                }
 6561
 6562                'expand_downwards: while end_row < buffer.max_point().row {
 6563                    let next_row = end_row + 1;
 6564                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6565                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6566                    {
 6567                        end_row = next_row;
 6568                    } else {
 6569                        break 'expand_downwards;
 6570                    }
 6571                }
 6572            }
 6573
 6574            let start = Point::new(start_row, 0);
 6575            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6576            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6577            let Some(lines_without_prefixes) = selection_text
 6578                .lines()
 6579                .map(|line| {
 6580                    line.strip_prefix(&line_prefix)
 6581                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6582                        .ok_or_else(|| {
 6583                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6584                        })
 6585                })
 6586                .collect::<Result<Vec<_>, _>>()
 6587                .log_err()
 6588            else {
 6589                continue;
 6590            };
 6591
 6592            let wrap_column = buffer
 6593                .settings_at(Point::new(start_row, 0), cx)
 6594                .preferred_line_length as usize;
 6595            let wrapped_text = wrap_with_prefix(
 6596                line_prefix,
 6597                lines_without_prefixes.join(" "),
 6598                wrap_column,
 6599                tab_size,
 6600            );
 6601
 6602            // TODO: should always use char-based diff while still supporting cursor behavior that
 6603            // matches vim.
 6604            let diff = match is_vim_mode {
 6605                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6606                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6607            };
 6608            let mut offset = start.to_offset(&buffer);
 6609            let mut moved_since_edit = true;
 6610
 6611            for change in diff.iter_all_changes() {
 6612                let value = change.value();
 6613                match change.tag() {
 6614                    ChangeTag::Equal => {
 6615                        offset += value.len();
 6616                        moved_since_edit = true;
 6617                    }
 6618                    ChangeTag::Delete => {
 6619                        let start = buffer.anchor_after(offset);
 6620                        let end = buffer.anchor_before(offset + value.len());
 6621
 6622                        if moved_since_edit {
 6623                            edits.push((start..end, String::new()));
 6624                        } else {
 6625                            edits.last_mut().unwrap().0.end = end;
 6626                        }
 6627
 6628                        offset += value.len();
 6629                        moved_since_edit = false;
 6630                    }
 6631                    ChangeTag::Insert => {
 6632                        if moved_since_edit {
 6633                            let anchor = buffer.anchor_after(offset);
 6634                            edits.push((anchor..anchor, value.to_string()));
 6635                        } else {
 6636                            edits.last_mut().unwrap().1.push_str(value);
 6637                        }
 6638
 6639                        moved_since_edit = false;
 6640                    }
 6641                }
 6642            }
 6643
 6644            rewrapped_row_ranges.push(start_row..=end_row);
 6645        }
 6646
 6647        self.buffer
 6648            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6649    }
 6650
 6651    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6652        let mut text = String::new();
 6653        let buffer = self.buffer.read(cx).snapshot(cx);
 6654        let mut selections = self.selections.all::<Point>(cx);
 6655        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6656        {
 6657            let max_point = buffer.max_point();
 6658            let mut is_first = true;
 6659            for selection in &mut selections {
 6660                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6661                if is_entire_line {
 6662                    selection.start = Point::new(selection.start.row, 0);
 6663                    if !selection.is_empty() && selection.end.column == 0 {
 6664                        selection.end = cmp::min(max_point, selection.end);
 6665                    } else {
 6666                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6667                    }
 6668                    selection.goal = SelectionGoal::None;
 6669                }
 6670                if is_first {
 6671                    is_first = false;
 6672                } else {
 6673                    text += "\n";
 6674                }
 6675                let mut len = 0;
 6676                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6677                    text.push_str(chunk);
 6678                    len += chunk.len();
 6679                }
 6680                clipboard_selections.push(ClipboardSelection {
 6681                    len,
 6682                    is_entire_line,
 6683                    first_line_indent: buffer
 6684                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6685                        .len,
 6686                });
 6687            }
 6688        }
 6689
 6690        self.transact(cx, |this, cx| {
 6691            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6692                s.select(selections);
 6693            });
 6694            this.insert("", cx);
 6695        });
 6696        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6697    }
 6698
 6699    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6700        let item = self.cut_common(cx);
 6701        cx.write_to_clipboard(item);
 6702    }
 6703
 6704    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6705        self.change_selections(None, cx, |s| {
 6706            s.move_with(|snapshot, sel| {
 6707                if sel.is_empty() {
 6708                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6709                }
 6710            });
 6711        });
 6712        let item = self.cut_common(cx);
 6713        cx.set_global(KillRing(item))
 6714    }
 6715
 6716    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6717        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6718            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6719                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6720            } else {
 6721                return;
 6722            }
 6723        } else {
 6724            return;
 6725        };
 6726        self.do_paste(&text, metadata, false, cx);
 6727    }
 6728
 6729    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6730        let selections = self.selections.all::<Point>(cx);
 6731        let buffer = self.buffer.read(cx).read(cx);
 6732        let mut text = String::new();
 6733
 6734        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6735        {
 6736            let max_point = buffer.max_point();
 6737            let mut is_first = true;
 6738            for selection in selections.iter() {
 6739                let mut start = selection.start;
 6740                let mut end = selection.end;
 6741                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6742                if is_entire_line {
 6743                    start = Point::new(start.row, 0);
 6744                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6745                }
 6746                if is_first {
 6747                    is_first = false;
 6748                } else {
 6749                    text += "\n";
 6750                }
 6751                let mut len = 0;
 6752                for chunk in buffer.text_for_range(start..end) {
 6753                    text.push_str(chunk);
 6754                    len += chunk.len();
 6755                }
 6756                clipboard_selections.push(ClipboardSelection {
 6757                    len,
 6758                    is_entire_line,
 6759                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6760                });
 6761            }
 6762        }
 6763
 6764        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6765            text,
 6766            clipboard_selections,
 6767        ));
 6768    }
 6769
 6770    pub fn do_paste(
 6771        &mut self,
 6772        text: &String,
 6773        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6774        handle_entire_lines: bool,
 6775        cx: &mut ViewContext<Self>,
 6776    ) {
 6777        if self.read_only(cx) {
 6778            return;
 6779        }
 6780
 6781        let clipboard_text = Cow::Borrowed(text);
 6782
 6783        self.transact(cx, |this, cx| {
 6784            if let Some(mut clipboard_selections) = clipboard_selections {
 6785                let old_selections = this.selections.all::<usize>(cx);
 6786                let all_selections_were_entire_line =
 6787                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6788                let first_selection_indent_column =
 6789                    clipboard_selections.first().map(|s| s.first_line_indent);
 6790                if clipboard_selections.len() != old_selections.len() {
 6791                    clipboard_selections.drain(..);
 6792                }
 6793                let cursor_offset = this.selections.last::<usize>(cx).head();
 6794                let mut auto_indent_on_paste = true;
 6795
 6796                this.buffer.update(cx, |buffer, cx| {
 6797                    let snapshot = buffer.read(cx);
 6798                    auto_indent_on_paste =
 6799                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6800
 6801                    let mut start_offset = 0;
 6802                    let mut edits = Vec::new();
 6803                    let mut original_indent_columns = Vec::new();
 6804                    for (ix, selection) in old_selections.iter().enumerate() {
 6805                        let to_insert;
 6806                        let entire_line;
 6807                        let original_indent_column;
 6808                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6809                            let end_offset = start_offset + clipboard_selection.len;
 6810                            to_insert = &clipboard_text[start_offset..end_offset];
 6811                            entire_line = clipboard_selection.is_entire_line;
 6812                            start_offset = end_offset + 1;
 6813                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6814                        } else {
 6815                            to_insert = clipboard_text.as_str();
 6816                            entire_line = all_selections_were_entire_line;
 6817                            original_indent_column = first_selection_indent_column
 6818                        }
 6819
 6820                        // If the corresponding selection was empty when this slice of the
 6821                        // clipboard text was written, then the entire line containing the
 6822                        // selection was copied. If this selection is also currently empty,
 6823                        // then paste the line before the current line of the buffer.
 6824                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6825                            let column = selection.start.to_point(&snapshot).column as usize;
 6826                            let line_start = selection.start - column;
 6827                            line_start..line_start
 6828                        } else {
 6829                            selection.range()
 6830                        };
 6831
 6832                        edits.push((range, to_insert));
 6833                        original_indent_columns.extend(original_indent_column);
 6834                    }
 6835                    drop(snapshot);
 6836
 6837                    buffer.edit(
 6838                        edits,
 6839                        if auto_indent_on_paste {
 6840                            Some(AutoindentMode::Block {
 6841                                original_indent_columns,
 6842                            })
 6843                        } else {
 6844                            None
 6845                        },
 6846                        cx,
 6847                    );
 6848                });
 6849
 6850                let selections = this.selections.all::<usize>(cx);
 6851                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6852            } else {
 6853                this.insert(&clipboard_text, cx);
 6854            }
 6855        });
 6856    }
 6857
 6858    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6859        if let Some(item) = cx.read_from_clipboard() {
 6860            let entries = item.entries();
 6861
 6862            match entries.first() {
 6863                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6864                // of all the pasted entries.
 6865                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6866                    .do_paste(
 6867                        clipboard_string.text(),
 6868                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 6869                        true,
 6870                        cx,
 6871                    ),
 6872                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 6873            }
 6874        }
 6875    }
 6876
 6877    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6878        if self.read_only(cx) {
 6879            return;
 6880        }
 6881
 6882        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6883            if let Some((selections, _)) =
 6884                self.selection_history.transaction(transaction_id).cloned()
 6885            {
 6886                self.change_selections(None, cx, |s| {
 6887                    s.select_anchors(selections.to_vec());
 6888                });
 6889            }
 6890            self.request_autoscroll(Autoscroll::fit(), cx);
 6891            self.unmark_text(cx);
 6892            self.refresh_inline_completion(true, false, cx);
 6893            cx.emit(EditorEvent::Edited { transaction_id });
 6894            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6895        }
 6896    }
 6897
 6898    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6899        if self.read_only(cx) {
 6900            return;
 6901        }
 6902
 6903        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6904            if let Some((_, Some(selections))) =
 6905                self.selection_history.transaction(transaction_id).cloned()
 6906            {
 6907                self.change_selections(None, cx, |s| {
 6908                    s.select_anchors(selections.to_vec());
 6909                });
 6910            }
 6911            self.request_autoscroll(Autoscroll::fit(), cx);
 6912            self.unmark_text(cx);
 6913            self.refresh_inline_completion(true, false, cx);
 6914            cx.emit(EditorEvent::Edited { transaction_id });
 6915        }
 6916    }
 6917
 6918    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6919        self.buffer
 6920            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6921    }
 6922
 6923    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6924        self.buffer
 6925            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6926    }
 6927
 6928    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6929        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6930            let line_mode = s.line_mode;
 6931            s.move_with(|map, selection| {
 6932                let cursor = if selection.is_empty() && !line_mode {
 6933                    movement::left(map, selection.start)
 6934                } else {
 6935                    selection.start
 6936                };
 6937                selection.collapse_to(cursor, SelectionGoal::None);
 6938            });
 6939        })
 6940    }
 6941
 6942    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6943        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6944            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6945        })
 6946    }
 6947
 6948    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6949        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6950            let line_mode = s.line_mode;
 6951            s.move_with(|map, selection| {
 6952                let cursor = if selection.is_empty() && !line_mode {
 6953                    movement::right(map, selection.end)
 6954                } else {
 6955                    selection.end
 6956                };
 6957                selection.collapse_to(cursor, SelectionGoal::None)
 6958            });
 6959        })
 6960    }
 6961
 6962    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6963        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6964            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6965        })
 6966    }
 6967
 6968    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6969        if self.take_rename(true, cx).is_some() {
 6970            return;
 6971        }
 6972
 6973        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6974            cx.propagate();
 6975            return;
 6976        }
 6977
 6978        let text_layout_details = &self.text_layout_details(cx);
 6979        let selection_count = self.selections.count();
 6980        let first_selection = self.selections.first_anchor();
 6981
 6982        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6983            let line_mode = s.line_mode;
 6984            s.move_with(|map, selection| {
 6985                if !selection.is_empty() && !line_mode {
 6986                    selection.goal = SelectionGoal::None;
 6987                }
 6988                let (cursor, goal) = movement::up(
 6989                    map,
 6990                    selection.start,
 6991                    selection.goal,
 6992                    false,
 6993                    text_layout_details,
 6994                );
 6995                selection.collapse_to(cursor, goal);
 6996            });
 6997        });
 6998
 6999        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7000        {
 7001            cx.propagate();
 7002        }
 7003    }
 7004
 7005    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7006        if self.take_rename(true, cx).is_some() {
 7007            return;
 7008        }
 7009
 7010        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7011            cx.propagate();
 7012            return;
 7013        }
 7014
 7015        let text_layout_details = &self.text_layout_details(cx);
 7016
 7017        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7018            let line_mode = s.line_mode;
 7019            s.move_with(|map, selection| {
 7020                if !selection.is_empty() && !line_mode {
 7021                    selection.goal = SelectionGoal::None;
 7022                }
 7023                let (cursor, goal) = movement::up_by_rows(
 7024                    map,
 7025                    selection.start,
 7026                    action.lines,
 7027                    selection.goal,
 7028                    false,
 7029                    text_layout_details,
 7030                );
 7031                selection.collapse_to(cursor, goal);
 7032            });
 7033        })
 7034    }
 7035
 7036    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7037        if self.take_rename(true, cx).is_some() {
 7038            return;
 7039        }
 7040
 7041        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7042            cx.propagate();
 7043            return;
 7044        }
 7045
 7046        let text_layout_details = &self.text_layout_details(cx);
 7047
 7048        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7049            let line_mode = s.line_mode;
 7050            s.move_with(|map, selection| {
 7051                if !selection.is_empty() && !line_mode {
 7052                    selection.goal = SelectionGoal::None;
 7053                }
 7054                let (cursor, goal) = movement::down_by_rows(
 7055                    map,
 7056                    selection.start,
 7057                    action.lines,
 7058                    selection.goal,
 7059                    false,
 7060                    text_layout_details,
 7061                );
 7062                selection.collapse_to(cursor, goal);
 7063            });
 7064        })
 7065    }
 7066
 7067    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7068        let text_layout_details = &self.text_layout_details(cx);
 7069        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7070            s.move_heads_with(|map, head, goal| {
 7071                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7072            })
 7073        })
 7074    }
 7075
 7076    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7077        let text_layout_details = &self.text_layout_details(cx);
 7078        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7079            s.move_heads_with(|map, head, goal| {
 7080                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7081            })
 7082        })
 7083    }
 7084
 7085    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7086        let Some(row_count) = self.visible_row_count() else {
 7087            return;
 7088        };
 7089
 7090        let text_layout_details = &self.text_layout_details(cx);
 7091
 7092        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7093            s.move_heads_with(|map, head, goal| {
 7094                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7095            })
 7096        })
 7097    }
 7098
 7099    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7100        if self.take_rename(true, cx).is_some() {
 7101            return;
 7102        }
 7103
 7104        if self
 7105            .context_menu
 7106            .borrow_mut()
 7107            .as_mut()
 7108            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7109            .unwrap_or(false)
 7110        {
 7111            return;
 7112        }
 7113
 7114        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7115            cx.propagate();
 7116            return;
 7117        }
 7118
 7119        let Some(row_count) = self.visible_row_count() else {
 7120            return;
 7121        };
 7122
 7123        let autoscroll = if action.center_cursor {
 7124            Autoscroll::center()
 7125        } else {
 7126            Autoscroll::fit()
 7127        };
 7128
 7129        let text_layout_details = &self.text_layout_details(cx);
 7130
 7131        self.change_selections(Some(autoscroll), cx, |s| {
 7132            let line_mode = s.line_mode;
 7133            s.move_with(|map, selection| {
 7134                if !selection.is_empty() && !line_mode {
 7135                    selection.goal = SelectionGoal::None;
 7136                }
 7137                let (cursor, goal) = movement::up_by_rows(
 7138                    map,
 7139                    selection.end,
 7140                    row_count,
 7141                    selection.goal,
 7142                    false,
 7143                    text_layout_details,
 7144                );
 7145                selection.collapse_to(cursor, goal);
 7146            });
 7147        });
 7148    }
 7149
 7150    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7151        let text_layout_details = &self.text_layout_details(cx);
 7152        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7153            s.move_heads_with(|map, head, goal| {
 7154                movement::up(map, head, goal, false, text_layout_details)
 7155            })
 7156        })
 7157    }
 7158
 7159    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7160        self.take_rename(true, cx);
 7161
 7162        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7163            cx.propagate();
 7164            return;
 7165        }
 7166
 7167        let text_layout_details = &self.text_layout_details(cx);
 7168        let selection_count = self.selections.count();
 7169        let first_selection = self.selections.first_anchor();
 7170
 7171        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7172            let line_mode = s.line_mode;
 7173            s.move_with(|map, selection| {
 7174                if !selection.is_empty() && !line_mode {
 7175                    selection.goal = SelectionGoal::None;
 7176                }
 7177                let (cursor, goal) = movement::down(
 7178                    map,
 7179                    selection.end,
 7180                    selection.goal,
 7181                    false,
 7182                    text_layout_details,
 7183                );
 7184                selection.collapse_to(cursor, goal);
 7185            });
 7186        });
 7187
 7188        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7189        {
 7190            cx.propagate();
 7191        }
 7192    }
 7193
 7194    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7195        let Some(row_count) = self.visible_row_count() else {
 7196            return;
 7197        };
 7198
 7199        let text_layout_details = &self.text_layout_details(cx);
 7200
 7201        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7202            s.move_heads_with(|map, head, goal| {
 7203                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7204            })
 7205        })
 7206    }
 7207
 7208    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7209        if self.take_rename(true, cx).is_some() {
 7210            return;
 7211        }
 7212
 7213        if self
 7214            .context_menu
 7215            .borrow_mut()
 7216            .as_mut()
 7217            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7218            .unwrap_or(false)
 7219        {
 7220            return;
 7221        }
 7222
 7223        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7224            cx.propagate();
 7225            return;
 7226        }
 7227
 7228        let Some(row_count) = self.visible_row_count() else {
 7229            return;
 7230        };
 7231
 7232        let autoscroll = if action.center_cursor {
 7233            Autoscroll::center()
 7234        } else {
 7235            Autoscroll::fit()
 7236        };
 7237
 7238        let text_layout_details = &self.text_layout_details(cx);
 7239        self.change_selections(Some(autoscroll), cx, |s| {
 7240            let line_mode = s.line_mode;
 7241            s.move_with(|map, selection| {
 7242                if !selection.is_empty() && !line_mode {
 7243                    selection.goal = SelectionGoal::None;
 7244                }
 7245                let (cursor, goal) = movement::down_by_rows(
 7246                    map,
 7247                    selection.end,
 7248                    row_count,
 7249                    selection.goal,
 7250                    false,
 7251                    text_layout_details,
 7252                );
 7253                selection.collapse_to(cursor, goal);
 7254            });
 7255        });
 7256    }
 7257
 7258    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7259        let text_layout_details = &self.text_layout_details(cx);
 7260        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7261            s.move_heads_with(|map, head, goal| {
 7262                movement::down(map, head, goal, false, text_layout_details)
 7263            })
 7264        });
 7265    }
 7266
 7267    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7268        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7269            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7270        }
 7271    }
 7272
 7273    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7274        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7275            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7276        }
 7277    }
 7278
 7279    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7280        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7281            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7282        }
 7283    }
 7284
 7285    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7286        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7287            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7288        }
 7289    }
 7290
 7291    pub fn move_to_previous_word_start(
 7292        &mut self,
 7293        _: &MoveToPreviousWordStart,
 7294        cx: &mut ViewContext<Self>,
 7295    ) {
 7296        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7297            s.move_cursors_with(|map, head, _| {
 7298                (
 7299                    movement::previous_word_start(map, head),
 7300                    SelectionGoal::None,
 7301                )
 7302            });
 7303        })
 7304    }
 7305
 7306    pub fn move_to_previous_subword_start(
 7307        &mut self,
 7308        _: &MoveToPreviousSubwordStart,
 7309        cx: &mut ViewContext<Self>,
 7310    ) {
 7311        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7312            s.move_cursors_with(|map, head, _| {
 7313                (
 7314                    movement::previous_subword_start(map, head),
 7315                    SelectionGoal::None,
 7316                )
 7317            });
 7318        })
 7319    }
 7320
 7321    pub fn select_to_previous_word_start(
 7322        &mut self,
 7323        _: &SelectToPreviousWordStart,
 7324        cx: &mut ViewContext<Self>,
 7325    ) {
 7326        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7327            s.move_heads_with(|map, head, _| {
 7328                (
 7329                    movement::previous_word_start(map, head),
 7330                    SelectionGoal::None,
 7331                )
 7332            });
 7333        })
 7334    }
 7335
 7336    pub fn select_to_previous_subword_start(
 7337        &mut self,
 7338        _: &SelectToPreviousSubwordStart,
 7339        cx: &mut ViewContext<Self>,
 7340    ) {
 7341        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7342            s.move_heads_with(|map, head, _| {
 7343                (
 7344                    movement::previous_subword_start(map, head),
 7345                    SelectionGoal::None,
 7346                )
 7347            });
 7348        })
 7349    }
 7350
 7351    pub fn delete_to_previous_word_start(
 7352        &mut self,
 7353        action: &DeleteToPreviousWordStart,
 7354        cx: &mut ViewContext<Self>,
 7355    ) {
 7356        self.transact(cx, |this, cx| {
 7357            this.select_autoclose_pair(cx);
 7358            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7359                let line_mode = s.line_mode;
 7360                s.move_with(|map, selection| {
 7361                    if selection.is_empty() && !line_mode {
 7362                        let cursor = if action.ignore_newlines {
 7363                            movement::previous_word_start(map, selection.head())
 7364                        } else {
 7365                            movement::previous_word_start_or_newline(map, selection.head())
 7366                        };
 7367                        selection.set_head(cursor, SelectionGoal::None);
 7368                    }
 7369                });
 7370            });
 7371            this.insert("", cx);
 7372        });
 7373    }
 7374
 7375    pub fn delete_to_previous_subword_start(
 7376        &mut self,
 7377        _: &DeleteToPreviousSubwordStart,
 7378        cx: &mut ViewContext<Self>,
 7379    ) {
 7380        self.transact(cx, |this, cx| {
 7381            this.select_autoclose_pair(cx);
 7382            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7383                let line_mode = s.line_mode;
 7384                s.move_with(|map, selection| {
 7385                    if selection.is_empty() && !line_mode {
 7386                        let cursor = movement::previous_subword_start(map, selection.head());
 7387                        selection.set_head(cursor, SelectionGoal::None);
 7388                    }
 7389                });
 7390            });
 7391            this.insert("", cx);
 7392        });
 7393    }
 7394
 7395    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7396        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7397            s.move_cursors_with(|map, head, _| {
 7398                (movement::next_word_end(map, head), SelectionGoal::None)
 7399            });
 7400        })
 7401    }
 7402
 7403    pub fn move_to_next_subword_end(
 7404        &mut self,
 7405        _: &MoveToNextSubwordEnd,
 7406        cx: &mut ViewContext<Self>,
 7407    ) {
 7408        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7409            s.move_cursors_with(|map, head, _| {
 7410                (movement::next_subword_end(map, head), SelectionGoal::None)
 7411            });
 7412        })
 7413    }
 7414
 7415    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7416        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7417            s.move_heads_with(|map, head, _| {
 7418                (movement::next_word_end(map, head), SelectionGoal::None)
 7419            });
 7420        })
 7421    }
 7422
 7423    pub fn select_to_next_subword_end(
 7424        &mut self,
 7425        _: &SelectToNextSubwordEnd,
 7426        cx: &mut ViewContext<Self>,
 7427    ) {
 7428        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7429            s.move_heads_with(|map, head, _| {
 7430                (movement::next_subword_end(map, head), SelectionGoal::None)
 7431            });
 7432        })
 7433    }
 7434
 7435    pub fn delete_to_next_word_end(
 7436        &mut self,
 7437        action: &DeleteToNextWordEnd,
 7438        cx: &mut ViewContext<Self>,
 7439    ) {
 7440        self.transact(cx, |this, cx| {
 7441            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7442                let line_mode = s.line_mode;
 7443                s.move_with(|map, selection| {
 7444                    if selection.is_empty() && !line_mode {
 7445                        let cursor = if action.ignore_newlines {
 7446                            movement::next_word_end(map, selection.head())
 7447                        } else {
 7448                            movement::next_word_end_or_newline(map, selection.head())
 7449                        };
 7450                        selection.set_head(cursor, SelectionGoal::None);
 7451                    }
 7452                });
 7453            });
 7454            this.insert("", cx);
 7455        });
 7456    }
 7457
 7458    pub fn delete_to_next_subword_end(
 7459        &mut self,
 7460        _: &DeleteToNextSubwordEnd,
 7461        cx: &mut ViewContext<Self>,
 7462    ) {
 7463        self.transact(cx, |this, cx| {
 7464            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7465                s.move_with(|map, selection| {
 7466                    if selection.is_empty() {
 7467                        let cursor = movement::next_subword_end(map, selection.head());
 7468                        selection.set_head(cursor, SelectionGoal::None);
 7469                    }
 7470                });
 7471            });
 7472            this.insert("", cx);
 7473        });
 7474    }
 7475
 7476    pub fn move_to_beginning_of_line(
 7477        &mut self,
 7478        action: &MoveToBeginningOfLine,
 7479        cx: &mut ViewContext<Self>,
 7480    ) {
 7481        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7482            s.move_cursors_with(|map, head, _| {
 7483                (
 7484                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7485                    SelectionGoal::None,
 7486                )
 7487            });
 7488        })
 7489    }
 7490
 7491    pub fn select_to_beginning_of_line(
 7492        &mut self,
 7493        action: &SelectToBeginningOfLine,
 7494        cx: &mut ViewContext<Self>,
 7495    ) {
 7496        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7497            s.move_heads_with(|map, head, _| {
 7498                (
 7499                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7500                    SelectionGoal::None,
 7501                )
 7502            });
 7503        });
 7504    }
 7505
 7506    pub fn delete_to_beginning_of_line(
 7507        &mut self,
 7508        _: &DeleteToBeginningOfLine,
 7509        cx: &mut ViewContext<Self>,
 7510    ) {
 7511        self.transact(cx, |this, cx| {
 7512            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7513                s.move_with(|_, selection| {
 7514                    selection.reversed = true;
 7515                });
 7516            });
 7517
 7518            this.select_to_beginning_of_line(
 7519                &SelectToBeginningOfLine {
 7520                    stop_at_soft_wraps: false,
 7521                },
 7522                cx,
 7523            );
 7524            this.backspace(&Backspace, cx);
 7525        });
 7526    }
 7527
 7528    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7529        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7530            s.move_cursors_with(|map, head, _| {
 7531                (
 7532                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7533                    SelectionGoal::None,
 7534                )
 7535            });
 7536        })
 7537    }
 7538
 7539    pub fn select_to_end_of_line(
 7540        &mut self,
 7541        action: &SelectToEndOfLine,
 7542        cx: &mut ViewContext<Self>,
 7543    ) {
 7544        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7545            s.move_heads_with(|map, head, _| {
 7546                (
 7547                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7548                    SelectionGoal::None,
 7549                )
 7550            });
 7551        })
 7552    }
 7553
 7554    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7555        self.transact(cx, |this, cx| {
 7556            this.select_to_end_of_line(
 7557                &SelectToEndOfLine {
 7558                    stop_at_soft_wraps: false,
 7559                },
 7560                cx,
 7561            );
 7562            this.delete(&Delete, cx);
 7563        });
 7564    }
 7565
 7566    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7567        self.transact(cx, |this, cx| {
 7568            this.select_to_end_of_line(
 7569                &SelectToEndOfLine {
 7570                    stop_at_soft_wraps: false,
 7571                },
 7572                cx,
 7573            );
 7574            this.cut(&Cut, cx);
 7575        });
 7576    }
 7577
 7578    pub fn move_to_start_of_paragraph(
 7579        &mut self,
 7580        _: &MoveToStartOfParagraph,
 7581        cx: &mut ViewContext<Self>,
 7582    ) {
 7583        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7584            cx.propagate();
 7585            return;
 7586        }
 7587
 7588        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7589            s.move_with(|map, selection| {
 7590                selection.collapse_to(
 7591                    movement::start_of_paragraph(map, selection.head(), 1),
 7592                    SelectionGoal::None,
 7593                )
 7594            });
 7595        })
 7596    }
 7597
 7598    pub fn move_to_end_of_paragraph(
 7599        &mut self,
 7600        _: &MoveToEndOfParagraph,
 7601        cx: &mut ViewContext<Self>,
 7602    ) {
 7603        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7604            cx.propagate();
 7605            return;
 7606        }
 7607
 7608        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7609            s.move_with(|map, selection| {
 7610                selection.collapse_to(
 7611                    movement::end_of_paragraph(map, selection.head(), 1),
 7612                    SelectionGoal::None,
 7613                )
 7614            });
 7615        })
 7616    }
 7617
 7618    pub fn select_to_start_of_paragraph(
 7619        &mut self,
 7620        _: &SelectToStartOfParagraph,
 7621        cx: &mut ViewContext<Self>,
 7622    ) {
 7623        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7624            cx.propagate();
 7625            return;
 7626        }
 7627
 7628        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7629            s.move_heads_with(|map, head, _| {
 7630                (
 7631                    movement::start_of_paragraph(map, head, 1),
 7632                    SelectionGoal::None,
 7633                )
 7634            });
 7635        })
 7636    }
 7637
 7638    pub fn select_to_end_of_paragraph(
 7639        &mut self,
 7640        _: &SelectToEndOfParagraph,
 7641        cx: &mut ViewContext<Self>,
 7642    ) {
 7643        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7644            cx.propagate();
 7645            return;
 7646        }
 7647
 7648        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7649            s.move_heads_with(|map, head, _| {
 7650                (
 7651                    movement::end_of_paragraph(map, head, 1),
 7652                    SelectionGoal::None,
 7653                )
 7654            });
 7655        })
 7656    }
 7657
 7658    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7659        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7660            cx.propagate();
 7661            return;
 7662        }
 7663
 7664        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7665            s.select_ranges(vec![0..0]);
 7666        });
 7667    }
 7668
 7669    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7670        let mut selection = self.selections.last::<Point>(cx);
 7671        selection.set_head(Point::zero(), SelectionGoal::None);
 7672
 7673        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7674            s.select(vec![selection]);
 7675        });
 7676    }
 7677
 7678    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7679        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7680            cx.propagate();
 7681            return;
 7682        }
 7683
 7684        let cursor = self.buffer.read(cx).read(cx).len();
 7685        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7686            s.select_ranges(vec![cursor..cursor])
 7687        });
 7688    }
 7689
 7690    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7691        self.nav_history = nav_history;
 7692    }
 7693
 7694    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7695        self.nav_history.as_ref()
 7696    }
 7697
 7698    fn push_to_nav_history(
 7699        &mut self,
 7700        cursor_anchor: Anchor,
 7701        new_position: Option<Point>,
 7702        cx: &mut ViewContext<Self>,
 7703    ) {
 7704        if let Some(nav_history) = self.nav_history.as_mut() {
 7705            let buffer = self.buffer.read(cx).read(cx);
 7706            let cursor_position = cursor_anchor.to_point(&buffer);
 7707            let scroll_state = self.scroll_manager.anchor();
 7708            let scroll_top_row = scroll_state.top_row(&buffer);
 7709            drop(buffer);
 7710
 7711            if let Some(new_position) = new_position {
 7712                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7713                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7714                    return;
 7715                }
 7716            }
 7717
 7718            nav_history.push(
 7719                Some(NavigationData {
 7720                    cursor_anchor,
 7721                    cursor_position,
 7722                    scroll_anchor: scroll_state,
 7723                    scroll_top_row,
 7724                }),
 7725                cx,
 7726            );
 7727        }
 7728    }
 7729
 7730    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7731        let buffer = self.buffer.read(cx).snapshot(cx);
 7732        let mut selection = self.selections.first::<usize>(cx);
 7733        selection.set_head(buffer.len(), SelectionGoal::None);
 7734        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7735            s.select(vec![selection]);
 7736        });
 7737    }
 7738
 7739    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7740        let end = self.buffer.read(cx).read(cx).len();
 7741        self.change_selections(None, cx, |s| {
 7742            s.select_ranges(vec![0..end]);
 7743        });
 7744    }
 7745
 7746    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7747        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7748        let mut selections = self.selections.all::<Point>(cx);
 7749        let max_point = display_map.buffer_snapshot.max_point();
 7750        for selection in &mut selections {
 7751            let rows = selection.spanned_rows(true, &display_map);
 7752            selection.start = Point::new(rows.start.0, 0);
 7753            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7754            selection.reversed = false;
 7755        }
 7756        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7757            s.select(selections);
 7758        });
 7759    }
 7760
 7761    pub fn split_selection_into_lines(
 7762        &mut self,
 7763        _: &SplitSelectionIntoLines,
 7764        cx: &mut ViewContext<Self>,
 7765    ) {
 7766        let mut to_unfold = Vec::new();
 7767        let mut new_selection_ranges = Vec::new();
 7768        {
 7769            let selections = self.selections.all::<Point>(cx);
 7770            let buffer = self.buffer.read(cx).read(cx);
 7771            for selection in selections {
 7772                for row in selection.start.row..selection.end.row {
 7773                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7774                    new_selection_ranges.push(cursor..cursor);
 7775                }
 7776                new_selection_ranges.push(selection.end..selection.end);
 7777                to_unfold.push(selection.start..selection.end);
 7778            }
 7779        }
 7780        self.unfold_ranges(&to_unfold, true, true, cx);
 7781        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7782            s.select_ranges(new_selection_ranges);
 7783        });
 7784    }
 7785
 7786    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7787        self.add_selection(true, cx);
 7788    }
 7789
 7790    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7791        self.add_selection(false, cx);
 7792    }
 7793
 7794    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7795        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7796        let mut selections = self.selections.all::<Point>(cx);
 7797        let text_layout_details = self.text_layout_details(cx);
 7798        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7799            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7800            let range = oldest_selection.display_range(&display_map).sorted();
 7801
 7802            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7803            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7804            let positions = start_x.min(end_x)..start_x.max(end_x);
 7805
 7806            selections.clear();
 7807            let mut stack = Vec::new();
 7808            for row in range.start.row().0..=range.end.row().0 {
 7809                if let Some(selection) = self.selections.build_columnar_selection(
 7810                    &display_map,
 7811                    DisplayRow(row),
 7812                    &positions,
 7813                    oldest_selection.reversed,
 7814                    &text_layout_details,
 7815                ) {
 7816                    stack.push(selection.id);
 7817                    selections.push(selection);
 7818                }
 7819            }
 7820
 7821            if above {
 7822                stack.reverse();
 7823            }
 7824
 7825            AddSelectionsState { above, stack }
 7826        });
 7827
 7828        let last_added_selection = *state.stack.last().unwrap();
 7829        let mut new_selections = Vec::new();
 7830        if above == state.above {
 7831            let end_row = if above {
 7832                DisplayRow(0)
 7833            } else {
 7834                display_map.max_point().row()
 7835            };
 7836
 7837            'outer: for selection in selections {
 7838                if selection.id == last_added_selection {
 7839                    let range = selection.display_range(&display_map).sorted();
 7840                    debug_assert_eq!(range.start.row(), range.end.row());
 7841                    let mut row = range.start.row();
 7842                    let positions =
 7843                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7844                            px(start)..px(end)
 7845                        } else {
 7846                            let start_x =
 7847                                display_map.x_for_display_point(range.start, &text_layout_details);
 7848                            let end_x =
 7849                                display_map.x_for_display_point(range.end, &text_layout_details);
 7850                            start_x.min(end_x)..start_x.max(end_x)
 7851                        };
 7852
 7853                    while row != end_row {
 7854                        if above {
 7855                            row.0 -= 1;
 7856                        } else {
 7857                            row.0 += 1;
 7858                        }
 7859
 7860                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7861                            &display_map,
 7862                            row,
 7863                            &positions,
 7864                            selection.reversed,
 7865                            &text_layout_details,
 7866                        ) {
 7867                            state.stack.push(new_selection.id);
 7868                            if above {
 7869                                new_selections.push(new_selection);
 7870                                new_selections.push(selection);
 7871                            } else {
 7872                                new_selections.push(selection);
 7873                                new_selections.push(new_selection);
 7874                            }
 7875
 7876                            continue 'outer;
 7877                        }
 7878                    }
 7879                }
 7880
 7881                new_selections.push(selection);
 7882            }
 7883        } else {
 7884            new_selections = selections;
 7885            new_selections.retain(|s| s.id != last_added_selection);
 7886            state.stack.pop();
 7887        }
 7888
 7889        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7890            s.select(new_selections);
 7891        });
 7892        if state.stack.len() > 1 {
 7893            self.add_selections_state = Some(state);
 7894        }
 7895    }
 7896
 7897    pub fn select_next_match_internal(
 7898        &mut self,
 7899        display_map: &DisplaySnapshot,
 7900        replace_newest: bool,
 7901        autoscroll: Option<Autoscroll>,
 7902        cx: &mut ViewContext<Self>,
 7903    ) -> Result<()> {
 7904        fn select_next_match_ranges(
 7905            this: &mut Editor,
 7906            range: Range<usize>,
 7907            replace_newest: bool,
 7908            auto_scroll: Option<Autoscroll>,
 7909            cx: &mut ViewContext<Editor>,
 7910        ) {
 7911            this.unfold_ranges(&[range.clone()], false, true, cx);
 7912            this.change_selections(auto_scroll, cx, |s| {
 7913                if replace_newest {
 7914                    s.delete(s.newest_anchor().id);
 7915                }
 7916                s.insert_range(range.clone());
 7917            });
 7918        }
 7919
 7920        let buffer = &display_map.buffer_snapshot;
 7921        let mut selections = self.selections.all::<usize>(cx);
 7922        if let Some(mut select_next_state) = self.select_next_state.take() {
 7923            let query = &select_next_state.query;
 7924            if !select_next_state.done {
 7925                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7926                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7927                let mut next_selected_range = None;
 7928
 7929                let bytes_after_last_selection =
 7930                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7931                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7932                let query_matches = query
 7933                    .stream_find_iter(bytes_after_last_selection)
 7934                    .map(|result| (last_selection.end, result))
 7935                    .chain(
 7936                        query
 7937                            .stream_find_iter(bytes_before_first_selection)
 7938                            .map(|result| (0, result)),
 7939                    );
 7940
 7941                for (start_offset, query_match) in query_matches {
 7942                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7943                    let offset_range =
 7944                        start_offset + query_match.start()..start_offset + query_match.end();
 7945                    let display_range = offset_range.start.to_display_point(display_map)
 7946                        ..offset_range.end.to_display_point(display_map);
 7947
 7948                    if !select_next_state.wordwise
 7949                        || (!movement::is_inside_word(display_map, display_range.start)
 7950                            && !movement::is_inside_word(display_map, display_range.end))
 7951                    {
 7952                        // TODO: This is n^2, because we might check all the selections
 7953                        if !selections
 7954                            .iter()
 7955                            .any(|selection| selection.range().overlaps(&offset_range))
 7956                        {
 7957                            next_selected_range = Some(offset_range);
 7958                            break;
 7959                        }
 7960                    }
 7961                }
 7962
 7963                if let Some(next_selected_range) = next_selected_range {
 7964                    select_next_match_ranges(
 7965                        self,
 7966                        next_selected_range,
 7967                        replace_newest,
 7968                        autoscroll,
 7969                        cx,
 7970                    );
 7971                } else {
 7972                    select_next_state.done = true;
 7973                }
 7974            }
 7975
 7976            self.select_next_state = Some(select_next_state);
 7977        } else {
 7978            let mut only_carets = true;
 7979            let mut same_text_selected = true;
 7980            let mut selected_text = None;
 7981
 7982            let mut selections_iter = selections.iter().peekable();
 7983            while let Some(selection) = selections_iter.next() {
 7984                if selection.start != selection.end {
 7985                    only_carets = false;
 7986                }
 7987
 7988                if same_text_selected {
 7989                    if selected_text.is_none() {
 7990                        selected_text =
 7991                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7992                    }
 7993
 7994                    if let Some(next_selection) = selections_iter.peek() {
 7995                        if next_selection.range().len() == selection.range().len() {
 7996                            let next_selected_text = buffer
 7997                                .text_for_range(next_selection.range())
 7998                                .collect::<String>();
 7999                            if Some(next_selected_text) != selected_text {
 8000                                same_text_selected = false;
 8001                                selected_text = None;
 8002                            }
 8003                        } else {
 8004                            same_text_selected = false;
 8005                            selected_text = None;
 8006                        }
 8007                    }
 8008                }
 8009            }
 8010
 8011            if only_carets {
 8012                for selection in &mut selections {
 8013                    let word_range = movement::surrounding_word(
 8014                        display_map,
 8015                        selection.start.to_display_point(display_map),
 8016                    );
 8017                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8018                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8019                    selection.goal = SelectionGoal::None;
 8020                    selection.reversed = false;
 8021                    select_next_match_ranges(
 8022                        self,
 8023                        selection.start..selection.end,
 8024                        replace_newest,
 8025                        autoscroll,
 8026                        cx,
 8027                    );
 8028                }
 8029
 8030                if selections.len() == 1 {
 8031                    let selection = selections
 8032                        .last()
 8033                        .expect("ensured that there's only one selection");
 8034                    let query = buffer
 8035                        .text_for_range(selection.start..selection.end)
 8036                        .collect::<String>();
 8037                    let is_empty = query.is_empty();
 8038                    let select_state = SelectNextState {
 8039                        query: AhoCorasick::new(&[query])?,
 8040                        wordwise: true,
 8041                        done: is_empty,
 8042                    };
 8043                    self.select_next_state = Some(select_state);
 8044                } else {
 8045                    self.select_next_state = None;
 8046                }
 8047            } else if let Some(selected_text) = selected_text {
 8048                self.select_next_state = Some(SelectNextState {
 8049                    query: AhoCorasick::new(&[selected_text])?,
 8050                    wordwise: false,
 8051                    done: false,
 8052                });
 8053                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8054            }
 8055        }
 8056        Ok(())
 8057    }
 8058
 8059    pub fn select_all_matches(
 8060        &mut self,
 8061        _action: &SelectAllMatches,
 8062        cx: &mut ViewContext<Self>,
 8063    ) -> Result<()> {
 8064        self.push_to_selection_history();
 8065        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8066
 8067        self.select_next_match_internal(&display_map, false, None, cx)?;
 8068        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8069            return Ok(());
 8070        };
 8071        if select_next_state.done {
 8072            return Ok(());
 8073        }
 8074
 8075        let mut new_selections = self.selections.all::<usize>(cx);
 8076
 8077        let buffer = &display_map.buffer_snapshot;
 8078        let query_matches = select_next_state
 8079            .query
 8080            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8081
 8082        for query_match in query_matches {
 8083            let query_match = query_match.unwrap(); // can only fail due to I/O
 8084            let offset_range = query_match.start()..query_match.end();
 8085            let display_range = offset_range.start.to_display_point(&display_map)
 8086                ..offset_range.end.to_display_point(&display_map);
 8087
 8088            if !select_next_state.wordwise
 8089                || (!movement::is_inside_word(&display_map, display_range.start)
 8090                    && !movement::is_inside_word(&display_map, display_range.end))
 8091            {
 8092                self.selections.change_with(cx, |selections| {
 8093                    new_selections.push(Selection {
 8094                        id: selections.new_selection_id(),
 8095                        start: offset_range.start,
 8096                        end: offset_range.end,
 8097                        reversed: false,
 8098                        goal: SelectionGoal::None,
 8099                    });
 8100                });
 8101            }
 8102        }
 8103
 8104        new_selections.sort_by_key(|selection| selection.start);
 8105        let mut ix = 0;
 8106        while ix + 1 < new_selections.len() {
 8107            let current_selection = &new_selections[ix];
 8108            let next_selection = &new_selections[ix + 1];
 8109            if current_selection.range().overlaps(&next_selection.range()) {
 8110                if current_selection.id < next_selection.id {
 8111                    new_selections.remove(ix + 1);
 8112                } else {
 8113                    new_selections.remove(ix);
 8114                }
 8115            } else {
 8116                ix += 1;
 8117            }
 8118        }
 8119
 8120        select_next_state.done = true;
 8121        self.unfold_ranges(
 8122            &new_selections
 8123                .iter()
 8124                .map(|selection| selection.range())
 8125                .collect::<Vec<_>>(),
 8126            false,
 8127            false,
 8128            cx,
 8129        );
 8130        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8131            selections.select(new_selections)
 8132        });
 8133
 8134        Ok(())
 8135    }
 8136
 8137    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8138        self.push_to_selection_history();
 8139        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8140        self.select_next_match_internal(
 8141            &display_map,
 8142            action.replace_newest,
 8143            Some(Autoscroll::newest()),
 8144            cx,
 8145        )?;
 8146        Ok(())
 8147    }
 8148
 8149    pub fn select_previous(
 8150        &mut self,
 8151        action: &SelectPrevious,
 8152        cx: &mut ViewContext<Self>,
 8153    ) -> Result<()> {
 8154        self.push_to_selection_history();
 8155        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8156        let buffer = &display_map.buffer_snapshot;
 8157        let mut selections = self.selections.all::<usize>(cx);
 8158        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8159            let query = &select_prev_state.query;
 8160            if !select_prev_state.done {
 8161                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8162                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8163                let mut next_selected_range = None;
 8164                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8165                let bytes_before_last_selection =
 8166                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8167                let bytes_after_first_selection =
 8168                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8169                let query_matches = query
 8170                    .stream_find_iter(bytes_before_last_selection)
 8171                    .map(|result| (last_selection.start, result))
 8172                    .chain(
 8173                        query
 8174                            .stream_find_iter(bytes_after_first_selection)
 8175                            .map(|result| (buffer.len(), result)),
 8176                    );
 8177                for (end_offset, query_match) in query_matches {
 8178                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8179                    let offset_range =
 8180                        end_offset - query_match.end()..end_offset - query_match.start();
 8181                    let display_range = offset_range.start.to_display_point(&display_map)
 8182                        ..offset_range.end.to_display_point(&display_map);
 8183
 8184                    if !select_prev_state.wordwise
 8185                        || (!movement::is_inside_word(&display_map, display_range.start)
 8186                            && !movement::is_inside_word(&display_map, display_range.end))
 8187                    {
 8188                        next_selected_range = Some(offset_range);
 8189                        break;
 8190                    }
 8191                }
 8192
 8193                if let Some(next_selected_range) = next_selected_range {
 8194                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8195                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8196                        if action.replace_newest {
 8197                            s.delete(s.newest_anchor().id);
 8198                        }
 8199                        s.insert_range(next_selected_range);
 8200                    });
 8201                } else {
 8202                    select_prev_state.done = true;
 8203                }
 8204            }
 8205
 8206            self.select_prev_state = Some(select_prev_state);
 8207        } else {
 8208            let mut only_carets = true;
 8209            let mut same_text_selected = true;
 8210            let mut selected_text = None;
 8211
 8212            let mut selections_iter = selections.iter().peekable();
 8213            while let Some(selection) = selections_iter.next() {
 8214                if selection.start != selection.end {
 8215                    only_carets = false;
 8216                }
 8217
 8218                if same_text_selected {
 8219                    if selected_text.is_none() {
 8220                        selected_text =
 8221                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8222                    }
 8223
 8224                    if let Some(next_selection) = selections_iter.peek() {
 8225                        if next_selection.range().len() == selection.range().len() {
 8226                            let next_selected_text = buffer
 8227                                .text_for_range(next_selection.range())
 8228                                .collect::<String>();
 8229                            if Some(next_selected_text) != selected_text {
 8230                                same_text_selected = false;
 8231                                selected_text = None;
 8232                            }
 8233                        } else {
 8234                            same_text_selected = false;
 8235                            selected_text = None;
 8236                        }
 8237                    }
 8238                }
 8239            }
 8240
 8241            if only_carets {
 8242                for selection in &mut selections {
 8243                    let word_range = movement::surrounding_word(
 8244                        &display_map,
 8245                        selection.start.to_display_point(&display_map),
 8246                    );
 8247                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8248                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8249                    selection.goal = SelectionGoal::None;
 8250                    selection.reversed = false;
 8251                }
 8252                if selections.len() == 1 {
 8253                    let selection = selections
 8254                        .last()
 8255                        .expect("ensured that there's only one selection");
 8256                    let query = buffer
 8257                        .text_for_range(selection.start..selection.end)
 8258                        .collect::<String>();
 8259                    let is_empty = query.is_empty();
 8260                    let select_state = SelectNextState {
 8261                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8262                        wordwise: true,
 8263                        done: is_empty,
 8264                    };
 8265                    self.select_prev_state = Some(select_state);
 8266                } else {
 8267                    self.select_prev_state = None;
 8268                }
 8269
 8270                self.unfold_ranges(
 8271                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8272                    false,
 8273                    true,
 8274                    cx,
 8275                );
 8276                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8277                    s.select(selections);
 8278                });
 8279            } else if let Some(selected_text) = selected_text {
 8280                self.select_prev_state = Some(SelectNextState {
 8281                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8282                    wordwise: false,
 8283                    done: false,
 8284                });
 8285                self.select_previous(action, cx)?;
 8286            }
 8287        }
 8288        Ok(())
 8289    }
 8290
 8291    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8292        if self.read_only(cx) {
 8293            return;
 8294        }
 8295        let text_layout_details = &self.text_layout_details(cx);
 8296        self.transact(cx, |this, cx| {
 8297            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8298            let mut edits = Vec::new();
 8299            let mut selection_edit_ranges = Vec::new();
 8300            let mut last_toggled_row = None;
 8301            let snapshot = this.buffer.read(cx).read(cx);
 8302            let empty_str: Arc<str> = Arc::default();
 8303            let mut suffixes_inserted = Vec::new();
 8304            let ignore_indent = action.ignore_indent;
 8305
 8306            fn comment_prefix_range(
 8307                snapshot: &MultiBufferSnapshot,
 8308                row: MultiBufferRow,
 8309                comment_prefix: &str,
 8310                comment_prefix_whitespace: &str,
 8311                ignore_indent: bool,
 8312            ) -> Range<Point> {
 8313                let indent_size = if ignore_indent {
 8314                    0
 8315                } else {
 8316                    snapshot.indent_size_for_line(row).len
 8317                };
 8318
 8319                let start = Point::new(row.0, indent_size);
 8320
 8321                let mut line_bytes = snapshot
 8322                    .bytes_in_range(start..snapshot.max_point())
 8323                    .flatten()
 8324                    .copied();
 8325
 8326                // If this line currently begins with the line comment prefix, then record
 8327                // the range containing the prefix.
 8328                if line_bytes
 8329                    .by_ref()
 8330                    .take(comment_prefix.len())
 8331                    .eq(comment_prefix.bytes())
 8332                {
 8333                    // Include any whitespace that matches the comment prefix.
 8334                    let matching_whitespace_len = line_bytes
 8335                        .zip(comment_prefix_whitespace.bytes())
 8336                        .take_while(|(a, b)| a == b)
 8337                        .count() as u32;
 8338                    let end = Point::new(
 8339                        start.row,
 8340                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8341                    );
 8342                    start..end
 8343                } else {
 8344                    start..start
 8345                }
 8346            }
 8347
 8348            fn comment_suffix_range(
 8349                snapshot: &MultiBufferSnapshot,
 8350                row: MultiBufferRow,
 8351                comment_suffix: &str,
 8352                comment_suffix_has_leading_space: bool,
 8353            ) -> Range<Point> {
 8354                let end = Point::new(row.0, snapshot.line_len(row));
 8355                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8356
 8357                let mut line_end_bytes = snapshot
 8358                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8359                    .flatten()
 8360                    .copied();
 8361
 8362                let leading_space_len = if suffix_start_column > 0
 8363                    && line_end_bytes.next() == Some(b' ')
 8364                    && comment_suffix_has_leading_space
 8365                {
 8366                    1
 8367                } else {
 8368                    0
 8369                };
 8370
 8371                // If this line currently begins with the line comment prefix, then record
 8372                // the range containing the prefix.
 8373                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8374                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8375                    start..end
 8376                } else {
 8377                    end..end
 8378                }
 8379            }
 8380
 8381            // TODO: Handle selections that cross excerpts
 8382            for selection in &mut selections {
 8383                let start_column = snapshot
 8384                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8385                    .len;
 8386                let language = if let Some(language) =
 8387                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8388                {
 8389                    language
 8390                } else {
 8391                    continue;
 8392                };
 8393
 8394                selection_edit_ranges.clear();
 8395
 8396                // If multiple selections contain a given row, avoid processing that
 8397                // row more than once.
 8398                let mut start_row = MultiBufferRow(selection.start.row);
 8399                if last_toggled_row == Some(start_row) {
 8400                    start_row = start_row.next_row();
 8401                }
 8402                let end_row =
 8403                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8404                        MultiBufferRow(selection.end.row - 1)
 8405                    } else {
 8406                        MultiBufferRow(selection.end.row)
 8407                    };
 8408                last_toggled_row = Some(end_row);
 8409
 8410                if start_row > end_row {
 8411                    continue;
 8412                }
 8413
 8414                // If the language has line comments, toggle those.
 8415                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8416
 8417                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8418                if ignore_indent {
 8419                    full_comment_prefixes = full_comment_prefixes
 8420                        .into_iter()
 8421                        .map(|s| Arc::from(s.trim_end()))
 8422                        .collect();
 8423                }
 8424
 8425                if !full_comment_prefixes.is_empty() {
 8426                    let first_prefix = full_comment_prefixes
 8427                        .first()
 8428                        .expect("prefixes is non-empty");
 8429                    let prefix_trimmed_lengths = full_comment_prefixes
 8430                        .iter()
 8431                        .map(|p| p.trim_end_matches(' ').len())
 8432                        .collect::<SmallVec<[usize; 4]>>();
 8433
 8434                    let mut all_selection_lines_are_comments = true;
 8435
 8436                    for row in start_row.0..=end_row.0 {
 8437                        let row = MultiBufferRow(row);
 8438                        if start_row < end_row && snapshot.is_line_blank(row) {
 8439                            continue;
 8440                        }
 8441
 8442                        let prefix_range = full_comment_prefixes
 8443                            .iter()
 8444                            .zip(prefix_trimmed_lengths.iter().copied())
 8445                            .map(|(prefix, trimmed_prefix_len)| {
 8446                                comment_prefix_range(
 8447                                    snapshot.deref(),
 8448                                    row,
 8449                                    &prefix[..trimmed_prefix_len],
 8450                                    &prefix[trimmed_prefix_len..],
 8451                                    ignore_indent,
 8452                                )
 8453                            })
 8454                            .max_by_key(|range| range.end.column - range.start.column)
 8455                            .expect("prefixes is non-empty");
 8456
 8457                        if prefix_range.is_empty() {
 8458                            all_selection_lines_are_comments = false;
 8459                        }
 8460
 8461                        selection_edit_ranges.push(prefix_range);
 8462                    }
 8463
 8464                    if all_selection_lines_are_comments {
 8465                        edits.extend(
 8466                            selection_edit_ranges
 8467                                .iter()
 8468                                .cloned()
 8469                                .map(|range| (range, empty_str.clone())),
 8470                        );
 8471                    } else {
 8472                        let min_column = selection_edit_ranges
 8473                            .iter()
 8474                            .map(|range| range.start.column)
 8475                            .min()
 8476                            .unwrap_or(0);
 8477                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8478                            let position = Point::new(range.start.row, min_column);
 8479                            (position..position, first_prefix.clone())
 8480                        }));
 8481                    }
 8482                } else if let Some((full_comment_prefix, comment_suffix)) =
 8483                    language.block_comment_delimiters()
 8484                {
 8485                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8486                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8487                    let prefix_range = comment_prefix_range(
 8488                        snapshot.deref(),
 8489                        start_row,
 8490                        comment_prefix,
 8491                        comment_prefix_whitespace,
 8492                        ignore_indent,
 8493                    );
 8494                    let suffix_range = comment_suffix_range(
 8495                        snapshot.deref(),
 8496                        end_row,
 8497                        comment_suffix.trim_start_matches(' '),
 8498                        comment_suffix.starts_with(' '),
 8499                    );
 8500
 8501                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8502                        edits.push((
 8503                            prefix_range.start..prefix_range.start,
 8504                            full_comment_prefix.clone(),
 8505                        ));
 8506                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8507                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8508                    } else {
 8509                        edits.push((prefix_range, empty_str.clone()));
 8510                        edits.push((suffix_range, empty_str.clone()));
 8511                    }
 8512                } else {
 8513                    continue;
 8514                }
 8515            }
 8516
 8517            drop(snapshot);
 8518            this.buffer.update(cx, |buffer, cx| {
 8519                buffer.edit(edits, None, cx);
 8520            });
 8521
 8522            // Adjust selections so that they end before any comment suffixes that
 8523            // were inserted.
 8524            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8525            let mut selections = this.selections.all::<Point>(cx);
 8526            let snapshot = this.buffer.read(cx).read(cx);
 8527            for selection in &mut selections {
 8528                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8529                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8530                        Ordering::Less => {
 8531                            suffixes_inserted.next();
 8532                            continue;
 8533                        }
 8534                        Ordering::Greater => break,
 8535                        Ordering::Equal => {
 8536                            if selection.end.column == snapshot.line_len(row) {
 8537                                if selection.is_empty() {
 8538                                    selection.start.column -= suffix_len as u32;
 8539                                }
 8540                                selection.end.column -= suffix_len as u32;
 8541                            }
 8542                            break;
 8543                        }
 8544                    }
 8545                }
 8546            }
 8547
 8548            drop(snapshot);
 8549            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8550
 8551            let selections = this.selections.all::<Point>(cx);
 8552            let selections_on_single_row = selections.windows(2).all(|selections| {
 8553                selections[0].start.row == selections[1].start.row
 8554                    && selections[0].end.row == selections[1].end.row
 8555                    && selections[0].start.row == selections[0].end.row
 8556            });
 8557            let selections_selecting = selections
 8558                .iter()
 8559                .any(|selection| selection.start != selection.end);
 8560            let advance_downwards = action.advance_downwards
 8561                && selections_on_single_row
 8562                && !selections_selecting
 8563                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8564
 8565            if advance_downwards {
 8566                let snapshot = this.buffer.read(cx).snapshot(cx);
 8567
 8568                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8569                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8570                        let mut point = display_point.to_point(display_snapshot);
 8571                        point.row += 1;
 8572                        point = snapshot.clip_point(point, Bias::Left);
 8573                        let display_point = point.to_display_point(display_snapshot);
 8574                        let goal = SelectionGoal::HorizontalPosition(
 8575                            display_snapshot
 8576                                .x_for_display_point(display_point, text_layout_details)
 8577                                .into(),
 8578                        );
 8579                        (display_point, goal)
 8580                    })
 8581                });
 8582            }
 8583        });
 8584    }
 8585
 8586    pub fn select_enclosing_symbol(
 8587        &mut self,
 8588        _: &SelectEnclosingSymbol,
 8589        cx: &mut ViewContext<Self>,
 8590    ) {
 8591        let buffer = self.buffer.read(cx).snapshot(cx);
 8592        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8593
 8594        fn update_selection(
 8595            selection: &Selection<usize>,
 8596            buffer_snap: &MultiBufferSnapshot,
 8597        ) -> Option<Selection<usize>> {
 8598            let cursor = selection.head();
 8599            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8600            for symbol in symbols.iter().rev() {
 8601                let start = symbol.range.start.to_offset(buffer_snap);
 8602                let end = symbol.range.end.to_offset(buffer_snap);
 8603                let new_range = start..end;
 8604                if start < selection.start || end > selection.end {
 8605                    return Some(Selection {
 8606                        id: selection.id,
 8607                        start: new_range.start,
 8608                        end: new_range.end,
 8609                        goal: SelectionGoal::None,
 8610                        reversed: selection.reversed,
 8611                    });
 8612                }
 8613            }
 8614            None
 8615        }
 8616
 8617        let mut selected_larger_symbol = false;
 8618        let new_selections = old_selections
 8619            .iter()
 8620            .map(|selection| match update_selection(selection, &buffer) {
 8621                Some(new_selection) => {
 8622                    if new_selection.range() != selection.range() {
 8623                        selected_larger_symbol = true;
 8624                    }
 8625                    new_selection
 8626                }
 8627                None => selection.clone(),
 8628            })
 8629            .collect::<Vec<_>>();
 8630
 8631        if selected_larger_symbol {
 8632            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8633                s.select(new_selections);
 8634            });
 8635        }
 8636    }
 8637
 8638    pub fn select_larger_syntax_node(
 8639        &mut self,
 8640        _: &SelectLargerSyntaxNode,
 8641        cx: &mut ViewContext<Self>,
 8642    ) {
 8643        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8644        let buffer = self.buffer.read(cx).snapshot(cx);
 8645        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8646
 8647        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8648        let mut selected_larger_node = false;
 8649        let new_selections = old_selections
 8650            .iter()
 8651            .map(|selection| {
 8652                let old_range = selection.start..selection.end;
 8653                let mut new_range = old_range.clone();
 8654                while let Some(containing_range) =
 8655                    buffer.range_for_syntax_ancestor(new_range.clone())
 8656                {
 8657                    new_range = containing_range;
 8658                    if !display_map.intersects_fold(new_range.start)
 8659                        && !display_map.intersects_fold(new_range.end)
 8660                    {
 8661                        break;
 8662                    }
 8663                }
 8664
 8665                selected_larger_node |= new_range != old_range;
 8666                Selection {
 8667                    id: selection.id,
 8668                    start: new_range.start,
 8669                    end: new_range.end,
 8670                    goal: SelectionGoal::None,
 8671                    reversed: selection.reversed,
 8672                }
 8673            })
 8674            .collect::<Vec<_>>();
 8675
 8676        if selected_larger_node {
 8677            stack.push(old_selections);
 8678            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8679                s.select(new_selections);
 8680            });
 8681        }
 8682        self.select_larger_syntax_node_stack = stack;
 8683    }
 8684
 8685    pub fn select_smaller_syntax_node(
 8686        &mut self,
 8687        _: &SelectSmallerSyntaxNode,
 8688        cx: &mut ViewContext<Self>,
 8689    ) {
 8690        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8691        if let Some(selections) = stack.pop() {
 8692            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8693                s.select(selections.to_vec());
 8694            });
 8695        }
 8696        self.select_larger_syntax_node_stack = stack;
 8697    }
 8698
 8699    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8700        if !EditorSettings::get_global(cx).gutter.runnables {
 8701            self.clear_tasks();
 8702            return Task::ready(());
 8703        }
 8704        let project = self.project.as_ref().map(Model::downgrade);
 8705        cx.spawn(|this, mut cx| async move {
 8706            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8707            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8708                return;
 8709            };
 8710            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8711                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8712            }) else {
 8713                return;
 8714            };
 8715
 8716            let hide_runnables = project
 8717                .update(&mut cx, |project, cx| {
 8718                    // Do not display any test indicators in non-dev server remote projects.
 8719                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8720                })
 8721                .unwrap_or(true);
 8722            if hide_runnables {
 8723                return;
 8724            }
 8725            let new_rows =
 8726                cx.background_executor()
 8727                    .spawn({
 8728                        let snapshot = display_snapshot.clone();
 8729                        async move {
 8730                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8731                        }
 8732                    })
 8733                    .await;
 8734            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8735
 8736            this.update(&mut cx, |this, _| {
 8737                this.clear_tasks();
 8738                for (key, value) in rows {
 8739                    this.insert_tasks(key, value);
 8740                }
 8741            })
 8742            .ok();
 8743        })
 8744    }
 8745    fn fetch_runnable_ranges(
 8746        snapshot: &DisplaySnapshot,
 8747        range: Range<Anchor>,
 8748    ) -> Vec<language::RunnableRange> {
 8749        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8750    }
 8751
 8752    fn runnable_rows(
 8753        project: Model<Project>,
 8754        snapshot: DisplaySnapshot,
 8755        runnable_ranges: Vec<RunnableRange>,
 8756        mut cx: AsyncWindowContext,
 8757    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8758        runnable_ranges
 8759            .into_iter()
 8760            .filter_map(|mut runnable| {
 8761                let tasks = cx
 8762                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8763                    .ok()?;
 8764                if tasks.is_empty() {
 8765                    return None;
 8766                }
 8767
 8768                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8769
 8770                let row = snapshot
 8771                    .buffer_snapshot
 8772                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8773                    .1
 8774                    .start
 8775                    .row;
 8776
 8777                let context_range =
 8778                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8779                Some((
 8780                    (runnable.buffer_id, row),
 8781                    RunnableTasks {
 8782                        templates: tasks,
 8783                        offset: MultiBufferOffset(runnable.run_range.start),
 8784                        context_range,
 8785                        column: point.column,
 8786                        extra_variables: runnable.extra_captures,
 8787                    },
 8788                ))
 8789            })
 8790            .collect()
 8791    }
 8792
 8793    fn templates_with_tags(
 8794        project: &Model<Project>,
 8795        runnable: &mut Runnable,
 8796        cx: &WindowContext<'_>,
 8797    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8798        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8799            let (worktree_id, file) = project
 8800                .buffer_for_id(runnable.buffer, cx)
 8801                .and_then(|buffer| buffer.read(cx).file())
 8802                .map(|file| (file.worktree_id(cx), file.clone()))
 8803                .unzip();
 8804
 8805            (
 8806                project.task_store().read(cx).task_inventory().cloned(),
 8807                worktree_id,
 8808                file,
 8809            )
 8810        });
 8811
 8812        let tags = mem::take(&mut runnable.tags);
 8813        let mut tags: Vec<_> = tags
 8814            .into_iter()
 8815            .flat_map(|tag| {
 8816                let tag = tag.0.clone();
 8817                inventory
 8818                    .as_ref()
 8819                    .into_iter()
 8820                    .flat_map(|inventory| {
 8821                        inventory.read(cx).list_tasks(
 8822                            file.clone(),
 8823                            Some(runnable.language.clone()),
 8824                            worktree_id,
 8825                            cx,
 8826                        )
 8827                    })
 8828                    .filter(move |(_, template)| {
 8829                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8830                    })
 8831            })
 8832            .sorted_by_key(|(kind, _)| kind.to_owned())
 8833            .collect();
 8834        if let Some((leading_tag_source, _)) = tags.first() {
 8835            // Strongest source wins; if we have worktree tag binding, prefer that to
 8836            // global and language bindings;
 8837            // if we have a global binding, prefer that to language binding.
 8838            let first_mismatch = tags
 8839                .iter()
 8840                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8841            if let Some(index) = first_mismatch {
 8842                tags.truncate(index);
 8843            }
 8844        }
 8845
 8846        tags
 8847    }
 8848
 8849    pub fn move_to_enclosing_bracket(
 8850        &mut self,
 8851        _: &MoveToEnclosingBracket,
 8852        cx: &mut ViewContext<Self>,
 8853    ) {
 8854        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8855            s.move_offsets_with(|snapshot, selection| {
 8856                let Some(enclosing_bracket_ranges) =
 8857                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8858                else {
 8859                    return;
 8860                };
 8861
 8862                let mut best_length = usize::MAX;
 8863                let mut best_inside = false;
 8864                let mut best_in_bracket_range = false;
 8865                let mut best_destination = None;
 8866                for (open, close) in enclosing_bracket_ranges {
 8867                    let close = close.to_inclusive();
 8868                    let length = close.end() - open.start;
 8869                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8870                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8871                        || close.contains(&selection.head());
 8872
 8873                    // If best is next to a bracket and current isn't, skip
 8874                    if !in_bracket_range && best_in_bracket_range {
 8875                        continue;
 8876                    }
 8877
 8878                    // Prefer smaller lengths unless best is inside and current isn't
 8879                    if length > best_length && (best_inside || !inside) {
 8880                        continue;
 8881                    }
 8882
 8883                    best_length = length;
 8884                    best_inside = inside;
 8885                    best_in_bracket_range = in_bracket_range;
 8886                    best_destination = Some(
 8887                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8888                            if inside {
 8889                                open.end
 8890                            } else {
 8891                                open.start
 8892                            }
 8893                        } else if inside {
 8894                            *close.start()
 8895                        } else {
 8896                            *close.end()
 8897                        },
 8898                    );
 8899                }
 8900
 8901                if let Some(destination) = best_destination {
 8902                    selection.collapse_to(destination, SelectionGoal::None);
 8903                }
 8904            })
 8905        });
 8906    }
 8907
 8908    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8909        self.end_selection(cx);
 8910        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8911        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8912            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8913            self.select_next_state = entry.select_next_state;
 8914            self.select_prev_state = entry.select_prev_state;
 8915            self.add_selections_state = entry.add_selections_state;
 8916            self.request_autoscroll(Autoscroll::newest(), cx);
 8917        }
 8918        self.selection_history.mode = SelectionHistoryMode::Normal;
 8919    }
 8920
 8921    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8922        self.end_selection(cx);
 8923        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8924        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8925            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8926            self.select_next_state = entry.select_next_state;
 8927            self.select_prev_state = entry.select_prev_state;
 8928            self.add_selections_state = entry.add_selections_state;
 8929            self.request_autoscroll(Autoscroll::newest(), cx);
 8930        }
 8931        self.selection_history.mode = SelectionHistoryMode::Normal;
 8932    }
 8933
 8934    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8935        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8936    }
 8937
 8938    pub fn expand_excerpts_down(
 8939        &mut self,
 8940        action: &ExpandExcerptsDown,
 8941        cx: &mut ViewContext<Self>,
 8942    ) {
 8943        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8944    }
 8945
 8946    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8947        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8948    }
 8949
 8950    pub fn expand_excerpts_for_direction(
 8951        &mut self,
 8952        lines: u32,
 8953        direction: ExpandExcerptDirection,
 8954        cx: &mut ViewContext<Self>,
 8955    ) {
 8956        let selections = self.selections.disjoint_anchors();
 8957
 8958        let lines = if lines == 0 {
 8959            EditorSettings::get_global(cx).expand_excerpt_lines
 8960        } else {
 8961            lines
 8962        };
 8963
 8964        self.buffer.update(cx, |buffer, cx| {
 8965            buffer.expand_excerpts(
 8966                selections
 8967                    .iter()
 8968                    .map(|selection| selection.head().excerpt_id)
 8969                    .dedup(),
 8970                lines,
 8971                direction,
 8972                cx,
 8973            )
 8974        })
 8975    }
 8976
 8977    pub fn expand_excerpt(
 8978        &mut self,
 8979        excerpt: ExcerptId,
 8980        direction: ExpandExcerptDirection,
 8981        cx: &mut ViewContext<Self>,
 8982    ) {
 8983        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8984        self.buffer.update(cx, |buffer, cx| {
 8985            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8986        })
 8987    }
 8988
 8989    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8990        self.go_to_diagnostic_impl(Direction::Next, cx)
 8991    }
 8992
 8993    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8994        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8995    }
 8996
 8997    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8998        let buffer = self.buffer.read(cx).snapshot(cx);
 8999        let selection = self.selections.newest::<usize>(cx);
 9000
 9001        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9002        if direction == Direction::Next {
 9003            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9004                let (group_id, jump_to) = popover.activation_info();
 9005                if self.activate_diagnostics(group_id, cx) {
 9006                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9007                        let mut new_selection = s.newest_anchor().clone();
 9008                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9009                        s.select_anchors(vec![new_selection.clone()]);
 9010                    });
 9011                }
 9012                return;
 9013            }
 9014        }
 9015
 9016        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9017            active_diagnostics
 9018                .primary_range
 9019                .to_offset(&buffer)
 9020                .to_inclusive()
 9021        });
 9022        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9023            if active_primary_range.contains(&selection.head()) {
 9024                *active_primary_range.start()
 9025            } else {
 9026                selection.head()
 9027            }
 9028        } else {
 9029            selection.head()
 9030        };
 9031        let snapshot = self.snapshot(cx);
 9032        loop {
 9033            let diagnostics = if direction == Direction::Prev {
 9034                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9035            } else {
 9036                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9037            }
 9038            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9039            let group = diagnostics
 9040                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9041                // be sorted in a stable way
 9042                // skip until we are at current active diagnostic, if it exists
 9043                .skip_while(|entry| {
 9044                    (match direction {
 9045                        Direction::Prev => entry.range.start >= search_start,
 9046                        Direction::Next => entry.range.start <= search_start,
 9047                    }) && self
 9048                        .active_diagnostics
 9049                        .as_ref()
 9050                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9051                })
 9052                .find_map(|entry| {
 9053                    if entry.diagnostic.is_primary
 9054                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9055                        && !entry.range.is_empty()
 9056                        // if we match with the active diagnostic, skip it
 9057                        && Some(entry.diagnostic.group_id)
 9058                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9059                    {
 9060                        Some((entry.range, entry.diagnostic.group_id))
 9061                    } else {
 9062                        None
 9063                    }
 9064                });
 9065
 9066            if let Some((primary_range, group_id)) = group {
 9067                if self.activate_diagnostics(group_id, cx) {
 9068                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9069                        s.select(vec![Selection {
 9070                            id: selection.id,
 9071                            start: primary_range.start,
 9072                            end: primary_range.start,
 9073                            reversed: false,
 9074                            goal: SelectionGoal::None,
 9075                        }]);
 9076                    });
 9077                }
 9078                break;
 9079            } else {
 9080                // Cycle around to the start of the buffer, potentially moving back to the start of
 9081                // the currently active diagnostic.
 9082                active_primary_range.take();
 9083                if direction == Direction::Prev {
 9084                    if search_start == buffer.len() {
 9085                        break;
 9086                    } else {
 9087                        search_start = buffer.len();
 9088                    }
 9089                } else if search_start == 0 {
 9090                    break;
 9091                } else {
 9092                    search_start = 0;
 9093                }
 9094            }
 9095        }
 9096    }
 9097
 9098    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9099        let snapshot = self.snapshot(cx);
 9100        let selection = self.selections.newest::<Point>(cx);
 9101        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9102    }
 9103
 9104    fn go_to_hunk_after_position(
 9105        &mut self,
 9106        snapshot: &EditorSnapshot,
 9107        position: Point,
 9108        cx: &mut ViewContext<'_, Editor>,
 9109    ) -> Option<MultiBufferDiffHunk> {
 9110        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9111            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9112                snapshot,
 9113                position,
 9114                ix > 0,
 9115                snapshot.diff_map.diff_hunks_in_range(
 9116                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9117                    &snapshot.buffer_snapshot,
 9118                ),
 9119                cx,
 9120            ) {
 9121                return Some(hunk);
 9122            }
 9123        }
 9124        None
 9125    }
 9126
 9127    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9128        let snapshot = self.snapshot(cx);
 9129        let selection = self.selections.newest::<Point>(cx);
 9130        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9131    }
 9132
 9133    fn go_to_hunk_before_position(
 9134        &mut self,
 9135        snapshot: &EditorSnapshot,
 9136        position: Point,
 9137        cx: &mut ViewContext<'_, Editor>,
 9138    ) -> Option<MultiBufferDiffHunk> {
 9139        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9140            .into_iter()
 9141            .enumerate()
 9142        {
 9143            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9144                snapshot,
 9145                position,
 9146                ix > 0,
 9147                snapshot
 9148                    .diff_map
 9149                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9150                cx,
 9151            ) {
 9152                return Some(hunk);
 9153            }
 9154        }
 9155        None
 9156    }
 9157
 9158    fn go_to_next_hunk_in_direction(
 9159        &mut self,
 9160        snapshot: &DisplaySnapshot,
 9161        initial_point: Point,
 9162        is_wrapped: bool,
 9163        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9164        cx: &mut ViewContext<Editor>,
 9165    ) -> Option<MultiBufferDiffHunk> {
 9166        let display_point = initial_point.to_display_point(snapshot);
 9167        let mut hunks = hunks
 9168            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9169            .filter(|(display_hunk, _)| {
 9170                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9171            })
 9172            .dedup();
 9173
 9174        if let Some((display_hunk, hunk)) = hunks.next() {
 9175            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9176                let row = display_hunk.start_display_row();
 9177                let point = DisplayPoint::new(row, 0);
 9178                s.select_display_ranges([point..point]);
 9179            });
 9180
 9181            Some(hunk)
 9182        } else {
 9183            None
 9184        }
 9185    }
 9186
 9187    pub fn go_to_definition(
 9188        &mut self,
 9189        _: &GoToDefinition,
 9190        cx: &mut ViewContext<Self>,
 9191    ) -> Task<Result<Navigated>> {
 9192        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9193        cx.spawn(|editor, mut cx| async move {
 9194            if definition.await? == Navigated::Yes {
 9195                return Ok(Navigated::Yes);
 9196            }
 9197            match editor.update(&mut cx, |editor, cx| {
 9198                editor.find_all_references(&FindAllReferences, cx)
 9199            })? {
 9200                Some(references) => references.await,
 9201                None => Ok(Navigated::No),
 9202            }
 9203        })
 9204    }
 9205
 9206    pub fn go_to_declaration(
 9207        &mut self,
 9208        _: &GoToDeclaration,
 9209        cx: &mut ViewContext<Self>,
 9210    ) -> Task<Result<Navigated>> {
 9211        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9212    }
 9213
 9214    pub fn go_to_declaration_split(
 9215        &mut self,
 9216        _: &GoToDeclaration,
 9217        cx: &mut ViewContext<Self>,
 9218    ) -> Task<Result<Navigated>> {
 9219        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9220    }
 9221
 9222    pub fn go_to_implementation(
 9223        &mut self,
 9224        _: &GoToImplementation,
 9225        cx: &mut ViewContext<Self>,
 9226    ) -> Task<Result<Navigated>> {
 9227        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9228    }
 9229
 9230    pub fn go_to_implementation_split(
 9231        &mut self,
 9232        _: &GoToImplementationSplit,
 9233        cx: &mut ViewContext<Self>,
 9234    ) -> Task<Result<Navigated>> {
 9235        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9236    }
 9237
 9238    pub fn go_to_type_definition(
 9239        &mut self,
 9240        _: &GoToTypeDefinition,
 9241        cx: &mut ViewContext<Self>,
 9242    ) -> Task<Result<Navigated>> {
 9243        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9244    }
 9245
 9246    pub fn go_to_definition_split(
 9247        &mut self,
 9248        _: &GoToDefinitionSplit,
 9249        cx: &mut ViewContext<Self>,
 9250    ) -> Task<Result<Navigated>> {
 9251        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9252    }
 9253
 9254    pub fn go_to_type_definition_split(
 9255        &mut self,
 9256        _: &GoToTypeDefinitionSplit,
 9257        cx: &mut ViewContext<Self>,
 9258    ) -> Task<Result<Navigated>> {
 9259        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9260    }
 9261
 9262    fn go_to_definition_of_kind(
 9263        &mut self,
 9264        kind: GotoDefinitionKind,
 9265        split: bool,
 9266        cx: &mut ViewContext<Self>,
 9267    ) -> Task<Result<Navigated>> {
 9268        let Some(provider) = self.semantics_provider.clone() else {
 9269            return Task::ready(Ok(Navigated::No));
 9270        };
 9271        let head = self.selections.newest::<usize>(cx).head();
 9272        let buffer = self.buffer.read(cx);
 9273        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9274            text_anchor
 9275        } else {
 9276            return Task::ready(Ok(Navigated::No));
 9277        };
 9278
 9279        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9280            return Task::ready(Ok(Navigated::No));
 9281        };
 9282
 9283        cx.spawn(|editor, mut cx| async move {
 9284            let definitions = definitions.await?;
 9285            let navigated = editor
 9286                .update(&mut cx, |editor, cx| {
 9287                    editor.navigate_to_hover_links(
 9288                        Some(kind),
 9289                        definitions
 9290                            .into_iter()
 9291                            .filter(|location| {
 9292                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9293                            })
 9294                            .map(HoverLink::Text)
 9295                            .collect::<Vec<_>>(),
 9296                        split,
 9297                        cx,
 9298                    )
 9299                })?
 9300                .await?;
 9301            anyhow::Ok(navigated)
 9302        })
 9303    }
 9304
 9305    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9306        let selection = self.selections.newest_anchor();
 9307        let head = selection.head();
 9308        let tail = selection.tail();
 9309
 9310        let Some((buffer, start_position)) =
 9311            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9312        else {
 9313            return;
 9314        };
 9315
 9316        let end_position = if head != tail {
 9317            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9318                return;
 9319            };
 9320            Some(pos)
 9321        } else {
 9322            None
 9323        };
 9324
 9325        let url_finder = cx.spawn(|editor, mut cx| async move {
 9326            let url = if let Some(end_pos) = end_position {
 9327                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9328            } else {
 9329                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9330            };
 9331
 9332            if let Some(url) = url {
 9333                editor.update(&mut cx, |_, cx| {
 9334                    cx.open_url(&url);
 9335                })
 9336            } else {
 9337                Ok(())
 9338            }
 9339        });
 9340
 9341        url_finder.detach();
 9342    }
 9343
 9344    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9345        let Some(workspace) = self.workspace() else {
 9346            return;
 9347        };
 9348
 9349        let position = self.selections.newest_anchor().head();
 9350
 9351        let Some((buffer, buffer_position)) =
 9352            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9353        else {
 9354            return;
 9355        };
 9356
 9357        let project = self.project.clone();
 9358
 9359        cx.spawn(|_, mut cx| async move {
 9360            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9361
 9362            if let Some((_, path)) = result {
 9363                workspace
 9364                    .update(&mut cx, |workspace, cx| {
 9365                        workspace.open_resolved_path(path, cx)
 9366                    })?
 9367                    .await?;
 9368            }
 9369            anyhow::Ok(())
 9370        })
 9371        .detach();
 9372    }
 9373
 9374    pub(crate) fn navigate_to_hover_links(
 9375        &mut self,
 9376        kind: Option<GotoDefinitionKind>,
 9377        mut definitions: Vec<HoverLink>,
 9378        split: bool,
 9379        cx: &mut ViewContext<Editor>,
 9380    ) -> Task<Result<Navigated>> {
 9381        // If there is one definition, just open it directly
 9382        if definitions.len() == 1 {
 9383            let definition = definitions.pop().unwrap();
 9384
 9385            enum TargetTaskResult {
 9386                Location(Option<Location>),
 9387                AlreadyNavigated,
 9388            }
 9389
 9390            let target_task = match definition {
 9391                HoverLink::Text(link) => {
 9392                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9393                }
 9394                HoverLink::InlayHint(lsp_location, server_id) => {
 9395                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9396                    cx.background_executor().spawn(async move {
 9397                        let location = computation.await?;
 9398                        Ok(TargetTaskResult::Location(location))
 9399                    })
 9400                }
 9401                HoverLink::Url(url) => {
 9402                    cx.open_url(&url);
 9403                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9404                }
 9405                HoverLink::File(path) => {
 9406                    if let Some(workspace) = self.workspace() {
 9407                        cx.spawn(|_, mut cx| async move {
 9408                            workspace
 9409                                .update(&mut cx, |workspace, cx| {
 9410                                    workspace.open_resolved_path(path, cx)
 9411                                })?
 9412                                .await
 9413                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9414                        })
 9415                    } else {
 9416                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9417                    }
 9418                }
 9419            };
 9420            cx.spawn(|editor, mut cx| async move {
 9421                let target = match target_task.await.context("target resolution task")? {
 9422                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9423                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9424                    TargetTaskResult::Location(Some(target)) => target,
 9425                };
 9426
 9427                editor.update(&mut cx, |editor, cx| {
 9428                    let Some(workspace) = editor.workspace() else {
 9429                        return Navigated::No;
 9430                    };
 9431                    let pane = workspace.read(cx).active_pane().clone();
 9432
 9433                    let range = target.range.to_offset(target.buffer.read(cx));
 9434                    let range = editor.range_for_match(&range);
 9435
 9436                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9437                        let buffer = target.buffer.read(cx);
 9438                        let range = check_multiline_range(buffer, range);
 9439                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9440                            s.select_ranges([range]);
 9441                        });
 9442                    } else {
 9443                        cx.window_context().defer(move |cx| {
 9444                            let target_editor: View<Self> =
 9445                                workspace.update(cx, |workspace, cx| {
 9446                                    let pane = if split {
 9447                                        workspace.adjacent_pane(cx)
 9448                                    } else {
 9449                                        workspace.active_pane().clone()
 9450                                    };
 9451
 9452                                    workspace.open_project_item(
 9453                                        pane,
 9454                                        target.buffer.clone(),
 9455                                        true,
 9456                                        true,
 9457                                        cx,
 9458                                    )
 9459                                });
 9460                            target_editor.update(cx, |target_editor, cx| {
 9461                                // When selecting a definition in a different buffer, disable the nav history
 9462                                // to avoid creating a history entry at the previous cursor location.
 9463                                pane.update(cx, |pane, _| pane.disable_history());
 9464                                let buffer = target.buffer.read(cx);
 9465                                let range = check_multiline_range(buffer, range);
 9466                                target_editor.change_selections(
 9467                                    Some(Autoscroll::focused()),
 9468                                    cx,
 9469                                    |s| {
 9470                                        s.select_ranges([range]);
 9471                                    },
 9472                                );
 9473                                pane.update(cx, |pane, _| pane.enable_history());
 9474                            });
 9475                        });
 9476                    }
 9477                    Navigated::Yes
 9478                })
 9479            })
 9480        } else if !definitions.is_empty() {
 9481            cx.spawn(|editor, mut cx| async move {
 9482                let (title, location_tasks, workspace) = editor
 9483                    .update(&mut cx, |editor, cx| {
 9484                        let tab_kind = match kind {
 9485                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9486                            _ => "Definitions",
 9487                        };
 9488                        let title = definitions
 9489                            .iter()
 9490                            .find_map(|definition| match definition {
 9491                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9492                                    let buffer = origin.buffer.read(cx);
 9493                                    format!(
 9494                                        "{} for {}",
 9495                                        tab_kind,
 9496                                        buffer
 9497                                            .text_for_range(origin.range.clone())
 9498                                            .collect::<String>()
 9499                                    )
 9500                                }),
 9501                                HoverLink::InlayHint(_, _) => None,
 9502                                HoverLink::Url(_) => None,
 9503                                HoverLink::File(_) => None,
 9504                            })
 9505                            .unwrap_or(tab_kind.to_string());
 9506                        let location_tasks = definitions
 9507                            .into_iter()
 9508                            .map(|definition| match definition {
 9509                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9510                                HoverLink::InlayHint(lsp_location, server_id) => {
 9511                                    editor.compute_target_location(lsp_location, server_id, cx)
 9512                                }
 9513                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9514                                HoverLink::File(_) => Task::ready(Ok(None)),
 9515                            })
 9516                            .collect::<Vec<_>>();
 9517                        (title, location_tasks, editor.workspace().clone())
 9518                    })
 9519                    .context("location tasks preparation")?;
 9520
 9521                let locations = future::join_all(location_tasks)
 9522                    .await
 9523                    .into_iter()
 9524                    .filter_map(|location| location.transpose())
 9525                    .collect::<Result<_>>()
 9526                    .context("location tasks")?;
 9527
 9528                let Some(workspace) = workspace else {
 9529                    return Ok(Navigated::No);
 9530                };
 9531                let opened = workspace
 9532                    .update(&mut cx, |workspace, cx| {
 9533                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9534                    })
 9535                    .ok();
 9536
 9537                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9538            })
 9539        } else {
 9540            Task::ready(Ok(Navigated::No))
 9541        }
 9542    }
 9543
 9544    fn compute_target_location(
 9545        &self,
 9546        lsp_location: lsp::Location,
 9547        server_id: LanguageServerId,
 9548        cx: &mut ViewContext<Self>,
 9549    ) -> Task<anyhow::Result<Option<Location>>> {
 9550        let Some(project) = self.project.clone() else {
 9551            return Task::ready(Ok(None));
 9552        };
 9553
 9554        cx.spawn(move |editor, mut cx| async move {
 9555            let location_task = editor.update(&mut cx, |_, cx| {
 9556                project.update(cx, |project, cx| {
 9557                    let language_server_name = project
 9558                        .language_server_statuses(cx)
 9559                        .find(|(id, _)| server_id == *id)
 9560                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9561                    language_server_name.map(|language_server_name| {
 9562                        project.open_local_buffer_via_lsp(
 9563                            lsp_location.uri.clone(),
 9564                            server_id,
 9565                            language_server_name,
 9566                            cx,
 9567                        )
 9568                    })
 9569                })
 9570            })?;
 9571            let location = match location_task {
 9572                Some(task) => Some({
 9573                    let target_buffer_handle = task.await.context("open local buffer")?;
 9574                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9575                        let target_start = target_buffer
 9576                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9577                        let target_end = target_buffer
 9578                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9579                        target_buffer.anchor_after(target_start)
 9580                            ..target_buffer.anchor_before(target_end)
 9581                    })?;
 9582                    Location {
 9583                        buffer: target_buffer_handle,
 9584                        range,
 9585                    }
 9586                }),
 9587                None => None,
 9588            };
 9589            Ok(location)
 9590        })
 9591    }
 9592
 9593    pub fn find_all_references(
 9594        &mut self,
 9595        _: &FindAllReferences,
 9596        cx: &mut ViewContext<Self>,
 9597    ) -> Option<Task<Result<Navigated>>> {
 9598        let selection = self.selections.newest::<usize>(cx);
 9599        let multi_buffer = self.buffer.read(cx);
 9600        let head = selection.head();
 9601
 9602        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9603        let head_anchor = multi_buffer_snapshot.anchor_at(
 9604            head,
 9605            if head < selection.tail() {
 9606                Bias::Right
 9607            } else {
 9608                Bias::Left
 9609            },
 9610        );
 9611
 9612        match self
 9613            .find_all_references_task_sources
 9614            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9615        {
 9616            Ok(_) => {
 9617                log::info!(
 9618                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9619                );
 9620                return None;
 9621            }
 9622            Err(i) => {
 9623                self.find_all_references_task_sources.insert(i, head_anchor);
 9624            }
 9625        }
 9626
 9627        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9628        let workspace = self.workspace()?;
 9629        let project = workspace.read(cx).project().clone();
 9630        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9631        Some(cx.spawn(|editor, mut cx| async move {
 9632            let _cleanup = defer({
 9633                let mut cx = cx.clone();
 9634                move || {
 9635                    let _ = editor.update(&mut cx, |editor, _| {
 9636                        if let Ok(i) =
 9637                            editor
 9638                                .find_all_references_task_sources
 9639                                .binary_search_by(|anchor| {
 9640                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9641                                })
 9642                        {
 9643                            editor.find_all_references_task_sources.remove(i);
 9644                        }
 9645                    });
 9646                }
 9647            });
 9648
 9649            let locations = references.await?;
 9650            if locations.is_empty() {
 9651                return anyhow::Ok(Navigated::No);
 9652            }
 9653
 9654            workspace.update(&mut cx, |workspace, cx| {
 9655                let title = locations
 9656                    .first()
 9657                    .as_ref()
 9658                    .map(|location| {
 9659                        let buffer = location.buffer.read(cx);
 9660                        format!(
 9661                            "References to `{}`",
 9662                            buffer
 9663                                .text_for_range(location.range.clone())
 9664                                .collect::<String>()
 9665                        )
 9666                    })
 9667                    .unwrap();
 9668                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9669                Navigated::Yes
 9670            })
 9671        }))
 9672    }
 9673
 9674    /// Opens a multibuffer with the given project locations in it
 9675    pub fn open_locations_in_multibuffer(
 9676        workspace: &mut Workspace,
 9677        mut locations: Vec<Location>,
 9678        title: String,
 9679        split: bool,
 9680        cx: &mut ViewContext<Workspace>,
 9681    ) {
 9682        // If there are multiple definitions, open them in a multibuffer
 9683        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9684        let mut locations = locations.into_iter().peekable();
 9685        let mut ranges_to_highlight = Vec::new();
 9686        let capability = workspace.project().read(cx).capability();
 9687
 9688        let excerpt_buffer = cx.new_model(|cx| {
 9689            let mut multibuffer = MultiBuffer::new(capability);
 9690            while let Some(location) = locations.next() {
 9691                let buffer = location.buffer.read(cx);
 9692                let mut ranges_for_buffer = Vec::new();
 9693                let range = location.range.to_offset(buffer);
 9694                ranges_for_buffer.push(range.clone());
 9695
 9696                while let Some(next_location) = locations.peek() {
 9697                    if next_location.buffer == location.buffer {
 9698                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9699                        locations.next();
 9700                    } else {
 9701                        break;
 9702                    }
 9703                }
 9704
 9705                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9706                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9707                    location.buffer.clone(),
 9708                    ranges_for_buffer,
 9709                    DEFAULT_MULTIBUFFER_CONTEXT,
 9710                    cx,
 9711                ))
 9712            }
 9713
 9714            multibuffer.with_title(title)
 9715        });
 9716
 9717        let editor = cx.new_view(|cx| {
 9718            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9719        });
 9720        editor.update(cx, |editor, cx| {
 9721            if let Some(first_range) = ranges_to_highlight.first() {
 9722                editor.change_selections(None, cx, |selections| {
 9723                    selections.clear_disjoint();
 9724                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9725                });
 9726            }
 9727            editor.highlight_background::<Self>(
 9728                &ranges_to_highlight,
 9729                |theme| theme.editor_highlighted_line_background,
 9730                cx,
 9731            );
 9732            editor.register_buffers_with_language_servers(cx);
 9733        });
 9734
 9735        let item = Box::new(editor);
 9736        let item_id = item.item_id();
 9737
 9738        if split {
 9739            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9740        } else {
 9741            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9742                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9743                    pane.close_current_preview_item(cx)
 9744                } else {
 9745                    None
 9746                }
 9747            });
 9748            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9749        }
 9750        workspace.active_pane().update(cx, |pane, cx| {
 9751            pane.set_preview_item_id(Some(item_id), cx);
 9752        });
 9753    }
 9754
 9755    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9756        use language::ToOffset as _;
 9757
 9758        let provider = self.semantics_provider.clone()?;
 9759        let selection = self.selections.newest_anchor().clone();
 9760        let (cursor_buffer, cursor_buffer_position) = self
 9761            .buffer
 9762            .read(cx)
 9763            .text_anchor_for_position(selection.head(), cx)?;
 9764        let (tail_buffer, cursor_buffer_position_end) = self
 9765            .buffer
 9766            .read(cx)
 9767            .text_anchor_for_position(selection.tail(), cx)?;
 9768        if tail_buffer != cursor_buffer {
 9769            return None;
 9770        }
 9771
 9772        let snapshot = cursor_buffer.read(cx).snapshot();
 9773        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9774        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9775        let prepare_rename = provider
 9776            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9777            .unwrap_or_else(|| Task::ready(Ok(None)));
 9778        drop(snapshot);
 9779
 9780        Some(cx.spawn(|this, mut cx| async move {
 9781            let rename_range = if let Some(range) = prepare_rename.await? {
 9782                Some(range)
 9783            } else {
 9784                this.update(&mut cx, |this, cx| {
 9785                    let buffer = this.buffer.read(cx).snapshot(cx);
 9786                    let mut buffer_highlights = this
 9787                        .document_highlights_for_position(selection.head(), &buffer)
 9788                        .filter(|highlight| {
 9789                            highlight.start.excerpt_id == selection.head().excerpt_id
 9790                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9791                        });
 9792                    buffer_highlights
 9793                        .next()
 9794                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9795                })?
 9796            };
 9797            if let Some(rename_range) = rename_range {
 9798                this.update(&mut cx, |this, cx| {
 9799                    let snapshot = cursor_buffer.read(cx).snapshot();
 9800                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9801                    let cursor_offset_in_rename_range =
 9802                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9803                    let cursor_offset_in_rename_range_end =
 9804                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9805
 9806                    this.take_rename(false, cx);
 9807                    let buffer = this.buffer.read(cx).read(cx);
 9808                    let cursor_offset = selection.head().to_offset(&buffer);
 9809                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9810                    let rename_end = rename_start + rename_buffer_range.len();
 9811                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9812                    let mut old_highlight_id = None;
 9813                    let old_name: Arc<str> = buffer
 9814                        .chunks(rename_start..rename_end, true)
 9815                        .map(|chunk| {
 9816                            if old_highlight_id.is_none() {
 9817                                old_highlight_id = chunk.syntax_highlight_id;
 9818                            }
 9819                            chunk.text
 9820                        })
 9821                        .collect::<String>()
 9822                        .into();
 9823
 9824                    drop(buffer);
 9825
 9826                    // Position the selection in the rename editor so that it matches the current selection.
 9827                    this.show_local_selections = false;
 9828                    let rename_editor = cx.new_view(|cx| {
 9829                        let mut editor = Editor::single_line(cx);
 9830                        editor.buffer.update(cx, |buffer, cx| {
 9831                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9832                        });
 9833                        let rename_selection_range = match cursor_offset_in_rename_range
 9834                            .cmp(&cursor_offset_in_rename_range_end)
 9835                        {
 9836                            Ordering::Equal => {
 9837                                editor.select_all(&SelectAll, cx);
 9838                                return editor;
 9839                            }
 9840                            Ordering::Less => {
 9841                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9842                            }
 9843                            Ordering::Greater => {
 9844                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9845                            }
 9846                        };
 9847                        if rename_selection_range.end > old_name.len() {
 9848                            editor.select_all(&SelectAll, cx);
 9849                        } else {
 9850                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9851                                s.select_ranges([rename_selection_range]);
 9852                            });
 9853                        }
 9854                        editor
 9855                    });
 9856                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9857                        if e == &EditorEvent::Focused {
 9858                            cx.emit(EditorEvent::FocusedIn)
 9859                        }
 9860                    })
 9861                    .detach();
 9862
 9863                    let write_highlights =
 9864                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9865                    let read_highlights =
 9866                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9867                    let ranges = write_highlights
 9868                        .iter()
 9869                        .flat_map(|(_, ranges)| ranges.iter())
 9870                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9871                        .cloned()
 9872                        .collect();
 9873
 9874                    this.highlight_text::<Rename>(
 9875                        ranges,
 9876                        HighlightStyle {
 9877                            fade_out: Some(0.6),
 9878                            ..Default::default()
 9879                        },
 9880                        cx,
 9881                    );
 9882                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9883                    cx.focus(&rename_focus_handle);
 9884                    let block_id = this.insert_blocks(
 9885                        [BlockProperties {
 9886                            style: BlockStyle::Flex,
 9887                            placement: BlockPlacement::Below(range.start),
 9888                            height: 1,
 9889                            render: Arc::new({
 9890                                let rename_editor = rename_editor.clone();
 9891                                move |cx: &mut BlockContext| {
 9892                                    let mut text_style = cx.editor_style.text.clone();
 9893                                    if let Some(highlight_style) = old_highlight_id
 9894                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9895                                    {
 9896                                        text_style = text_style.highlight(highlight_style);
 9897                                    }
 9898                                    div()
 9899                                        .block_mouse_down()
 9900                                        .pl(cx.anchor_x)
 9901                                        .child(EditorElement::new(
 9902                                            &rename_editor,
 9903                                            EditorStyle {
 9904                                                background: cx.theme().system().transparent,
 9905                                                local_player: cx.editor_style.local_player,
 9906                                                text: text_style,
 9907                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9908                                                syntax: cx.editor_style.syntax.clone(),
 9909                                                status: cx.editor_style.status.clone(),
 9910                                                inlay_hints_style: HighlightStyle {
 9911                                                    font_weight: Some(FontWeight::BOLD),
 9912                                                    ..make_inlay_hints_style(cx)
 9913                                                },
 9914                                                inline_completion_styles: make_suggestion_styles(
 9915                                                    cx,
 9916                                                ),
 9917                                                ..EditorStyle::default()
 9918                                            },
 9919                                        ))
 9920                                        .into_any_element()
 9921                                }
 9922                            }),
 9923                            priority: 0,
 9924                        }],
 9925                        Some(Autoscroll::fit()),
 9926                        cx,
 9927                    )[0];
 9928                    this.pending_rename = Some(RenameState {
 9929                        range,
 9930                        old_name,
 9931                        editor: rename_editor,
 9932                        block_id,
 9933                    });
 9934                })?;
 9935            }
 9936
 9937            Ok(())
 9938        }))
 9939    }
 9940
 9941    pub fn confirm_rename(
 9942        &mut self,
 9943        _: &ConfirmRename,
 9944        cx: &mut ViewContext<Self>,
 9945    ) -> Option<Task<Result<()>>> {
 9946        let rename = self.take_rename(false, cx)?;
 9947        let workspace = self.workspace()?.downgrade();
 9948        let (buffer, start) = self
 9949            .buffer
 9950            .read(cx)
 9951            .text_anchor_for_position(rename.range.start, cx)?;
 9952        let (end_buffer, _) = self
 9953            .buffer
 9954            .read(cx)
 9955            .text_anchor_for_position(rename.range.end, cx)?;
 9956        if buffer != end_buffer {
 9957            return None;
 9958        }
 9959
 9960        let old_name = rename.old_name;
 9961        let new_name = rename.editor.read(cx).text(cx);
 9962
 9963        let rename = self.semantics_provider.as_ref()?.perform_rename(
 9964            &buffer,
 9965            start,
 9966            new_name.clone(),
 9967            cx,
 9968        )?;
 9969
 9970        Some(cx.spawn(|editor, mut cx| async move {
 9971            let project_transaction = rename.await?;
 9972            Self::open_project_transaction(
 9973                &editor,
 9974                workspace,
 9975                project_transaction,
 9976                format!("Rename: {}{}", old_name, new_name),
 9977                cx.clone(),
 9978            )
 9979            .await?;
 9980
 9981            editor.update(&mut cx, |editor, cx| {
 9982                editor.refresh_document_highlights(cx);
 9983            })?;
 9984            Ok(())
 9985        }))
 9986    }
 9987
 9988    fn take_rename(
 9989        &mut self,
 9990        moving_cursor: bool,
 9991        cx: &mut ViewContext<Self>,
 9992    ) -> Option<RenameState> {
 9993        let rename = self.pending_rename.take()?;
 9994        if rename.editor.focus_handle(cx).is_focused(cx) {
 9995            cx.focus(&self.focus_handle);
 9996        }
 9997
 9998        self.remove_blocks(
 9999            [rename.block_id].into_iter().collect(),
10000            Some(Autoscroll::fit()),
10001            cx,
10002        );
10003        self.clear_highlights::<Rename>(cx);
10004        self.show_local_selections = true;
10005
10006        if moving_cursor {
10007            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10008                editor.selections.newest::<usize>(cx).head()
10009            });
10010
10011            // Update the selection to match the position of the selection inside
10012            // the rename editor.
10013            let snapshot = self.buffer.read(cx).read(cx);
10014            let rename_range = rename.range.to_offset(&snapshot);
10015            let cursor_in_editor = snapshot
10016                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10017                .min(rename_range.end);
10018            drop(snapshot);
10019
10020            self.change_selections(None, cx, |s| {
10021                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10022            });
10023        } else {
10024            self.refresh_document_highlights(cx);
10025        }
10026
10027        Some(rename)
10028    }
10029
10030    pub fn pending_rename(&self) -> Option<&RenameState> {
10031        self.pending_rename.as_ref()
10032    }
10033
10034    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10035        let project = match &self.project {
10036            Some(project) => project.clone(),
10037            None => return None,
10038        };
10039
10040        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10041    }
10042
10043    fn format_selections(
10044        &mut self,
10045        _: &FormatSelections,
10046        cx: &mut ViewContext<Self>,
10047    ) -> Option<Task<Result<()>>> {
10048        let project = match &self.project {
10049            Some(project) => project.clone(),
10050            None => return None,
10051        };
10052
10053        let selections = self
10054            .selections
10055            .all_adjusted(cx)
10056            .into_iter()
10057            .filter(|s| !s.is_empty())
10058            .collect_vec();
10059
10060        Some(self.perform_format(
10061            project,
10062            FormatTrigger::Manual,
10063            FormatTarget::Ranges(selections),
10064            cx,
10065        ))
10066    }
10067
10068    fn perform_format(
10069        &mut self,
10070        project: Model<Project>,
10071        trigger: FormatTrigger,
10072        target: FormatTarget,
10073        cx: &mut ViewContext<Self>,
10074    ) -> Task<Result<()>> {
10075        let buffer = self.buffer().clone();
10076        let mut buffers = buffer.read(cx).all_buffers();
10077        if trigger == FormatTrigger::Save {
10078            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10079        }
10080
10081        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10082        let format = project.update(cx, |project, cx| {
10083            project.format(buffers, true, trigger, target, cx)
10084        });
10085
10086        cx.spawn(|_, mut cx| async move {
10087            let transaction = futures::select_biased! {
10088                () = timeout => {
10089                    log::warn!("timed out waiting for formatting");
10090                    None
10091                }
10092                transaction = format.log_err().fuse() => transaction,
10093            };
10094
10095            buffer
10096                .update(&mut cx, |buffer, cx| {
10097                    if let Some(transaction) = transaction {
10098                        if !buffer.is_singleton() {
10099                            buffer.push_transaction(&transaction.0, cx);
10100                        }
10101                    }
10102
10103                    cx.notify();
10104                })
10105                .ok();
10106
10107            Ok(())
10108        })
10109    }
10110
10111    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10112        if let Some(project) = self.project.clone() {
10113            self.buffer.update(cx, |multi_buffer, cx| {
10114                project.update(cx, |project, cx| {
10115                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10116                });
10117            })
10118        }
10119    }
10120
10121    fn cancel_language_server_work(
10122        &mut self,
10123        _: &actions::CancelLanguageServerWork,
10124        cx: &mut ViewContext<Self>,
10125    ) {
10126        if let Some(project) = self.project.clone() {
10127            self.buffer.update(cx, |multi_buffer, cx| {
10128                project.update(cx, |project, cx| {
10129                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10130                });
10131            })
10132        }
10133    }
10134
10135    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10136        cx.show_character_palette();
10137    }
10138
10139    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10140        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10141            let buffer = self.buffer.read(cx).snapshot(cx);
10142            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10143            let is_valid = buffer
10144                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10145                .any(|entry| {
10146                    entry.diagnostic.is_primary
10147                        && !entry.range.is_empty()
10148                        && entry.range.start == primary_range_start
10149                        && entry.diagnostic.message == active_diagnostics.primary_message
10150                });
10151
10152            if is_valid != active_diagnostics.is_valid {
10153                active_diagnostics.is_valid = is_valid;
10154                let mut new_styles = HashMap::default();
10155                for (block_id, diagnostic) in &active_diagnostics.blocks {
10156                    new_styles.insert(
10157                        *block_id,
10158                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10159                    );
10160                }
10161                self.display_map.update(cx, |display_map, _cx| {
10162                    display_map.replace_blocks(new_styles)
10163                });
10164            }
10165        }
10166    }
10167
10168    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10169        self.dismiss_diagnostics(cx);
10170        let snapshot = self.snapshot(cx);
10171        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10172            let buffer = self.buffer.read(cx).snapshot(cx);
10173
10174            let mut primary_range = None;
10175            let mut primary_message = None;
10176            let mut group_end = Point::zero();
10177            let diagnostic_group = buffer
10178                .diagnostic_group::<MultiBufferPoint>(group_id)
10179                .filter_map(|entry| {
10180                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10181                        && (entry.range.start.row == entry.range.end.row
10182                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10183                    {
10184                        return None;
10185                    }
10186                    if entry.range.end > group_end {
10187                        group_end = entry.range.end;
10188                    }
10189                    if entry.diagnostic.is_primary {
10190                        primary_range = Some(entry.range.clone());
10191                        primary_message = Some(entry.diagnostic.message.clone());
10192                    }
10193                    Some(entry)
10194                })
10195                .collect::<Vec<_>>();
10196            let primary_range = primary_range?;
10197            let primary_message = primary_message?;
10198            let primary_range =
10199                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10200
10201            let blocks = display_map
10202                .insert_blocks(
10203                    diagnostic_group.iter().map(|entry| {
10204                        let diagnostic = entry.diagnostic.clone();
10205                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10206                        BlockProperties {
10207                            style: BlockStyle::Fixed,
10208                            placement: BlockPlacement::Below(
10209                                buffer.anchor_after(entry.range.start),
10210                            ),
10211                            height: message_height,
10212                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10213                            priority: 0,
10214                        }
10215                    }),
10216                    cx,
10217                )
10218                .into_iter()
10219                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10220                .collect();
10221
10222            Some(ActiveDiagnosticGroup {
10223                primary_range,
10224                primary_message,
10225                group_id,
10226                blocks,
10227                is_valid: true,
10228            })
10229        });
10230        self.active_diagnostics.is_some()
10231    }
10232
10233    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10234        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10235            self.display_map.update(cx, |display_map, cx| {
10236                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10237            });
10238            cx.notify();
10239        }
10240    }
10241
10242    pub fn set_selections_from_remote(
10243        &mut self,
10244        selections: Vec<Selection<Anchor>>,
10245        pending_selection: Option<Selection<Anchor>>,
10246        cx: &mut ViewContext<Self>,
10247    ) {
10248        let old_cursor_position = self.selections.newest_anchor().head();
10249        self.selections.change_with(cx, |s| {
10250            s.select_anchors(selections);
10251            if let Some(pending_selection) = pending_selection {
10252                s.set_pending(pending_selection, SelectMode::Character);
10253            } else {
10254                s.clear_pending();
10255            }
10256        });
10257        self.selections_did_change(false, &old_cursor_position, true, cx);
10258    }
10259
10260    fn push_to_selection_history(&mut self) {
10261        self.selection_history.push(SelectionHistoryEntry {
10262            selections: self.selections.disjoint_anchors(),
10263            select_next_state: self.select_next_state.clone(),
10264            select_prev_state: self.select_prev_state.clone(),
10265            add_selections_state: self.add_selections_state.clone(),
10266        });
10267    }
10268
10269    pub fn transact(
10270        &mut self,
10271        cx: &mut ViewContext<Self>,
10272        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10273    ) -> Option<TransactionId> {
10274        self.start_transaction_at(Instant::now(), cx);
10275        update(self, cx);
10276        self.end_transaction_at(Instant::now(), cx)
10277    }
10278
10279    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10280        self.end_selection(cx);
10281        if let Some(tx_id) = self
10282            .buffer
10283            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10284        {
10285            self.selection_history
10286                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10287            cx.emit(EditorEvent::TransactionBegun {
10288                transaction_id: tx_id,
10289            })
10290        }
10291    }
10292
10293    fn end_transaction_at(
10294        &mut self,
10295        now: Instant,
10296        cx: &mut ViewContext<Self>,
10297    ) -> Option<TransactionId> {
10298        if let Some(transaction_id) = self
10299            .buffer
10300            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10301        {
10302            if let Some((_, end_selections)) =
10303                self.selection_history.transaction_mut(transaction_id)
10304            {
10305                *end_selections = Some(self.selections.disjoint_anchors());
10306            } else {
10307                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10308            }
10309
10310            cx.emit(EditorEvent::Edited { transaction_id });
10311            Some(transaction_id)
10312        } else {
10313            None
10314        }
10315    }
10316
10317    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10318        if self.is_singleton(cx) {
10319            let selection = self.selections.newest::<Point>(cx);
10320
10321            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10322            let range = if selection.is_empty() {
10323                let point = selection.head().to_display_point(&display_map);
10324                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10325                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10326                    .to_point(&display_map);
10327                start..end
10328            } else {
10329                selection.range()
10330            };
10331            if display_map.folds_in_range(range).next().is_some() {
10332                self.unfold_lines(&Default::default(), cx)
10333            } else {
10334                self.fold(&Default::default(), cx)
10335            }
10336        } else {
10337            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10338            let mut toggled_buffers = HashSet::default();
10339            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10340                self.selections
10341                    .disjoint_anchors()
10342                    .into_iter()
10343                    .map(|selection| selection.range()),
10344            ) {
10345                let buffer_id = buffer_snapshot.remote_id();
10346                if toggled_buffers.insert(buffer_id) {
10347                    if self.buffer_folded(buffer_id, cx) {
10348                        self.unfold_buffer(buffer_id, cx);
10349                    } else {
10350                        self.fold_buffer(buffer_id, cx);
10351                    }
10352                }
10353            }
10354        }
10355    }
10356
10357    pub fn toggle_fold_recursive(
10358        &mut self,
10359        _: &actions::ToggleFoldRecursive,
10360        cx: &mut ViewContext<Self>,
10361    ) {
10362        let selection = self.selections.newest::<Point>(cx);
10363
10364        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10365        let range = if selection.is_empty() {
10366            let point = selection.head().to_display_point(&display_map);
10367            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10368            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10369                .to_point(&display_map);
10370            start..end
10371        } else {
10372            selection.range()
10373        };
10374        if display_map.folds_in_range(range).next().is_some() {
10375            self.unfold_recursive(&Default::default(), cx)
10376        } else {
10377            self.fold_recursive(&Default::default(), cx)
10378        }
10379    }
10380
10381    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10382        if self.is_singleton(cx) {
10383            let mut to_fold = Vec::new();
10384            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10385            let selections = self.selections.all_adjusted(cx);
10386
10387            for selection in selections {
10388                let range = selection.range().sorted();
10389                let buffer_start_row = range.start.row;
10390
10391                if range.start.row != range.end.row {
10392                    let mut found = false;
10393                    let mut row = range.start.row;
10394                    while row <= range.end.row {
10395                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10396                        {
10397                            found = true;
10398                            row = crease.range().end.row + 1;
10399                            to_fold.push(crease);
10400                        } else {
10401                            row += 1
10402                        }
10403                    }
10404                    if found {
10405                        continue;
10406                    }
10407                }
10408
10409                for row in (0..=range.start.row).rev() {
10410                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10411                        if crease.range().end.row >= buffer_start_row {
10412                            to_fold.push(crease);
10413                            if row <= range.start.row {
10414                                break;
10415                            }
10416                        }
10417                    }
10418                }
10419            }
10420
10421            self.fold_creases(to_fold, true, cx);
10422        } else {
10423            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10424            let mut folded_buffers = HashSet::default();
10425            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10426                self.selections
10427                    .disjoint_anchors()
10428                    .into_iter()
10429                    .map(|selection| selection.range()),
10430            ) {
10431                let buffer_id = buffer_snapshot.remote_id();
10432                if folded_buffers.insert(buffer_id) {
10433                    self.fold_buffer(buffer_id, cx);
10434                }
10435            }
10436        }
10437    }
10438
10439    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10440        if !self.buffer.read(cx).is_singleton() {
10441            return;
10442        }
10443
10444        let fold_at_level = fold_at.level;
10445        let snapshot = self.buffer.read(cx).snapshot(cx);
10446        let mut to_fold = Vec::new();
10447        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10448
10449        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10450            while start_row < end_row {
10451                match self
10452                    .snapshot(cx)
10453                    .crease_for_buffer_row(MultiBufferRow(start_row))
10454                {
10455                    Some(crease) => {
10456                        let nested_start_row = crease.range().start.row + 1;
10457                        let nested_end_row = crease.range().end.row;
10458
10459                        if current_level < fold_at_level {
10460                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10461                        } else if current_level == fold_at_level {
10462                            to_fold.push(crease);
10463                        }
10464
10465                        start_row = nested_end_row + 1;
10466                    }
10467                    None => start_row += 1,
10468                }
10469            }
10470        }
10471
10472        self.fold_creases(to_fold, true, cx);
10473    }
10474
10475    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10476        if self.buffer.read(cx).is_singleton() {
10477            let mut fold_ranges = Vec::new();
10478            let snapshot = self.buffer.read(cx).snapshot(cx);
10479
10480            for row in 0..snapshot.max_row().0 {
10481                if let Some(foldable_range) =
10482                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10483                {
10484                    fold_ranges.push(foldable_range);
10485                }
10486            }
10487
10488            self.fold_creases(fold_ranges, true, cx);
10489        } else {
10490            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10491                editor
10492                    .update(&mut cx, |editor, cx| {
10493                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10494                            editor.fold_buffer(buffer_id, cx);
10495                        }
10496                    })
10497                    .ok();
10498            });
10499        }
10500    }
10501
10502    pub fn fold_function_bodies(
10503        &mut self,
10504        _: &actions::FoldFunctionBodies,
10505        cx: &mut ViewContext<Self>,
10506    ) {
10507        let snapshot = self.buffer.read(cx).snapshot(cx);
10508        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10509            return;
10510        };
10511        let creases = buffer
10512            .function_body_fold_ranges(0..buffer.len())
10513            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10514            .collect();
10515
10516        self.fold_creases(creases, true, cx);
10517    }
10518
10519    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10520        let mut to_fold = Vec::new();
10521        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10522        let selections = self.selections.all_adjusted(cx);
10523
10524        for selection in selections {
10525            let range = selection.range().sorted();
10526            let buffer_start_row = range.start.row;
10527
10528            if range.start.row != range.end.row {
10529                let mut found = false;
10530                for row in range.start.row..=range.end.row {
10531                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10532                        found = true;
10533                        to_fold.push(crease);
10534                    }
10535                }
10536                if found {
10537                    continue;
10538                }
10539            }
10540
10541            for row in (0..=range.start.row).rev() {
10542                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10543                    if crease.range().end.row >= buffer_start_row {
10544                        to_fold.push(crease);
10545                    } else {
10546                        break;
10547                    }
10548                }
10549            }
10550        }
10551
10552        self.fold_creases(to_fold, true, cx);
10553    }
10554
10555    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10556        let buffer_row = fold_at.buffer_row;
10557        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10558
10559        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10560            let autoscroll = self
10561                .selections
10562                .all::<Point>(cx)
10563                .iter()
10564                .any(|selection| crease.range().overlaps(&selection.range()));
10565
10566            self.fold_creases(vec![crease], autoscroll, cx);
10567        }
10568    }
10569
10570    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10571        if self.is_singleton(cx) {
10572            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10573            let buffer = &display_map.buffer_snapshot;
10574            let selections = self.selections.all::<Point>(cx);
10575            let ranges = selections
10576                .iter()
10577                .map(|s| {
10578                    let range = s.display_range(&display_map).sorted();
10579                    let mut start = range.start.to_point(&display_map);
10580                    let mut end = range.end.to_point(&display_map);
10581                    start.column = 0;
10582                    end.column = buffer.line_len(MultiBufferRow(end.row));
10583                    start..end
10584                })
10585                .collect::<Vec<_>>();
10586
10587            self.unfold_ranges(&ranges, true, true, cx);
10588        } else {
10589            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10590            let mut unfolded_buffers = HashSet::default();
10591            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10592                self.selections
10593                    .disjoint_anchors()
10594                    .into_iter()
10595                    .map(|selection| selection.range()),
10596            ) {
10597                let buffer_id = buffer_snapshot.remote_id();
10598                if unfolded_buffers.insert(buffer_id) {
10599                    self.unfold_buffer(buffer_id, cx);
10600                }
10601            }
10602        }
10603    }
10604
10605    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10606        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10607        let selections = self.selections.all::<Point>(cx);
10608        let ranges = selections
10609            .iter()
10610            .map(|s| {
10611                let mut range = s.display_range(&display_map).sorted();
10612                *range.start.column_mut() = 0;
10613                *range.end.column_mut() = display_map.line_len(range.end.row());
10614                let start = range.start.to_point(&display_map);
10615                let end = range.end.to_point(&display_map);
10616                start..end
10617            })
10618            .collect::<Vec<_>>();
10619
10620        self.unfold_ranges(&ranges, true, true, cx);
10621    }
10622
10623    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10624        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10625
10626        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10627            ..Point::new(
10628                unfold_at.buffer_row.0,
10629                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10630            );
10631
10632        let autoscroll = self
10633            .selections
10634            .all::<Point>(cx)
10635            .iter()
10636            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10637
10638        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10639    }
10640
10641    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10642        if self.buffer.read(cx).is_singleton() {
10643            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10644            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10645        } else {
10646            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10647                editor
10648                    .update(&mut cx, |editor, cx| {
10649                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10650                            editor.unfold_buffer(buffer_id, cx);
10651                        }
10652                    })
10653                    .ok();
10654            });
10655        }
10656    }
10657
10658    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10659        let selections = self.selections.all::<Point>(cx);
10660        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10661        let line_mode = self.selections.line_mode;
10662        let ranges = selections
10663            .into_iter()
10664            .map(|s| {
10665                if line_mode {
10666                    let start = Point::new(s.start.row, 0);
10667                    let end = Point::new(
10668                        s.end.row,
10669                        display_map
10670                            .buffer_snapshot
10671                            .line_len(MultiBufferRow(s.end.row)),
10672                    );
10673                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10674                } else {
10675                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10676                }
10677            })
10678            .collect::<Vec<_>>();
10679        self.fold_creases(ranges, true, cx);
10680    }
10681
10682    pub fn fold_creases<T: ToOffset + Clone>(
10683        &mut self,
10684        creases: Vec<Crease<T>>,
10685        auto_scroll: bool,
10686        cx: &mut ViewContext<Self>,
10687    ) {
10688        if creases.is_empty() {
10689            return;
10690        }
10691
10692        let mut buffers_affected = HashSet::default();
10693        let multi_buffer = self.buffer().read(cx);
10694        for crease in &creases {
10695            if let Some((_, buffer, _)) =
10696                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10697            {
10698                buffers_affected.insert(buffer.read(cx).remote_id());
10699            };
10700        }
10701
10702        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10703
10704        if auto_scroll {
10705            self.request_autoscroll(Autoscroll::fit(), cx);
10706        }
10707
10708        for buffer_id in buffers_affected {
10709            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10710        }
10711
10712        cx.notify();
10713
10714        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10715            // Clear diagnostics block when folding a range that contains it.
10716            let snapshot = self.snapshot(cx);
10717            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10718                drop(snapshot);
10719                self.active_diagnostics = Some(active_diagnostics);
10720                self.dismiss_diagnostics(cx);
10721            } else {
10722                self.active_diagnostics = Some(active_diagnostics);
10723            }
10724        }
10725
10726        self.scrollbar_marker_state.dirty = true;
10727    }
10728
10729    /// Removes any folds whose ranges intersect any of the given ranges.
10730    pub fn unfold_ranges<T: ToOffset + Clone>(
10731        &mut self,
10732        ranges: &[Range<T>],
10733        inclusive: bool,
10734        auto_scroll: bool,
10735        cx: &mut ViewContext<Self>,
10736    ) {
10737        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10738            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10739        });
10740    }
10741
10742    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10743        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10744            return;
10745        }
10746        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10747            return;
10748        };
10749        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10750        self.display_map
10751            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10752        cx.emit(EditorEvent::BufferFoldToggled {
10753            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10754            folded: true,
10755        });
10756        cx.notify();
10757    }
10758
10759    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10760        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10761            return;
10762        }
10763        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10764            return;
10765        };
10766        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10767        self.display_map.update(cx, |display_map, cx| {
10768            display_map.unfold_buffer(buffer_id, cx);
10769        });
10770        cx.emit(EditorEvent::BufferFoldToggled {
10771            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10772            folded: false,
10773        });
10774        cx.notify();
10775    }
10776
10777    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10778        self.display_map.read(cx).buffer_folded(buffer)
10779    }
10780
10781    /// Removes any folds with the given ranges.
10782    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10783        &mut self,
10784        ranges: &[Range<T>],
10785        type_id: TypeId,
10786        auto_scroll: bool,
10787        cx: &mut ViewContext<Self>,
10788    ) {
10789        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10790            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10791        });
10792    }
10793
10794    fn remove_folds_with<T: ToOffset + Clone>(
10795        &mut self,
10796        ranges: &[Range<T>],
10797        auto_scroll: bool,
10798        cx: &mut ViewContext<Self>,
10799        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10800    ) {
10801        if ranges.is_empty() {
10802            return;
10803        }
10804
10805        let mut buffers_affected = HashSet::default();
10806        let multi_buffer = self.buffer().read(cx);
10807        for range in ranges {
10808            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10809                buffers_affected.insert(buffer.read(cx).remote_id());
10810            };
10811        }
10812
10813        self.display_map.update(cx, update);
10814
10815        if auto_scroll {
10816            self.request_autoscroll(Autoscroll::fit(), cx);
10817        }
10818
10819        for buffer_id in buffers_affected {
10820            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10821        }
10822
10823        cx.notify();
10824        self.scrollbar_marker_state.dirty = true;
10825        self.active_indent_guides_state.dirty = true;
10826    }
10827
10828    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10829        self.display_map.read(cx).fold_placeholder.clone()
10830    }
10831
10832    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10833        if hovered != self.gutter_hovered {
10834            self.gutter_hovered = hovered;
10835            cx.notify();
10836        }
10837    }
10838
10839    pub fn insert_blocks(
10840        &mut self,
10841        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10842        autoscroll: Option<Autoscroll>,
10843        cx: &mut ViewContext<Self>,
10844    ) -> Vec<CustomBlockId> {
10845        let blocks = self
10846            .display_map
10847            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10848        if let Some(autoscroll) = autoscroll {
10849            self.request_autoscroll(autoscroll, cx);
10850        }
10851        cx.notify();
10852        blocks
10853    }
10854
10855    pub fn resize_blocks(
10856        &mut self,
10857        heights: HashMap<CustomBlockId, u32>,
10858        autoscroll: Option<Autoscroll>,
10859        cx: &mut ViewContext<Self>,
10860    ) {
10861        self.display_map
10862            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10863        if let Some(autoscroll) = autoscroll {
10864            self.request_autoscroll(autoscroll, cx);
10865        }
10866        cx.notify();
10867    }
10868
10869    pub fn replace_blocks(
10870        &mut self,
10871        renderers: HashMap<CustomBlockId, RenderBlock>,
10872        autoscroll: Option<Autoscroll>,
10873        cx: &mut ViewContext<Self>,
10874    ) {
10875        self.display_map
10876            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10877        if let Some(autoscroll) = autoscroll {
10878            self.request_autoscroll(autoscroll, cx);
10879        }
10880        cx.notify();
10881    }
10882
10883    pub fn remove_blocks(
10884        &mut self,
10885        block_ids: HashSet<CustomBlockId>,
10886        autoscroll: Option<Autoscroll>,
10887        cx: &mut ViewContext<Self>,
10888    ) {
10889        self.display_map.update(cx, |display_map, cx| {
10890            display_map.remove_blocks(block_ids, cx)
10891        });
10892        if let Some(autoscroll) = autoscroll {
10893            self.request_autoscroll(autoscroll, cx);
10894        }
10895        cx.notify();
10896    }
10897
10898    pub fn row_for_block(
10899        &self,
10900        block_id: CustomBlockId,
10901        cx: &mut ViewContext<Self>,
10902    ) -> Option<DisplayRow> {
10903        self.display_map
10904            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10905    }
10906
10907    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10908        self.focused_block = Some(focused_block);
10909    }
10910
10911    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10912        self.focused_block.take()
10913    }
10914
10915    pub fn insert_creases(
10916        &mut self,
10917        creases: impl IntoIterator<Item = Crease<Anchor>>,
10918        cx: &mut ViewContext<Self>,
10919    ) -> Vec<CreaseId> {
10920        self.display_map
10921            .update(cx, |map, cx| map.insert_creases(creases, cx))
10922    }
10923
10924    pub fn remove_creases(
10925        &mut self,
10926        ids: impl IntoIterator<Item = CreaseId>,
10927        cx: &mut ViewContext<Self>,
10928    ) {
10929        self.display_map
10930            .update(cx, |map, cx| map.remove_creases(ids, cx));
10931    }
10932
10933    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10934        self.display_map
10935            .update(cx, |map, cx| map.snapshot(cx))
10936            .longest_row()
10937    }
10938
10939    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10940        self.display_map
10941            .update(cx, |map, cx| map.snapshot(cx))
10942            .max_point()
10943    }
10944
10945    pub fn text(&self, cx: &AppContext) -> String {
10946        self.buffer.read(cx).read(cx).text()
10947    }
10948
10949    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10950        let text = self.text(cx);
10951        let text = text.trim();
10952
10953        if text.is_empty() {
10954            return None;
10955        }
10956
10957        Some(text.to_string())
10958    }
10959
10960    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10961        self.transact(cx, |this, cx| {
10962            this.buffer
10963                .read(cx)
10964                .as_singleton()
10965                .expect("you can only call set_text on editors for singleton buffers")
10966                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10967        });
10968    }
10969
10970    pub fn display_text(&self, cx: &mut AppContext) -> String {
10971        self.display_map
10972            .update(cx, |map, cx| map.snapshot(cx))
10973            .text()
10974    }
10975
10976    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10977        let mut wrap_guides = smallvec::smallvec![];
10978
10979        if self.show_wrap_guides == Some(false) {
10980            return wrap_guides;
10981        }
10982
10983        let settings = self.buffer.read(cx).settings_at(0, cx);
10984        if settings.show_wrap_guides {
10985            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10986                wrap_guides.push((soft_wrap as usize, true));
10987            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10988                wrap_guides.push((soft_wrap as usize, true));
10989            }
10990            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10991        }
10992
10993        wrap_guides
10994    }
10995
10996    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10997        let settings = self.buffer.read(cx).settings_at(0, cx);
10998        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10999        match mode {
11000            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11001                SoftWrap::None
11002            }
11003            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11004            language_settings::SoftWrap::PreferredLineLength => {
11005                SoftWrap::Column(settings.preferred_line_length)
11006            }
11007            language_settings::SoftWrap::Bounded => {
11008                SoftWrap::Bounded(settings.preferred_line_length)
11009            }
11010        }
11011    }
11012
11013    pub fn set_soft_wrap_mode(
11014        &mut self,
11015        mode: language_settings::SoftWrap,
11016        cx: &mut ViewContext<Self>,
11017    ) {
11018        self.soft_wrap_mode_override = Some(mode);
11019        cx.notify();
11020    }
11021
11022    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11023        self.text_style_refinement = Some(style);
11024    }
11025
11026    /// called by the Element so we know what style we were most recently rendered with.
11027    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11028        let rem_size = cx.rem_size();
11029        self.display_map.update(cx, |map, cx| {
11030            map.set_font(
11031                style.text.font(),
11032                style.text.font_size.to_pixels(rem_size),
11033                cx,
11034            )
11035        });
11036        self.style = Some(style);
11037    }
11038
11039    pub fn style(&self) -> Option<&EditorStyle> {
11040        self.style.as_ref()
11041    }
11042
11043    // Called by the element. This method is not designed to be called outside of the editor
11044    // element's layout code because it does not notify when rewrapping is computed synchronously.
11045    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11046        self.display_map
11047            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11048    }
11049
11050    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11051        if self.soft_wrap_mode_override.is_some() {
11052            self.soft_wrap_mode_override.take();
11053        } else {
11054            let soft_wrap = match self.soft_wrap_mode(cx) {
11055                SoftWrap::GitDiff => return,
11056                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11057                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11058                    language_settings::SoftWrap::None
11059                }
11060            };
11061            self.soft_wrap_mode_override = Some(soft_wrap);
11062        }
11063        cx.notify();
11064    }
11065
11066    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11067        let Some(workspace) = self.workspace() else {
11068            return;
11069        };
11070        let fs = workspace.read(cx).app_state().fs.clone();
11071        let current_show = TabBarSettings::get_global(cx).show;
11072        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11073            setting.show = Some(!current_show);
11074        });
11075    }
11076
11077    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11078        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11079            self.buffer
11080                .read(cx)
11081                .settings_at(0, cx)
11082                .indent_guides
11083                .enabled
11084        });
11085        self.show_indent_guides = Some(!currently_enabled);
11086        cx.notify();
11087    }
11088
11089    fn should_show_indent_guides(&self) -> Option<bool> {
11090        self.show_indent_guides
11091    }
11092
11093    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11094        let mut editor_settings = EditorSettings::get_global(cx).clone();
11095        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11096        EditorSettings::override_global(editor_settings, cx);
11097    }
11098
11099    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11100        self.use_relative_line_numbers
11101            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11102    }
11103
11104    pub fn toggle_relative_line_numbers(
11105        &mut self,
11106        _: &ToggleRelativeLineNumbers,
11107        cx: &mut ViewContext<Self>,
11108    ) {
11109        let is_relative = self.should_use_relative_line_numbers(cx);
11110        self.set_relative_line_number(Some(!is_relative), cx)
11111    }
11112
11113    pub fn set_relative_line_number(
11114        &mut self,
11115        is_relative: Option<bool>,
11116        cx: &mut ViewContext<Self>,
11117    ) {
11118        self.use_relative_line_numbers = is_relative;
11119        cx.notify();
11120    }
11121
11122    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11123        self.show_gutter = show_gutter;
11124        cx.notify();
11125    }
11126
11127    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11128        self.show_line_numbers = Some(show_line_numbers);
11129        cx.notify();
11130    }
11131
11132    pub fn set_show_git_diff_gutter(
11133        &mut self,
11134        show_git_diff_gutter: bool,
11135        cx: &mut ViewContext<Self>,
11136    ) {
11137        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11138        cx.notify();
11139    }
11140
11141    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11142        self.show_code_actions = Some(show_code_actions);
11143        cx.notify();
11144    }
11145
11146    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11147        self.show_runnables = Some(show_runnables);
11148        cx.notify();
11149    }
11150
11151    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11152        if self.display_map.read(cx).masked != masked {
11153            self.display_map.update(cx, |map, _| map.masked = masked);
11154        }
11155        cx.notify()
11156    }
11157
11158    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11159        self.show_wrap_guides = Some(show_wrap_guides);
11160        cx.notify();
11161    }
11162
11163    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11164        self.show_indent_guides = Some(show_indent_guides);
11165        cx.notify();
11166    }
11167
11168    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11169        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11170            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11171                if let Some(dir) = file.abs_path(cx).parent() {
11172                    return Some(dir.to_owned());
11173                }
11174            }
11175
11176            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11177                return Some(project_path.path.to_path_buf());
11178            }
11179        }
11180
11181        None
11182    }
11183
11184    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11185        self.active_excerpt(cx)?
11186            .1
11187            .read(cx)
11188            .file()
11189            .and_then(|f| f.as_local())
11190    }
11191
11192    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11193        if let Some(target) = self.target_file(cx) {
11194            cx.reveal_path(&target.abs_path(cx));
11195        }
11196    }
11197
11198    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11199        if let Some(file) = self.target_file(cx) {
11200            if let Some(path) = file.abs_path(cx).to_str() {
11201                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11202            }
11203        }
11204    }
11205
11206    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11207        if let Some(file) = self.target_file(cx) {
11208            if let Some(path) = file.path().to_str() {
11209                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11210            }
11211        }
11212    }
11213
11214    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11215        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11216
11217        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11218            self.start_git_blame(true, cx);
11219        }
11220
11221        cx.notify();
11222    }
11223
11224    pub fn toggle_git_blame_inline(
11225        &mut self,
11226        _: &ToggleGitBlameInline,
11227        cx: &mut ViewContext<Self>,
11228    ) {
11229        self.toggle_git_blame_inline_internal(true, cx);
11230        cx.notify();
11231    }
11232
11233    pub fn git_blame_inline_enabled(&self) -> bool {
11234        self.git_blame_inline_enabled
11235    }
11236
11237    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11238        self.show_selection_menu = self
11239            .show_selection_menu
11240            .map(|show_selections_menu| !show_selections_menu)
11241            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11242
11243        cx.notify();
11244    }
11245
11246    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11247        self.show_selection_menu
11248            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11249    }
11250
11251    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11252        if let Some(project) = self.project.as_ref() {
11253            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11254                return;
11255            };
11256
11257            if buffer.read(cx).file().is_none() {
11258                return;
11259            }
11260
11261            let focused = self.focus_handle(cx).contains_focused(cx);
11262
11263            let project = project.clone();
11264            let blame =
11265                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11266            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11267            self.blame = Some(blame);
11268        }
11269    }
11270
11271    fn toggle_git_blame_inline_internal(
11272        &mut self,
11273        user_triggered: bool,
11274        cx: &mut ViewContext<Self>,
11275    ) {
11276        if self.git_blame_inline_enabled {
11277            self.git_blame_inline_enabled = false;
11278            self.show_git_blame_inline = false;
11279            self.show_git_blame_inline_delay_task.take();
11280        } else {
11281            self.git_blame_inline_enabled = true;
11282            self.start_git_blame_inline(user_triggered, cx);
11283        }
11284
11285        cx.notify();
11286    }
11287
11288    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11289        self.start_git_blame(user_triggered, cx);
11290
11291        if ProjectSettings::get_global(cx)
11292            .git
11293            .inline_blame_delay()
11294            .is_some()
11295        {
11296            self.start_inline_blame_timer(cx);
11297        } else {
11298            self.show_git_blame_inline = true
11299        }
11300    }
11301
11302    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11303        self.blame.as_ref()
11304    }
11305
11306    pub fn show_git_blame_gutter(&self) -> bool {
11307        self.show_git_blame_gutter
11308    }
11309
11310    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11311        self.show_git_blame_gutter && self.has_blame_entries(cx)
11312    }
11313
11314    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11315        self.show_git_blame_inline
11316            && self.focus_handle.is_focused(cx)
11317            && !self.newest_selection_head_on_empty_line(cx)
11318            && self.has_blame_entries(cx)
11319    }
11320
11321    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11322        self.blame()
11323            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11324    }
11325
11326    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11327        let cursor_anchor = self.selections.newest_anchor().head();
11328
11329        let snapshot = self.buffer.read(cx).snapshot(cx);
11330        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11331
11332        snapshot.line_len(buffer_row) == 0
11333    }
11334
11335    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11336        let buffer_and_selection = maybe!({
11337            let selection = self.selections.newest::<Point>(cx);
11338            let selection_range = selection.range();
11339
11340            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11341                (buffer, selection_range.start.row..selection_range.end.row)
11342            } else {
11343                let buffer_ranges = self
11344                    .buffer()
11345                    .read(cx)
11346                    .range_to_buffer_ranges(selection_range, cx);
11347
11348                let (buffer, range, _) = if selection.reversed {
11349                    buffer_ranges.first()
11350                } else {
11351                    buffer_ranges.last()
11352                }?;
11353
11354                let snapshot = buffer.read(cx).snapshot();
11355                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11356                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11357                (buffer.clone(), selection)
11358            };
11359
11360            Some((buffer, selection))
11361        });
11362
11363        let Some((buffer, selection)) = buffer_and_selection else {
11364            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11365        };
11366
11367        let Some(project) = self.project.as_ref() else {
11368            return Task::ready(Err(anyhow!("editor does not have project")));
11369        };
11370
11371        project.update(cx, |project, cx| {
11372            project.get_permalink_to_line(&buffer, selection, cx)
11373        })
11374    }
11375
11376    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11377        let permalink_task = self.get_permalink_to_line(cx);
11378        let workspace = self.workspace();
11379
11380        cx.spawn(|_, mut cx| async move {
11381            match permalink_task.await {
11382                Ok(permalink) => {
11383                    cx.update(|cx| {
11384                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11385                    })
11386                    .ok();
11387                }
11388                Err(err) => {
11389                    let message = format!("Failed to copy permalink: {err}");
11390
11391                    Err::<(), anyhow::Error>(err).log_err();
11392
11393                    if let Some(workspace) = workspace {
11394                        workspace
11395                            .update(&mut cx, |workspace, cx| {
11396                                struct CopyPermalinkToLine;
11397
11398                                workspace.show_toast(
11399                                    Toast::new(
11400                                        NotificationId::unique::<CopyPermalinkToLine>(),
11401                                        message,
11402                                    ),
11403                                    cx,
11404                                )
11405                            })
11406                            .ok();
11407                    }
11408                }
11409            }
11410        })
11411        .detach();
11412    }
11413
11414    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11415        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11416        if let Some(file) = self.target_file(cx) {
11417            if let Some(path) = file.path().to_str() {
11418                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11419            }
11420        }
11421    }
11422
11423    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11424        let permalink_task = self.get_permalink_to_line(cx);
11425        let workspace = self.workspace();
11426
11427        cx.spawn(|_, mut cx| async move {
11428            match permalink_task.await {
11429                Ok(permalink) => {
11430                    cx.update(|cx| {
11431                        cx.open_url(permalink.as_ref());
11432                    })
11433                    .ok();
11434                }
11435                Err(err) => {
11436                    let message = format!("Failed to open permalink: {err}");
11437
11438                    Err::<(), anyhow::Error>(err).log_err();
11439
11440                    if let Some(workspace) = workspace {
11441                        workspace
11442                            .update(&mut cx, |workspace, cx| {
11443                                struct OpenPermalinkToLine;
11444
11445                                workspace.show_toast(
11446                                    Toast::new(
11447                                        NotificationId::unique::<OpenPermalinkToLine>(),
11448                                        message,
11449                                    ),
11450                                    cx,
11451                                )
11452                            })
11453                            .ok();
11454                    }
11455                }
11456            }
11457        })
11458        .detach();
11459    }
11460
11461    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11462        self.insert_uuid(UuidVersion::V4, cx);
11463    }
11464
11465    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11466        self.insert_uuid(UuidVersion::V7, cx);
11467    }
11468
11469    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11470        self.transact(cx, |this, cx| {
11471            let edits = this
11472                .selections
11473                .all::<Point>(cx)
11474                .into_iter()
11475                .map(|selection| {
11476                    let uuid = match version {
11477                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11478                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11479                    };
11480
11481                    (selection.range(), uuid.to_string())
11482                });
11483            this.edit(edits, cx);
11484            this.refresh_inline_completion(true, false, cx);
11485        });
11486    }
11487
11488    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11489    /// last highlight added will be used.
11490    ///
11491    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11492    pub fn highlight_rows<T: 'static>(
11493        &mut self,
11494        range: Range<Anchor>,
11495        color: Hsla,
11496        should_autoscroll: bool,
11497        cx: &mut ViewContext<Self>,
11498    ) {
11499        let snapshot = self.buffer().read(cx).snapshot(cx);
11500        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11501        let ix = row_highlights.binary_search_by(|highlight| {
11502            Ordering::Equal
11503                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11504                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11505        });
11506
11507        if let Err(mut ix) = ix {
11508            let index = post_inc(&mut self.highlight_order);
11509
11510            // If this range intersects with the preceding highlight, then merge it with
11511            // the preceding highlight. Otherwise insert a new highlight.
11512            let mut merged = false;
11513            if ix > 0 {
11514                let prev_highlight = &mut row_highlights[ix - 1];
11515                if prev_highlight
11516                    .range
11517                    .end
11518                    .cmp(&range.start, &snapshot)
11519                    .is_ge()
11520                {
11521                    ix -= 1;
11522                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11523                        prev_highlight.range.end = range.end;
11524                    }
11525                    merged = true;
11526                    prev_highlight.index = index;
11527                    prev_highlight.color = color;
11528                    prev_highlight.should_autoscroll = should_autoscroll;
11529                }
11530            }
11531
11532            if !merged {
11533                row_highlights.insert(
11534                    ix,
11535                    RowHighlight {
11536                        range: range.clone(),
11537                        index,
11538                        color,
11539                        should_autoscroll,
11540                    },
11541                );
11542            }
11543
11544            // If any of the following highlights intersect with this one, merge them.
11545            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11546                let highlight = &row_highlights[ix];
11547                if next_highlight
11548                    .range
11549                    .start
11550                    .cmp(&highlight.range.end, &snapshot)
11551                    .is_le()
11552                {
11553                    if next_highlight
11554                        .range
11555                        .end
11556                        .cmp(&highlight.range.end, &snapshot)
11557                        .is_gt()
11558                    {
11559                        row_highlights[ix].range.end = next_highlight.range.end;
11560                    }
11561                    row_highlights.remove(ix + 1);
11562                } else {
11563                    break;
11564                }
11565            }
11566        }
11567    }
11568
11569    /// Remove any highlighted row ranges of the given type that intersect the
11570    /// given ranges.
11571    pub fn remove_highlighted_rows<T: 'static>(
11572        &mut self,
11573        ranges_to_remove: Vec<Range<Anchor>>,
11574        cx: &mut ViewContext<Self>,
11575    ) {
11576        let snapshot = self.buffer().read(cx).snapshot(cx);
11577        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11578        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11579        row_highlights.retain(|highlight| {
11580            while let Some(range_to_remove) = ranges_to_remove.peek() {
11581                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11582                    Ordering::Less | Ordering::Equal => {
11583                        ranges_to_remove.next();
11584                    }
11585                    Ordering::Greater => {
11586                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11587                            Ordering::Less | Ordering::Equal => {
11588                                return false;
11589                            }
11590                            Ordering::Greater => break,
11591                        }
11592                    }
11593                }
11594            }
11595
11596            true
11597        })
11598    }
11599
11600    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11601    pub fn clear_row_highlights<T: 'static>(&mut self) {
11602        self.highlighted_rows.remove(&TypeId::of::<T>());
11603    }
11604
11605    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11606    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11607        self.highlighted_rows
11608            .get(&TypeId::of::<T>())
11609            .map_or(&[] as &[_], |vec| vec.as_slice())
11610            .iter()
11611            .map(|highlight| (highlight.range.clone(), highlight.color))
11612    }
11613
11614    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11615    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11616    /// Allows to ignore certain kinds of highlights.
11617    pub fn highlighted_display_rows(
11618        &mut self,
11619        cx: &mut WindowContext,
11620    ) -> BTreeMap<DisplayRow, Hsla> {
11621        let snapshot = self.snapshot(cx);
11622        let mut used_highlight_orders = HashMap::default();
11623        self.highlighted_rows
11624            .iter()
11625            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11626            .fold(
11627                BTreeMap::<DisplayRow, Hsla>::new(),
11628                |mut unique_rows, highlight| {
11629                    let start = highlight.range.start.to_display_point(&snapshot);
11630                    let end = highlight.range.end.to_display_point(&snapshot);
11631                    let start_row = start.row().0;
11632                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11633                        && end.column() == 0
11634                    {
11635                        end.row().0.saturating_sub(1)
11636                    } else {
11637                        end.row().0
11638                    };
11639                    for row in start_row..=end_row {
11640                        let used_index =
11641                            used_highlight_orders.entry(row).or_insert(highlight.index);
11642                        if highlight.index >= *used_index {
11643                            *used_index = highlight.index;
11644                            unique_rows.insert(DisplayRow(row), highlight.color);
11645                        }
11646                    }
11647                    unique_rows
11648                },
11649            )
11650    }
11651
11652    pub fn highlighted_display_row_for_autoscroll(
11653        &self,
11654        snapshot: &DisplaySnapshot,
11655    ) -> Option<DisplayRow> {
11656        self.highlighted_rows
11657            .values()
11658            .flat_map(|highlighted_rows| highlighted_rows.iter())
11659            .filter_map(|highlight| {
11660                if highlight.should_autoscroll {
11661                    Some(highlight.range.start.to_display_point(snapshot).row())
11662                } else {
11663                    None
11664                }
11665            })
11666            .min()
11667    }
11668
11669    pub fn set_search_within_ranges(
11670        &mut self,
11671        ranges: &[Range<Anchor>],
11672        cx: &mut ViewContext<Self>,
11673    ) {
11674        self.highlight_background::<SearchWithinRange>(
11675            ranges,
11676            |colors| colors.editor_document_highlight_read_background,
11677            cx,
11678        )
11679    }
11680
11681    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11682        self.breadcrumb_header = Some(new_header);
11683    }
11684
11685    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11686        self.clear_background_highlights::<SearchWithinRange>(cx);
11687    }
11688
11689    pub fn highlight_background<T: 'static>(
11690        &mut self,
11691        ranges: &[Range<Anchor>],
11692        color_fetcher: fn(&ThemeColors) -> Hsla,
11693        cx: &mut ViewContext<Self>,
11694    ) {
11695        self.background_highlights
11696            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11697        self.scrollbar_marker_state.dirty = true;
11698        cx.notify();
11699    }
11700
11701    pub fn clear_background_highlights<T: 'static>(
11702        &mut self,
11703        cx: &mut ViewContext<Self>,
11704    ) -> Option<BackgroundHighlight> {
11705        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11706        if !text_highlights.1.is_empty() {
11707            self.scrollbar_marker_state.dirty = true;
11708            cx.notify();
11709        }
11710        Some(text_highlights)
11711    }
11712
11713    pub fn highlight_gutter<T: 'static>(
11714        &mut self,
11715        ranges: &[Range<Anchor>],
11716        color_fetcher: fn(&AppContext) -> Hsla,
11717        cx: &mut ViewContext<Self>,
11718    ) {
11719        self.gutter_highlights
11720            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11721        cx.notify();
11722    }
11723
11724    pub fn clear_gutter_highlights<T: 'static>(
11725        &mut self,
11726        cx: &mut ViewContext<Self>,
11727    ) -> Option<GutterHighlight> {
11728        cx.notify();
11729        self.gutter_highlights.remove(&TypeId::of::<T>())
11730    }
11731
11732    #[cfg(feature = "test-support")]
11733    pub fn all_text_background_highlights(
11734        &mut self,
11735        cx: &mut ViewContext<Self>,
11736    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11737        let snapshot = self.snapshot(cx);
11738        let buffer = &snapshot.buffer_snapshot;
11739        let start = buffer.anchor_before(0);
11740        let end = buffer.anchor_after(buffer.len());
11741        let theme = cx.theme().colors();
11742        self.background_highlights_in_range(start..end, &snapshot, theme)
11743    }
11744
11745    #[cfg(feature = "test-support")]
11746    pub fn search_background_highlights(
11747        &mut self,
11748        cx: &mut ViewContext<Self>,
11749    ) -> Vec<Range<Point>> {
11750        let snapshot = self.buffer().read(cx).snapshot(cx);
11751
11752        let highlights = self
11753            .background_highlights
11754            .get(&TypeId::of::<items::BufferSearchHighlights>());
11755
11756        if let Some((_color, ranges)) = highlights {
11757            ranges
11758                .iter()
11759                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11760                .collect_vec()
11761        } else {
11762            vec![]
11763        }
11764    }
11765
11766    fn document_highlights_for_position<'a>(
11767        &'a self,
11768        position: Anchor,
11769        buffer: &'a MultiBufferSnapshot,
11770    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11771        let read_highlights = self
11772            .background_highlights
11773            .get(&TypeId::of::<DocumentHighlightRead>())
11774            .map(|h| &h.1);
11775        let write_highlights = self
11776            .background_highlights
11777            .get(&TypeId::of::<DocumentHighlightWrite>())
11778            .map(|h| &h.1);
11779        let left_position = position.bias_left(buffer);
11780        let right_position = position.bias_right(buffer);
11781        read_highlights
11782            .into_iter()
11783            .chain(write_highlights)
11784            .flat_map(move |ranges| {
11785                let start_ix = match ranges.binary_search_by(|probe| {
11786                    let cmp = probe.end.cmp(&left_position, buffer);
11787                    if cmp.is_ge() {
11788                        Ordering::Greater
11789                    } else {
11790                        Ordering::Less
11791                    }
11792                }) {
11793                    Ok(i) | Err(i) => i,
11794                };
11795
11796                ranges[start_ix..]
11797                    .iter()
11798                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11799            })
11800    }
11801
11802    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11803        self.background_highlights
11804            .get(&TypeId::of::<T>())
11805            .map_or(false, |(_, highlights)| !highlights.is_empty())
11806    }
11807
11808    pub fn background_highlights_in_range(
11809        &self,
11810        search_range: Range<Anchor>,
11811        display_snapshot: &DisplaySnapshot,
11812        theme: &ThemeColors,
11813    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11814        let mut results = Vec::new();
11815        for (color_fetcher, ranges) in self.background_highlights.values() {
11816            let color = color_fetcher(theme);
11817            let start_ix = match ranges.binary_search_by(|probe| {
11818                let cmp = probe
11819                    .end
11820                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11821                if cmp.is_gt() {
11822                    Ordering::Greater
11823                } else {
11824                    Ordering::Less
11825                }
11826            }) {
11827                Ok(i) | Err(i) => i,
11828            };
11829            for range in &ranges[start_ix..] {
11830                if range
11831                    .start
11832                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11833                    .is_ge()
11834                {
11835                    break;
11836                }
11837
11838                let start = range.start.to_display_point(display_snapshot);
11839                let end = range.end.to_display_point(display_snapshot);
11840                results.push((start..end, color))
11841            }
11842        }
11843        results
11844    }
11845
11846    pub fn background_highlight_row_ranges<T: 'static>(
11847        &self,
11848        search_range: Range<Anchor>,
11849        display_snapshot: &DisplaySnapshot,
11850        count: usize,
11851    ) -> Vec<RangeInclusive<DisplayPoint>> {
11852        let mut results = Vec::new();
11853        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11854            return vec![];
11855        };
11856
11857        let start_ix = match ranges.binary_search_by(|probe| {
11858            let cmp = probe
11859                .end
11860                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11861            if cmp.is_gt() {
11862                Ordering::Greater
11863            } else {
11864                Ordering::Less
11865            }
11866        }) {
11867            Ok(i) | Err(i) => i,
11868        };
11869        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11870            if let (Some(start_display), Some(end_display)) = (start, end) {
11871                results.push(
11872                    start_display.to_display_point(display_snapshot)
11873                        ..=end_display.to_display_point(display_snapshot),
11874                );
11875            }
11876        };
11877        let mut start_row: Option<Point> = None;
11878        let mut end_row: Option<Point> = None;
11879        if ranges.len() > count {
11880            return Vec::new();
11881        }
11882        for range in &ranges[start_ix..] {
11883            if range
11884                .start
11885                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11886                .is_ge()
11887            {
11888                break;
11889            }
11890            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11891            if let Some(current_row) = &end_row {
11892                if end.row == current_row.row {
11893                    continue;
11894                }
11895            }
11896            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11897            if start_row.is_none() {
11898                assert_eq!(end_row, None);
11899                start_row = Some(start);
11900                end_row = Some(end);
11901                continue;
11902            }
11903            if let Some(current_end) = end_row.as_mut() {
11904                if start.row > current_end.row + 1 {
11905                    push_region(start_row, end_row);
11906                    start_row = Some(start);
11907                    end_row = Some(end);
11908                } else {
11909                    // Merge two hunks.
11910                    *current_end = end;
11911                }
11912            } else {
11913                unreachable!();
11914            }
11915        }
11916        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11917        push_region(start_row, end_row);
11918        results
11919    }
11920
11921    pub fn gutter_highlights_in_range(
11922        &self,
11923        search_range: Range<Anchor>,
11924        display_snapshot: &DisplaySnapshot,
11925        cx: &AppContext,
11926    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11927        let mut results = Vec::new();
11928        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11929            let color = color_fetcher(cx);
11930            let start_ix = match ranges.binary_search_by(|probe| {
11931                let cmp = probe
11932                    .end
11933                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11934                if cmp.is_gt() {
11935                    Ordering::Greater
11936                } else {
11937                    Ordering::Less
11938                }
11939            }) {
11940                Ok(i) | Err(i) => i,
11941            };
11942            for range in &ranges[start_ix..] {
11943                if range
11944                    .start
11945                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11946                    .is_ge()
11947                {
11948                    break;
11949                }
11950
11951                let start = range.start.to_display_point(display_snapshot);
11952                let end = range.end.to_display_point(display_snapshot);
11953                results.push((start..end, color))
11954            }
11955        }
11956        results
11957    }
11958
11959    /// Get the text ranges corresponding to the redaction query
11960    pub fn redacted_ranges(
11961        &self,
11962        search_range: Range<Anchor>,
11963        display_snapshot: &DisplaySnapshot,
11964        cx: &WindowContext,
11965    ) -> Vec<Range<DisplayPoint>> {
11966        display_snapshot
11967            .buffer_snapshot
11968            .redacted_ranges(search_range, |file| {
11969                if let Some(file) = file {
11970                    file.is_private()
11971                        && EditorSettings::get(
11972                            Some(SettingsLocation {
11973                                worktree_id: file.worktree_id(cx),
11974                                path: file.path().as_ref(),
11975                            }),
11976                            cx,
11977                        )
11978                        .redact_private_values
11979                } else {
11980                    false
11981                }
11982            })
11983            .map(|range| {
11984                range.start.to_display_point(display_snapshot)
11985                    ..range.end.to_display_point(display_snapshot)
11986            })
11987            .collect()
11988    }
11989
11990    pub fn highlight_text<T: 'static>(
11991        &mut self,
11992        ranges: Vec<Range<Anchor>>,
11993        style: HighlightStyle,
11994        cx: &mut ViewContext<Self>,
11995    ) {
11996        self.display_map.update(cx, |map, _| {
11997            map.highlight_text(TypeId::of::<T>(), ranges, style)
11998        });
11999        cx.notify();
12000    }
12001
12002    pub(crate) fn highlight_inlays<T: 'static>(
12003        &mut self,
12004        highlights: Vec<InlayHighlight>,
12005        style: HighlightStyle,
12006        cx: &mut ViewContext<Self>,
12007    ) {
12008        self.display_map.update(cx, |map, _| {
12009            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12010        });
12011        cx.notify();
12012    }
12013
12014    pub fn text_highlights<'a, T: 'static>(
12015        &'a self,
12016        cx: &'a AppContext,
12017    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12018        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12019    }
12020
12021    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12022        let cleared = self
12023            .display_map
12024            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12025        if cleared {
12026            cx.notify();
12027        }
12028    }
12029
12030    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12031        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12032            && self.focus_handle.is_focused(cx)
12033    }
12034
12035    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12036        self.show_cursor_when_unfocused = is_enabled;
12037        cx.notify();
12038    }
12039
12040    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12041        self.project
12042            .as_ref()
12043            .map(|project| project.read(cx).lsp_store())
12044    }
12045
12046    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12047        cx.notify();
12048    }
12049
12050    fn on_buffer_event(
12051        &mut self,
12052        multibuffer: Model<MultiBuffer>,
12053        event: &multi_buffer::Event,
12054        cx: &mut ViewContext<Self>,
12055    ) {
12056        match event {
12057            multi_buffer::Event::Edited {
12058                singleton_buffer_edited,
12059                edited_buffer: buffer_edited,
12060            } => {
12061                self.scrollbar_marker_state.dirty = true;
12062                self.active_indent_guides_state.dirty = true;
12063                self.refresh_active_diagnostics(cx);
12064                self.refresh_code_actions(cx);
12065                if self.has_active_inline_completion() {
12066                    self.update_visible_inline_completion(cx);
12067                }
12068                if let Some(buffer) = buffer_edited {
12069                    let buffer_id = buffer.read(cx).remote_id();
12070                    if !self.registered_buffers.contains_key(&buffer_id) {
12071                        if let Some(lsp_store) = self.lsp_store(cx) {
12072                            lsp_store.update(cx, |lsp_store, cx| {
12073                                self.registered_buffers.insert(
12074                                    buffer_id,
12075                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12076                                );
12077                            })
12078                        }
12079                    }
12080                }
12081                cx.emit(EditorEvent::BufferEdited);
12082                cx.emit(SearchEvent::MatchesInvalidated);
12083                if *singleton_buffer_edited {
12084                    if let Some(project) = &self.project {
12085                        let project = project.read(cx);
12086                        #[allow(clippy::mutable_key_type)]
12087                        let languages_affected = multibuffer
12088                            .read(cx)
12089                            .all_buffers()
12090                            .into_iter()
12091                            .filter_map(|buffer| {
12092                                let buffer = buffer.read(cx);
12093                                let language = buffer.language()?;
12094                                if project.is_local()
12095                                    && project
12096                                        .language_servers_for_local_buffer(buffer, cx)
12097                                        .count()
12098                                        == 0
12099                                {
12100                                    None
12101                                } else {
12102                                    Some(language)
12103                                }
12104                            })
12105                            .cloned()
12106                            .collect::<HashSet<_>>();
12107                        if !languages_affected.is_empty() {
12108                            self.refresh_inlay_hints(
12109                                InlayHintRefreshReason::BufferEdited(languages_affected),
12110                                cx,
12111                            );
12112                        }
12113                    }
12114                }
12115
12116                let Some(project) = &self.project else { return };
12117                let (telemetry, is_via_ssh) = {
12118                    let project = project.read(cx);
12119                    let telemetry = project.client().telemetry().clone();
12120                    let is_via_ssh = project.is_via_ssh();
12121                    (telemetry, is_via_ssh)
12122                };
12123                refresh_linked_ranges(self, cx);
12124                telemetry.log_edit_event("editor", is_via_ssh);
12125            }
12126            multi_buffer::Event::ExcerptsAdded {
12127                buffer,
12128                predecessor,
12129                excerpts,
12130            } => {
12131                self.tasks_update_task = Some(self.refresh_runnables(cx));
12132                let buffer_id = buffer.read(cx).remote_id();
12133                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12134                    if let Some(project) = &self.project {
12135                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12136                    }
12137                }
12138                cx.emit(EditorEvent::ExcerptsAdded {
12139                    buffer: buffer.clone(),
12140                    predecessor: *predecessor,
12141                    excerpts: excerpts.clone(),
12142                });
12143                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12144            }
12145            multi_buffer::Event::ExcerptsRemoved { ids } => {
12146                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12147                let buffer = self.buffer.read(cx);
12148                self.registered_buffers
12149                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12150                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12151            }
12152            multi_buffer::Event::ExcerptsEdited { ids } => {
12153                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12154            }
12155            multi_buffer::Event::ExcerptsExpanded { ids } => {
12156                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12157            }
12158            multi_buffer::Event::Reparsed(buffer_id) => {
12159                self.tasks_update_task = Some(self.refresh_runnables(cx));
12160
12161                cx.emit(EditorEvent::Reparsed(*buffer_id));
12162            }
12163            multi_buffer::Event::LanguageChanged(buffer_id) => {
12164                linked_editing_ranges::refresh_linked_ranges(self, cx);
12165                cx.emit(EditorEvent::Reparsed(*buffer_id));
12166                cx.notify();
12167            }
12168            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12169            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12170            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12171                cx.emit(EditorEvent::TitleChanged)
12172            }
12173            // multi_buffer::Event::DiffBaseChanged => {
12174            //     self.scrollbar_marker_state.dirty = true;
12175            //     cx.emit(EditorEvent::DiffBaseChanged);
12176            //     cx.notify();
12177            // }
12178            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12179            multi_buffer::Event::DiagnosticsUpdated => {
12180                self.refresh_active_diagnostics(cx);
12181                self.scrollbar_marker_state.dirty = true;
12182                cx.notify();
12183            }
12184            _ => {}
12185        };
12186    }
12187
12188    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12189        cx.notify();
12190    }
12191
12192    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12193        self.tasks_update_task = Some(self.refresh_runnables(cx));
12194        self.refresh_inline_completion(true, false, cx);
12195        self.refresh_inlay_hints(
12196            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12197                self.selections.newest_anchor().head(),
12198                &self.buffer.read(cx).snapshot(cx),
12199                cx,
12200            )),
12201            cx,
12202        );
12203
12204        let old_cursor_shape = self.cursor_shape;
12205
12206        {
12207            let editor_settings = EditorSettings::get_global(cx);
12208            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12209            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12210            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12211        }
12212
12213        if old_cursor_shape != self.cursor_shape {
12214            cx.emit(EditorEvent::CursorShapeChanged);
12215        }
12216
12217        let project_settings = ProjectSettings::get_global(cx);
12218        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12219
12220        if self.mode == EditorMode::Full {
12221            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12222            if self.git_blame_inline_enabled != inline_blame_enabled {
12223                self.toggle_git_blame_inline_internal(false, cx);
12224            }
12225        }
12226
12227        cx.notify();
12228    }
12229
12230    pub fn set_searchable(&mut self, searchable: bool) {
12231        self.searchable = searchable;
12232    }
12233
12234    pub fn searchable(&self) -> bool {
12235        self.searchable
12236    }
12237
12238    fn open_proposed_changes_editor(
12239        &mut self,
12240        _: &OpenProposedChangesEditor,
12241        cx: &mut ViewContext<Self>,
12242    ) {
12243        let Some(workspace) = self.workspace() else {
12244            cx.propagate();
12245            return;
12246        };
12247
12248        let selections = self.selections.all::<usize>(cx);
12249        let buffer = self.buffer.read(cx);
12250        let mut new_selections_by_buffer = HashMap::default();
12251        for selection in selections {
12252            for (buffer, range, _) in
12253                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12254            {
12255                let mut range = range.to_point(buffer.read(cx));
12256                range.start.column = 0;
12257                range.end.column = buffer.read(cx).line_len(range.end.row);
12258                new_selections_by_buffer
12259                    .entry(buffer)
12260                    .or_insert(Vec::new())
12261                    .push(range)
12262            }
12263        }
12264
12265        let proposed_changes_buffers = new_selections_by_buffer
12266            .into_iter()
12267            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12268            .collect::<Vec<_>>();
12269        let proposed_changes_editor = cx.new_view(|cx| {
12270            ProposedChangesEditor::new(
12271                "Proposed changes",
12272                proposed_changes_buffers,
12273                self.project.clone(),
12274                cx,
12275            )
12276        });
12277
12278        cx.window_context().defer(move |cx| {
12279            workspace.update(cx, |workspace, cx| {
12280                workspace.active_pane().update(cx, |pane, cx| {
12281                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12282                });
12283            });
12284        });
12285    }
12286
12287    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12288        self.open_excerpts_common(None, true, cx)
12289    }
12290
12291    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12292        self.open_excerpts_common(None, false, cx)
12293    }
12294
12295    fn open_excerpts_common(
12296        &mut self,
12297        jump_data: Option<JumpData>,
12298        split: bool,
12299        cx: &mut ViewContext<Self>,
12300    ) {
12301        let Some(workspace) = self.workspace() else {
12302            cx.propagate();
12303            return;
12304        };
12305
12306        if self.buffer.read(cx).is_singleton() {
12307            cx.propagate();
12308            return;
12309        }
12310
12311        let mut new_selections_by_buffer = HashMap::default();
12312        match &jump_data {
12313            Some(jump_data) => {
12314                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12315                if let Some(buffer) = multi_buffer_snapshot
12316                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12317                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12318                {
12319                    let buffer_snapshot = buffer.read(cx).snapshot();
12320                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12321                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12322                    } else {
12323                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12324                    };
12325                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12326                    new_selections_by_buffer.insert(
12327                        buffer,
12328                        (
12329                            vec![jump_to_offset..jump_to_offset],
12330                            Some(jump_data.line_offset_from_top),
12331                        ),
12332                    );
12333                }
12334            }
12335            None => {
12336                let selections = self.selections.all::<usize>(cx);
12337                let buffer = self.buffer.read(cx);
12338                for selection in selections {
12339                    for (mut buffer_handle, mut range, _) in
12340                        buffer.range_to_buffer_ranges(selection.range(), cx)
12341                    {
12342                        // When editing branch buffers, jump to the corresponding location
12343                        // in their base buffer.
12344                        let buffer = buffer_handle.read(cx);
12345                        if let Some(base_buffer) = buffer.base_buffer() {
12346                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12347                            buffer_handle = base_buffer;
12348                        }
12349
12350                        if selection.reversed {
12351                            mem::swap(&mut range.start, &mut range.end);
12352                        }
12353                        new_selections_by_buffer
12354                            .entry(buffer_handle)
12355                            .or_insert((Vec::new(), None))
12356                            .0
12357                            .push(range)
12358                    }
12359                }
12360            }
12361        }
12362
12363        if new_selections_by_buffer.is_empty() {
12364            return;
12365        }
12366
12367        // We defer the pane interaction because we ourselves are a workspace item
12368        // and activating a new item causes the pane to call a method on us reentrantly,
12369        // which panics if we're on the stack.
12370        cx.window_context().defer(move |cx| {
12371            workspace.update(cx, |workspace, cx| {
12372                let pane = if split {
12373                    workspace.adjacent_pane(cx)
12374                } else {
12375                    workspace.active_pane().clone()
12376                };
12377
12378                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12379                    let editor = buffer
12380                        .read(cx)
12381                        .file()
12382                        .is_none()
12383                        .then(|| {
12384                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12385                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12386                            // Instead, we try to activate the existing editor in the pane first.
12387                            let (editor, pane_item_index) =
12388                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12389                                    let editor = item.downcast::<Editor>()?;
12390                                    let singleton_buffer =
12391                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12392                                    if singleton_buffer == buffer {
12393                                        Some((editor, i))
12394                                    } else {
12395                                        None
12396                                    }
12397                                })?;
12398                            pane.update(cx, |pane, cx| {
12399                                pane.activate_item(pane_item_index, true, true, cx)
12400                            });
12401                            Some(editor)
12402                        })
12403                        .flatten()
12404                        .unwrap_or_else(|| {
12405                            workspace.open_project_item::<Self>(
12406                                pane.clone(),
12407                                buffer,
12408                                true,
12409                                true,
12410                                cx,
12411                            )
12412                        });
12413
12414                    editor.update(cx, |editor, cx| {
12415                        let autoscroll = match scroll_offset {
12416                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12417                            None => Autoscroll::newest(),
12418                        };
12419                        let nav_history = editor.nav_history.take();
12420                        editor.change_selections(Some(autoscroll), cx, |s| {
12421                            s.select_ranges(ranges);
12422                        });
12423                        editor.nav_history = nav_history;
12424                    });
12425                }
12426            })
12427        });
12428    }
12429
12430    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12431        let snapshot = self.buffer.read(cx).read(cx);
12432        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12433        Some(
12434            ranges
12435                .iter()
12436                .map(move |range| {
12437                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12438                })
12439                .collect(),
12440        )
12441    }
12442
12443    fn selection_replacement_ranges(
12444        &self,
12445        range: Range<OffsetUtf16>,
12446        cx: &mut AppContext,
12447    ) -> Vec<Range<OffsetUtf16>> {
12448        let selections = self.selections.all::<OffsetUtf16>(cx);
12449        let newest_selection = selections
12450            .iter()
12451            .max_by_key(|selection| selection.id)
12452            .unwrap();
12453        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12454        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12455        let snapshot = self.buffer.read(cx).read(cx);
12456        selections
12457            .into_iter()
12458            .map(|mut selection| {
12459                selection.start.0 =
12460                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12461                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12462                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12463                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12464            })
12465            .collect()
12466    }
12467
12468    fn report_editor_event(
12469        &self,
12470        operation: &'static str,
12471        file_extension: Option<String>,
12472        cx: &AppContext,
12473    ) {
12474        if cfg!(any(test, feature = "test-support")) {
12475            return;
12476        }
12477
12478        let Some(project) = &self.project else { return };
12479
12480        // If None, we are in a file without an extension
12481        let file = self
12482            .buffer
12483            .read(cx)
12484            .as_singleton()
12485            .and_then(|b| b.read(cx).file());
12486        let file_extension = file_extension.or(file
12487            .as_ref()
12488            .and_then(|file| Path::new(file.file_name(cx)).extension())
12489            .and_then(|e| e.to_str())
12490            .map(|a| a.to_string()));
12491
12492        let vim_mode = cx
12493            .global::<SettingsStore>()
12494            .raw_user_settings()
12495            .get("vim_mode")
12496            == Some(&serde_json::Value::Bool(true));
12497
12498        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12499            == language::language_settings::InlineCompletionProvider::Copilot;
12500        let copilot_enabled_for_language = self
12501            .buffer
12502            .read(cx)
12503            .settings_at(0, cx)
12504            .show_inline_completions;
12505
12506        let project = project.read(cx);
12507        let telemetry = project.client().telemetry().clone();
12508        telemetry.report_editor_event(
12509            file_extension,
12510            vim_mode,
12511            operation,
12512            copilot_enabled,
12513            copilot_enabled_for_language,
12514            project.is_via_ssh(),
12515        )
12516    }
12517
12518    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12519    /// with each line being an array of {text, highlight} objects.
12520    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12521        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12522            return;
12523        };
12524
12525        #[derive(Serialize)]
12526        struct Chunk<'a> {
12527            text: String,
12528            highlight: Option<&'a str>,
12529        }
12530
12531        let snapshot = buffer.read(cx).snapshot();
12532        let range = self
12533            .selected_text_range(false, cx)
12534            .and_then(|selection| {
12535                if selection.range.is_empty() {
12536                    None
12537                } else {
12538                    Some(selection.range)
12539                }
12540            })
12541            .unwrap_or_else(|| 0..snapshot.len());
12542
12543        let chunks = snapshot.chunks(range, true);
12544        let mut lines = Vec::new();
12545        let mut line: VecDeque<Chunk> = VecDeque::new();
12546
12547        let Some(style) = self.style.as_ref() else {
12548            return;
12549        };
12550
12551        for chunk in chunks {
12552            let highlight = chunk
12553                .syntax_highlight_id
12554                .and_then(|id| id.name(&style.syntax));
12555            let mut chunk_lines = chunk.text.split('\n').peekable();
12556            while let Some(text) = chunk_lines.next() {
12557                let mut merged_with_last_token = false;
12558                if let Some(last_token) = line.back_mut() {
12559                    if last_token.highlight == highlight {
12560                        last_token.text.push_str(text);
12561                        merged_with_last_token = true;
12562                    }
12563                }
12564
12565                if !merged_with_last_token {
12566                    line.push_back(Chunk {
12567                        text: text.into(),
12568                        highlight,
12569                    });
12570                }
12571
12572                if chunk_lines.peek().is_some() {
12573                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12574                        line.pop_front();
12575                    }
12576                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12577                        line.pop_back();
12578                    }
12579
12580                    lines.push(mem::take(&mut line));
12581                }
12582            }
12583        }
12584
12585        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12586            return;
12587        };
12588        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12589    }
12590
12591    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12592        self.request_autoscroll(Autoscroll::newest(), cx);
12593        let position = self.selections.newest_display(cx).start;
12594        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12595    }
12596
12597    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12598        &self.inlay_hint_cache
12599    }
12600
12601    pub fn replay_insert_event(
12602        &mut self,
12603        text: &str,
12604        relative_utf16_range: Option<Range<isize>>,
12605        cx: &mut ViewContext<Self>,
12606    ) {
12607        if !self.input_enabled {
12608            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12609            return;
12610        }
12611        if let Some(relative_utf16_range) = relative_utf16_range {
12612            let selections = self.selections.all::<OffsetUtf16>(cx);
12613            self.change_selections(None, cx, |s| {
12614                let new_ranges = selections.into_iter().map(|range| {
12615                    let start = OffsetUtf16(
12616                        range
12617                            .head()
12618                            .0
12619                            .saturating_add_signed(relative_utf16_range.start),
12620                    );
12621                    let end = OffsetUtf16(
12622                        range
12623                            .head()
12624                            .0
12625                            .saturating_add_signed(relative_utf16_range.end),
12626                    );
12627                    start..end
12628                });
12629                s.select_ranges(new_ranges);
12630            });
12631        }
12632
12633        self.handle_input(text, cx);
12634    }
12635
12636    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12637        let Some(provider) = self.semantics_provider.as_ref() else {
12638            return false;
12639        };
12640
12641        let mut supports = false;
12642        self.buffer().read(cx).for_each_buffer(|buffer| {
12643            supports |= provider.supports_inlay_hints(buffer, cx);
12644        });
12645        supports
12646    }
12647
12648    pub fn focus(&self, cx: &mut WindowContext) {
12649        cx.focus(&self.focus_handle)
12650    }
12651
12652    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12653        self.focus_handle.is_focused(cx)
12654    }
12655
12656    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12657        cx.emit(EditorEvent::Focused);
12658
12659        if let Some(descendant) = self
12660            .last_focused_descendant
12661            .take()
12662            .and_then(|descendant| descendant.upgrade())
12663        {
12664            cx.focus(&descendant);
12665        } else {
12666            if let Some(blame) = self.blame.as_ref() {
12667                blame.update(cx, GitBlame::focus)
12668            }
12669
12670            self.blink_manager.update(cx, BlinkManager::enable);
12671            self.show_cursor_names(cx);
12672            self.buffer.update(cx, |buffer, cx| {
12673                buffer.finalize_last_transaction(cx);
12674                if self.leader_peer_id.is_none() {
12675                    buffer.set_active_selections(
12676                        &self.selections.disjoint_anchors(),
12677                        self.selections.line_mode,
12678                        self.cursor_shape,
12679                        cx,
12680                    );
12681                }
12682            });
12683        }
12684    }
12685
12686    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12687        cx.emit(EditorEvent::FocusedIn)
12688    }
12689
12690    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12691        if event.blurred != self.focus_handle {
12692            self.last_focused_descendant = Some(event.blurred);
12693        }
12694    }
12695
12696    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12697        self.blink_manager.update(cx, BlinkManager::disable);
12698        self.buffer
12699            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12700
12701        if let Some(blame) = self.blame.as_ref() {
12702            blame.update(cx, GitBlame::blur)
12703        }
12704        if !self.hover_state.focused(cx) {
12705            hide_hover(self, cx);
12706        }
12707
12708        self.hide_context_menu(cx);
12709        cx.emit(EditorEvent::Blurred);
12710        cx.notify();
12711    }
12712
12713    pub fn register_action<A: Action>(
12714        &mut self,
12715        listener: impl Fn(&A, &mut WindowContext) + 'static,
12716    ) -> Subscription {
12717        let id = self.next_editor_action_id.post_inc();
12718        let listener = Arc::new(listener);
12719        self.editor_actions.borrow_mut().insert(
12720            id,
12721            Box::new(move |cx| {
12722                let cx = cx.window_context();
12723                let listener = listener.clone();
12724                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12725                    let action = action.downcast_ref().unwrap();
12726                    if phase == DispatchPhase::Bubble {
12727                        listener(action, cx)
12728                    }
12729                })
12730            }),
12731        );
12732
12733        let editor_actions = self.editor_actions.clone();
12734        Subscription::new(move || {
12735            editor_actions.borrow_mut().remove(&id);
12736        })
12737    }
12738
12739    pub fn file_header_size(&self) -> u32 {
12740        FILE_HEADER_HEIGHT
12741    }
12742
12743    pub fn revert(
12744        &mut self,
12745        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12746        cx: &mut ViewContext<Self>,
12747    ) {
12748        self.buffer().update(cx, |multi_buffer, cx| {
12749            for (buffer_id, changes) in revert_changes {
12750                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12751                    buffer.update(cx, |buffer, cx| {
12752                        buffer.edit(
12753                            changes.into_iter().map(|(range, text)| {
12754                                (range, text.to_string().map(Arc::<str>::from))
12755                            }),
12756                            None,
12757                            cx,
12758                        );
12759                    });
12760                }
12761            }
12762        });
12763        self.change_selections(None, cx, |selections| selections.refresh());
12764    }
12765
12766    pub fn to_pixel_point(
12767        &mut self,
12768        source: multi_buffer::Anchor,
12769        editor_snapshot: &EditorSnapshot,
12770        cx: &mut ViewContext<Self>,
12771    ) -> Option<gpui::Point<Pixels>> {
12772        let source_point = source.to_display_point(editor_snapshot);
12773        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12774    }
12775
12776    pub fn display_to_pixel_point(
12777        &self,
12778        source: DisplayPoint,
12779        editor_snapshot: &EditorSnapshot,
12780        cx: &WindowContext,
12781    ) -> Option<gpui::Point<Pixels>> {
12782        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12783        let text_layout_details = self.text_layout_details(cx);
12784        let scroll_top = text_layout_details
12785            .scroll_anchor
12786            .scroll_position(editor_snapshot)
12787            .y;
12788
12789        if source.row().as_f32() < scroll_top.floor() {
12790            return None;
12791        }
12792        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12793        let source_y = line_height * (source.row().as_f32() - scroll_top);
12794        Some(gpui::Point::new(source_x, source_y))
12795    }
12796
12797    pub fn has_active_completions_menu(&self) -> bool {
12798        self.context_menu.borrow().as_ref().map_or(false, |menu| {
12799            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12800        })
12801    }
12802
12803    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12804        self.addons
12805            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12806    }
12807
12808    pub fn unregister_addon<T: Addon>(&mut self) {
12809        self.addons.remove(&std::any::TypeId::of::<T>());
12810    }
12811
12812    pub fn addon<T: Addon>(&self) -> Option<&T> {
12813        let type_id = std::any::TypeId::of::<T>();
12814        self.addons
12815            .get(&type_id)
12816            .and_then(|item| item.to_any().downcast_ref::<T>())
12817    }
12818
12819    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12820        let text_layout_details = self.text_layout_details(cx);
12821        let style = &text_layout_details.editor_style;
12822        let font_id = cx.text_system().resolve_font(&style.text.font());
12823        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12824        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12825
12826        let em_width = cx
12827            .text_system()
12828            .typographic_bounds(font_id, font_size, 'm')
12829            .unwrap()
12830            .size
12831            .width;
12832
12833        gpui::Point::new(em_width, line_height)
12834    }
12835}
12836
12837fn get_unstaged_changes_for_buffers(
12838    project: &Model<Project>,
12839    buffers: impl IntoIterator<Item = Model<Buffer>>,
12840    cx: &mut ViewContext<Editor>,
12841) {
12842    let mut tasks = Vec::new();
12843    project.update(cx, |project, cx| {
12844        for buffer in buffers {
12845            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12846        }
12847    });
12848    cx.spawn(|this, mut cx| async move {
12849        let change_sets = futures::future::join_all(tasks).await;
12850        this.update(&mut cx, |this, cx| {
12851            for change_set in change_sets {
12852                if let Some(change_set) = change_set.log_err() {
12853                    this.diff_map.add_change_set(change_set, cx);
12854                }
12855            }
12856        })
12857        .ok();
12858    })
12859    .detach();
12860}
12861
12862fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12863    let tab_size = tab_size.get() as usize;
12864    let mut width = offset;
12865
12866    for ch in text.chars() {
12867        width += if ch == '\t' {
12868            tab_size - (width % tab_size)
12869        } else {
12870            1
12871        };
12872    }
12873
12874    width - offset
12875}
12876
12877#[cfg(test)]
12878mod tests {
12879    use super::*;
12880
12881    #[test]
12882    fn test_string_size_with_expanded_tabs() {
12883        let nz = |val| NonZeroU32::new(val).unwrap();
12884        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12885        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12886        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12887        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12888        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12889        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12890        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12891        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12892    }
12893}
12894
12895/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12896struct WordBreakingTokenizer<'a> {
12897    input: &'a str,
12898}
12899
12900impl<'a> WordBreakingTokenizer<'a> {
12901    fn new(input: &'a str) -> Self {
12902        Self { input }
12903    }
12904}
12905
12906fn is_char_ideographic(ch: char) -> bool {
12907    use unicode_script::Script::*;
12908    use unicode_script::UnicodeScript;
12909    matches!(ch.script(), Han | Tangut | Yi)
12910}
12911
12912fn is_grapheme_ideographic(text: &str) -> bool {
12913    text.chars().any(is_char_ideographic)
12914}
12915
12916fn is_grapheme_whitespace(text: &str) -> bool {
12917    text.chars().any(|x| x.is_whitespace())
12918}
12919
12920fn should_stay_with_preceding_ideograph(text: &str) -> bool {
12921    text.chars().next().map_or(false, |ch| {
12922        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
12923    })
12924}
12925
12926#[derive(PartialEq, Eq, Debug, Clone, Copy)]
12927struct WordBreakToken<'a> {
12928    token: &'a str,
12929    grapheme_len: usize,
12930    is_whitespace: bool,
12931}
12932
12933impl<'a> Iterator for WordBreakingTokenizer<'a> {
12934    /// Yields a span, the count of graphemes in the token, and whether it was
12935    /// whitespace. Note that it also breaks at word boundaries.
12936    type Item = WordBreakToken<'a>;
12937
12938    fn next(&mut self) -> Option<Self::Item> {
12939        use unicode_segmentation::UnicodeSegmentation;
12940        if self.input.is_empty() {
12941            return None;
12942        }
12943
12944        let mut iter = self.input.graphemes(true).peekable();
12945        let mut offset = 0;
12946        let mut graphemes = 0;
12947        if let Some(first_grapheme) = iter.next() {
12948            let is_whitespace = is_grapheme_whitespace(first_grapheme);
12949            offset += first_grapheme.len();
12950            graphemes += 1;
12951            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
12952                if let Some(grapheme) = iter.peek().copied() {
12953                    if should_stay_with_preceding_ideograph(grapheme) {
12954                        offset += grapheme.len();
12955                        graphemes += 1;
12956                    }
12957                }
12958            } else {
12959                let mut words = self.input[offset..].split_word_bound_indices().peekable();
12960                let mut next_word_bound = words.peek().copied();
12961                if next_word_bound.map_or(false, |(i, _)| i == 0) {
12962                    next_word_bound = words.next();
12963                }
12964                while let Some(grapheme) = iter.peek().copied() {
12965                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
12966                        break;
12967                    };
12968                    if is_grapheme_whitespace(grapheme) != is_whitespace {
12969                        break;
12970                    };
12971                    offset += grapheme.len();
12972                    graphemes += 1;
12973                    iter.next();
12974                }
12975            }
12976            let token = &self.input[..offset];
12977            self.input = &self.input[offset..];
12978            if is_whitespace {
12979                Some(WordBreakToken {
12980                    token: " ",
12981                    grapheme_len: 1,
12982                    is_whitespace: true,
12983                })
12984            } else {
12985                Some(WordBreakToken {
12986                    token,
12987                    grapheme_len: graphemes,
12988                    is_whitespace: false,
12989                })
12990            }
12991        } else {
12992            None
12993        }
12994    }
12995}
12996
12997#[test]
12998fn test_word_breaking_tokenizer() {
12999    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13000        ("", &[]),
13001        ("  ", &[(" ", 1, true)]),
13002        ("Ʒ", &[("Ʒ", 1, false)]),
13003        ("Ǽ", &[("Ǽ", 1, false)]),
13004        ("", &[("", 1, false)]),
13005        ("⋑⋑", &[("⋑⋑", 2, false)]),
13006        (
13007            "原理,进而",
13008            &[
13009                ("", 1, false),
13010                ("理,", 2, false),
13011                ("", 1, false),
13012                ("", 1, false),
13013            ],
13014        ),
13015        (
13016            "hello world",
13017            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13018        ),
13019        (
13020            "hello, world",
13021            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13022        ),
13023        (
13024            "  hello world",
13025            &[
13026                (" ", 1, true),
13027                ("hello", 5, false),
13028                (" ", 1, true),
13029                ("world", 5, false),
13030            ],
13031        ),
13032        (
13033            "这是什么 \n 钢笔",
13034            &[
13035                ("", 1, false),
13036                ("", 1, false),
13037                ("", 1, false),
13038                ("", 1, false),
13039                (" ", 1, true),
13040                ("", 1, false),
13041                ("", 1, false),
13042            ],
13043        ),
13044        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13045    ];
13046
13047    for (input, result) in tests {
13048        assert_eq!(
13049            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13050            result
13051                .iter()
13052                .copied()
13053                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13054                    token,
13055                    grapheme_len,
13056                    is_whitespace,
13057                })
13058                .collect::<Vec<_>>()
13059        );
13060    }
13061}
13062
13063fn wrap_with_prefix(
13064    line_prefix: String,
13065    unwrapped_text: String,
13066    wrap_column: usize,
13067    tab_size: NonZeroU32,
13068) -> String {
13069    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13070    let mut wrapped_text = String::new();
13071    let mut current_line = line_prefix.clone();
13072
13073    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13074    let mut current_line_len = line_prefix_len;
13075    for WordBreakToken {
13076        token,
13077        grapheme_len,
13078        is_whitespace,
13079    } in tokenizer
13080    {
13081        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13082            wrapped_text.push_str(current_line.trim_end());
13083            wrapped_text.push('\n');
13084            current_line.truncate(line_prefix.len());
13085            current_line_len = line_prefix_len;
13086            if !is_whitespace {
13087                current_line.push_str(token);
13088                current_line_len += grapheme_len;
13089            }
13090        } else if !is_whitespace {
13091            current_line.push_str(token);
13092            current_line_len += grapheme_len;
13093        } else if current_line_len != line_prefix_len {
13094            current_line.push(' ');
13095            current_line_len += 1;
13096        }
13097    }
13098
13099    if !current_line.is_empty() {
13100        wrapped_text.push_str(&current_line);
13101    }
13102    wrapped_text
13103}
13104
13105#[test]
13106fn test_wrap_with_prefix() {
13107    assert_eq!(
13108        wrap_with_prefix(
13109            "# ".to_string(),
13110            "abcdefg".to_string(),
13111            4,
13112            NonZeroU32::new(4).unwrap()
13113        ),
13114        "# abcdefg"
13115    );
13116    assert_eq!(
13117        wrap_with_prefix(
13118            "".to_string(),
13119            "\thello world".to_string(),
13120            8,
13121            NonZeroU32::new(4).unwrap()
13122        ),
13123        "hello\nworld"
13124    );
13125    assert_eq!(
13126        wrap_with_prefix(
13127            "// ".to_string(),
13128            "xx \nyy zz aa bb cc".to_string(),
13129            12,
13130            NonZeroU32::new(4).unwrap()
13131        ),
13132        "// xx yy zz\n// aa bb cc"
13133    );
13134    assert_eq!(
13135        wrap_with_prefix(
13136            String::new(),
13137            "这是什么 \n 钢笔".to_string(),
13138            3,
13139            NonZeroU32::new(4).unwrap()
13140        ),
13141        "这是什\n么 钢\n"
13142    );
13143}
13144
13145fn hunks_for_selections(
13146    snapshot: &EditorSnapshot,
13147    selections: &[Selection<Point>],
13148) -> Vec<MultiBufferDiffHunk> {
13149    hunks_for_ranges(
13150        selections.iter().map(|selection| selection.range()),
13151        snapshot,
13152    )
13153}
13154
13155pub fn hunks_for_ranges(
13156    ranges: impl Iterator<Item = Range<Point>>,
13157    snapshot: &EditorSnapshot,
13158) -> Vec<MultiBufferDiffHunk> {
13159    let mut hunks = Vec::new();
13160    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13161        HashMap::default();
13162    for query_range in ranges {
13163        let query_rows =
13164            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13165        for hunk in snapshot.diff_map.diff_hunks_in_range(
13166            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13167            &snapshot.buffer_snapshot,
13168        ) {
13169            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13170            // when the caret is just above or just below the deleted hunk.
13171            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13172            let related_to_selection = if allow_adjacent {
13173                hunk.row_range.overlaps(&query_rows)
13174                    || hunk.row_range.start == query_rows.end
13175                    || hunk.row_range.end == query_rows.start
13176            } else {
13177                hunk.row_range.overlaps(&query_rows)
13178            };
13179            if related_to_selection {
13180                if !processed_buffer_rows
13181                    .entry(hunk.buffer_id)
13182                    .or_default()
13183                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13184                {
13185                    continue;
13186                }
13187                hunks.push(hunk);
13188            }
13189        }
13190    }
13191
13192    hunks
13193}
13194
13195pub trait CollaborationHub {
13196    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13197    fn user_participant_indices<'a>(
13198        &self,
13199        cx: &'a AppContext,
13200    ) -> &'a HashMap<u64, ParticipantIndex>;
13201    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13202}
13203
13204impl CollaborationHub for Model<Project> {
13205    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13206        self.read(cx).collaborators()
13207    }
13208
13209    fn user_participant_indices<'a>(
13210        &self,
13211        cx: &'a AppContext,
13212    ) -> &'a HashMap<u64, ParticipantIndex> {
13213        self.read(cx).user_store().read(cx).participant_indices()
13214    }
13215
13216    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13217        let this = self.read(cx);
13218        let user_ids = this.collaborators().values().map(|c| c.user_id);
13219        this.user_store().read_with(cx, |user_store, cx| {
13220            user_store.participant_names(user_ids, cx)
13221        })
13222    }
13223}
13224
13225pub trait SemanticsProvider {
13226    fn hover(
13227        &self,
13228        buffer: &Model<Buffer>,
13229        position: text::Anchor,
13230        cx: &mut AppContext,
13231    ) -> Option<Task<Vec<project::Hover>>>;
13232
13233    fn inlay_hints(
13234        &self,
13235        buffer_handle: Model<Buffer>,
13236        range: Range<text::Anchor>,
13237        cx: &mut AppContext,
13238    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13239
13240    fn resolve_inlay_hint(
13241        &self,
13242        hint: InlayHint,
13243        buffer_handle: Model<Buffer>,
13244        server_id: LanguageServerId,
13245        cx: &mut AppContext,
13246    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13247
13248    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13249
13250    fn document_highlights(
13251        &self,
13252        buffer: &Model<Buffer>,
13253        position: text::Anchor,
13254        cx: &mut AppContext,
13255    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13256
13257    fn definitions(
13258        &self,
13259        buffer: &Model<Buffer>,
13260        position: text::Anchor,
13261        kind: GotoDefinitionKind,
13262        cx: &mut AppContext,
13263    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13264
13265    fn range_for_rename(
13266        &self,
13267        buffer: &Model<Buffer>,
13268        position: text::Anchor,
13269        cx: &mut AppContext,
13270    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13271
13272    fn perform_rename(
13273        &self,
13274        buffer: &Model<Buffer>,
13275        position: text::Anchor,
13276        new_name: String,
13277        cx: &mut AppContext,
13278    ) -> Option<Task<Result<ProjectTransaction>>>;
13279}
13280
13281pub trait CompletionProvider {
13282    fn completions(
13283        &self,
13284        buffer: &Model<Buffer>,
13285        buffer_position: text::Anchor,
13286        trigger: CompletionContext,
13287        cx: &mut ViewContext<Editor>,
13288    ) -> Task<Result<Vec<Completion>>>;
13289
13290    fn resolve_completions(
13291        &self,
13292        buffer: Model<Buffer>,
13293        completion_indices: Vec<usize>,
13294        completions: Rc<RefCell<Box<[Completion]>>>,
13295        cx: &mut ViewContext<Editor>,
13296    ) -> Task<Result<bool>>;
13297
13298    fn apply_additional_edits_for_completion(
13299        &self,
13300        buffer: Model<Buffer>,
13301        completion: Completion,
13302        push_to_history: bool,
13303        cx: &mut ViewContext<Editor>,
13304    ) -> Task<Result<Option<language::Transaction>>>;
13305
13306    fn is_completion_trigger(
13307        &self,
13308        buffer: &Model<Buffer>,
13309        position: language::Anchor,
13310        text: &str,
13311        trigger_in_words: bool,
13312        cx: &mut ViewContext<Editor>,
13313    ) -> bool;
13314
13315    fn sort_completions(&self) -> bool {
13316        true
13317    }
13318}
13319
13320pub trait CodeActionProvider {
13321    fn code_actions(
13322        &self,
13323        buffer: &Model<Buffer>,
13324        range: Range<text::Anchor>,
13325        cx: &mut WindowContext,
13326    ) -> Task<Result<Vec<CodeAction>>>;
13327
13328    fn apply_code_action(
13329        &self,
13330        buffer_handle: Model<Buffer>,
13331        action: CodeAction,
13332        excerpt_id: ExcerptId,
13333        push_to_history: bool,
13334        cx: &mut WindowContext,
13335    ) -> Task<Result<ProjectTransaction>>;
13336}
13337
13338impl CodeActionProvider for Model<Project> {
13339    fn code_actions(
13340        &self,
13341        buffer: &Model<Buffer>,
13342        range: Range<text::Anchor>,
13343        cx: &mut WindowContext,
13344    ) -> Task<Result<Vec<CodeAction>>> {
13345        self.update(cx, |project, cx| {
13346            project.code_actions(buffer, range, None, cx)
13347        })
13348    }
13349
13350    fn apply_code_action(
13351        &self,
13352        buffer_handle: Model<Buffer>,
13353        action: CodeAction,
13354        _excerpt_id: ExcerptId,
13355        push_to_history: bool,
13356        cx: &mut WindowContext,
13357    ) -> Task<Result<ProjectTransaction>> {
13358        self.update(cx, |project, cx| {
13359            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13360        })
13361    }
13362}
13363
13364fn snippet_completions(
13365    project: &Project,
13366    buffer: &Model<Buffer>,
13367    buffer_position: text::Anchor,
13368    cx: &mut AppContext,
13369) -> Task<Result<Vec<Completion>>> {
13370    let language = buffer.read(cx).language_at(buffer_position);
13371    let language_name = language.as_ref().map(|language| language.lsp_id());
13372    let snippet_store = project.snippets().read(cx);
13373    let snippets = snippet_store.snippets_for(language_name, cx);
13374
13375    if snippets.is_empty() {
13376        return Task::ready(Ok(vec![]));
13377    }
13378    let snapshot = buffer.read(cx).text_snapshot();
13379    let chars: String = snapshot
13380        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13381        .collect();
13382
13383    let scope = language.map(|language| language.default_scope());
13384    let executor = cx.background_executor().clone();
13385
13386    cx.background_executor().spawn(async move {
13387        let classifier = CharClassifier::new(scope).for_completion(true);
13388        let mut last_word = chars
13389            .chars()
13390            .take_while(|c| classifier.is_word(*c))
13391            .collect::<String>();
13392        last_word = last_word.chars().rev().collect();
13393
13394        if last_word.is_empty() {
13395            return Ok(vec![]);
13396        }
13397
13398        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13399        let to_lsp = |point: &text::Anchor| {
13400            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13401            point_to_lsp(end)
13402        };
13403        let lsp_end = to_lsp(&buffer_position);
13404
13405        let candidates = snippets
13406            .iter()
13407            .enumerate()
13408            .flat_map(|(ix, snippet)| {
13409                snippet
13410                    .prefix
13411                    .iter()
13412                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13413            })
13414            .collect::<Vec<StringMatchCandidate>>();
13415
13416        let mut matches = fuzzy::match_strings(
13417            &candidates,
13418            &last_word,
13419            last_word.chars().any(|c| c.is_uppercase()),
13420            100,
13421            &Default::default(),
13422            executor,
13423        )
13424        .await;
13425
13426        // Remove all candidates where the query's start does not match the start of any word in the candidate
13427        if let Some(query_start) = last_word.chars().next() {
13428            matches.retain(|string_match| {
13429                split_words(&string_match.string).any(|word| {
13430                    // Check that the first codepoint of the word as lowercase matches the first
13431                    // codepoint of the query as lowercase
13432                    word.chars()
13433                        .flat_map(|codepoint| codepoint.to_lowercase())
13434                        .zip(query_start.to_lowercase())
13435                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13436                })
13437            });
13438        }
13439
13440        let matched_strings = matches
13441            .into_iter()
13442            .map(|m| m.string)
13443            .collect::<HashSet<_>>();
13444
13445        let result: Vec<Completion> = snippets
13446            .into_iter()
13447            .filter_map(|snippet| {
13448                let matching_prefix = snippet
13449                    .prefix
13450                    .iter()
13451                    .find(|prefix| matched_strings.contains(*prefix))?;
13452                let start = as_offset - last_word.len();
13453                let start = snapshot.anchor_before(start);
13454                let range = start..buffer_position;
13455                let lsp_start = to_lsp(&start);
13456                let lsp_range = lsp::Range {
13457                    start: lsp_start,
13458                    end: lsp_end,
13459                };
13460                Some(Completion {
13461                    old_range: range,
13462                    new_text: snippet.body.clone(),
13463                    label: CodeLabel {
13464                        text: matching_prefix.clone(),
13465                        runs: vec![],
13466                        filter_range: 0..matching_prefix.len(),
13467                    },
13468                    server_id: LanguageServerId(usize::MAX),
13469                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13470                    lsp_completion: lsp::CompletionItem {
13471                        label: snippet.prefix.first().unwrap().clone(),
13472                        kind: Some(CompletionItemKind::SNIPPET),
13473                        label_details: snippet.description.as_ref().map(|description| {
13474                            lsp::CompletionItemLabelDetails {
13475                                detail: Some(description.clone()),
13476                                description: None,
13477                            }
13478                        }),
13479                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13480                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13481                            lsp::InsertReplaceEdit {
13482                                new_text: snippet.body.clone(),
13483                                insert: lsp_range,
13484                                replace: lsp_range,
13485                            },
13486                        )),
13487                        filter_text: Some(snippet.body.clone()),
13488                        sort_text: Some(char::MAX.to_string()),
13489                        ..Default::default()
13490                    },
13491                    confirm: None,
13492                })
13493            })
13494            .collect();
13495
13496        Ok(result)
13497    })
13498}
13499
13500impl CompletionProvider for Model<Project> {
13501    fn completions(
13502        &self,
13503        buffer: &Model<Buffer>,
13504        buffer_position: text::Anchor,
13505        options: CompletionContext,
13506        cx: &mut ViewContext<Editor>,
13507    ) -> Task<Result<Vec<Completion>>> {
13508        self.update(cx, |project, cx| {
13509            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13510            let project_completions = project.completions(buffer, buffer_position, options, cx);
13511            cx.background_executor().spawn(async move {
13512                let mut completions = project_completions.await?;
13513                let snippets_completions = snippets.await?;
13514                completions.extend(snippets_completions);
13515                Ok(completions)
13516            })
13517        })
13518    }
13519
13520    fn resolve_completions(
13521        &self,
13522        buffer: Model<Buffer>,
13523        completion_indices: Vec<usize>,
13524        completions: Rc<RefCell<Box<[Completion]>>>,
13525        cx: &mut ViewContext<Editor>,
13526    ) -> Task<Result<bool>> {
13527        self.update(cx, |project, cx| {
13528            project.resolve_completions(buffer, completion_indices, completions, cx)
13529        })
13530    }
13531
13532    fn apply_additional_edits_for_completion(
13533        &self,
13534        buffer: Model<Buffer>,
13535        completion: Completion,
13536        push_to_history: bool,
13537        cx: &mut ViewContext<Editor>,
13538    ) -> Task<Result<Option<language::Transaction>>> {
13539        self.update(cx, |project, cx| {
13540            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13541        })
13542    }
13543
13544    fn is_completion_trigger(
13545        &self,
13546        buffer: &Model<Buffer>,
13547        position: language::Anchor,
13548        text: &str,
13549        trigger_in_words: bool,
13550        cx: &mut ViewContext<Editor>,
13551    ) -> bool {
13552        let mut chars = text.chars();
13553        let char = if let Some(char) = chars.next() {
13554            char
13555        } else {
13556            return false;
13557        };
13558        if chars.next().is_some() {
13559            return false;
13560        }
13561
13562        let buffer = buffer.read(cx);
13563        let snapshot = buffer.snapshot();
13564        if !snapshot.settings_at(position, cx).show_completions_on_input {
13565            return false;
13566        }
13567        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13568        if trigger_in_words && classifier.is_word(char) {
13569            return true;
13570        }
13571
13572        buffer.completion_triggers().contains(text)
13573    }
13574}
13575
13576impl SemanticsProvider for Model<Project> {
13577    fn hover(
13578        &self,
13579        buffer: &Model<Buffer>,
13580        position: text::Anchor,
13581        cx: &mut AppContext,
13582    ) -> Option<Task<Vec<project::Hover>>> {
13583        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13584    }
13585
13586    fn document_highlights(
13587        &self,
13588        buffer: &Model<Buffer>,
13589        position: text::Anchor,
13590        cx: &mut AppContext,
13591    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13592        Some(self.update(cx, |project, cx| {
13593            project.document_highlights(buffer, position, cx)
13594        }))
13595    }
13596
13597    fn definitions(
13598        &self,
13599        buffer: &Model<Buffer>,
13600        position: text::Anchor,
13601        kind: GotoDefinitionKind,
13602        cx: &mut AppContext,
13603    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13604        Some(self.update(cx, |project, cx| match kind {
13605            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13606            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13607            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13608            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13609        }))
13610    }
13611
13612    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13613        // TODO: make this work for remote projects
13614        self.read(cx)
13615            .language_servers_for_local_buffer(buffer.read(cx), cx)
13616            .any(
13617                |(_, server)| match server.capabilities().inlay_hint_provider {
13618                    Some(lsp::OneOf::Left(enabled)) => enabled,
13619                    Some(lsp::OneOf::Right(_)) => true,
13620                    None => false,
13621                },
13622            )
13623    }
13624
13625    fn inlay_hints(
13626        &self,
13627        buffer_handle: Model<Buffer>,
13628        range: Range<text::Anchor>,
13629        cx: &mut AppContext,
13630    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13631        Some(self.update(cx, |project, cx| {
13632            project.inlay_hints(buffer_handle, range, cx)
13633        }))
13634    }
13635
13636    fn resolve_inlay_hint(
13637        &self,
13638        hint: InlayHint,
13639        buffer_handle: Model<Buffer>,
13640        server_id: LanguageServerId,
13641        cx: &mut AppContext,
13642    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13643        Some(self.update(cx, |project, cx| {
13644            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13645        }))
13646    }
13647
13648    fn range_for_rename(
13649        &self,
13650        buffer: &Model<Buffer>,
13651        position: text::Anchor,
13652        cx: &mut AppContext,
13653    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13654        Some(self.update(cx, |project, cx| {
13655            project.prepare_rename(buffer.clone(), position, cx)
13656        }))
13657    }
13658
13659    fn perform_rename(
13660        &self,
13661        buffer: &Model<Buffer>,
13662        position: text::Anchor,
13663        new_name: String,
13664        cx: &mut AppContext,
13665    ) -> Option<Task<Result<ProjectTransaction>>> {
13666        Some(self.update(cx, |project, cx| {
13667            project.perform_rename(buffer.clone(), position, new_name, cx)
13668        }))
13669    }
13670}
13671
13672fn inlay_hint_settings(
13673    location: Anchor,
13674    snapshot: &MultiBufferSnapshot,
13675    cx: &mut ViewContext<'_, Editor>,
13676) -> InlayHintSettings {
13677    let file = snapshot.file_at(location);
13678    let language = snapshot.language_at(location).map(|l| l.name());
13679    language_settings(language, file, cx).inlay_hints
13680}
13681
13682fn consume_contiguous_rows(
13683    contiguous_row_selections: &mut Vec<Selection<Point>>,
13684    selection: &Selection<Point>,
13685    display_map: &DisplaySnapshot,
13686    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13687) -> (MultiBufferRow, MultiBufferRow) {
13688    contiguous_row_selections.push(selection.clone());
13689    let start_row = MultiBufferRow(selection.start.row);
13690    let mut end_row = ending_row(selection, display_map);
13691
13692    while let Some(next_selection) = selections.peek() {
13693        if next_selection.start.row <= end_row.0 {
13694            end_row = ending_row(next_selection, display_map);
13695            contiguous_row_selections.push(selections.next().unwrap().clone());
13696        } else {
13697            break;
13698        }
13699    }
13700    (start_row, end_row)
13701}
13702
13703fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13704    if next_selection.end.column > 0 || next_selection.is_empty() {
13705        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13706    } else {
13707        MultiBufferRow(next_selection.end.row)
13708    }
13709}
13710
13711impl EditorSnapshot {
13712    pub fn remote_selections_in_range<'a>(
13713        &'a self,
13714        range: &'a Range<Anchor>,
13715        collaboration_hub: &dyn CollaborationHub,
13716        cx: &'a AppContext,
13717    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13718        let participant_names = collaboration_hub.user_names(cx);
13719        let participant_indices = collaboration_hub.user_participant_indices(cx);
13720        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13721        let collaborators_by_replica_id = collaborators_by_peer_id
13722            .iter()
13723            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13724            .collect::<HashMap<_, _>>();
13725        self.buffer_snapshot
13726            .selections_in_range(range, false)
13727            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13728                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13729                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13730                let user_name = participant_names.get(&collaborator.user_id).cloned();
13731                Some(RemoteSelection {
13732                    replica_id,
13733                    selection,
13734                    cursor_shape,
13735                    line_mode,
13736                    participant_index,
13737                    peer_id: collaborator.peer_id,
13738                    user_name,
13739                })
13740            })
13741    }
13742
13743    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13744        self.display_snapshot.buffer_snapshot.language_at(position)
13745    }
13746
13747    pub fn is_focused(&self) -> bool {
13748        self.is_focused
13749    }
13750
13751    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13752        self.placeholder_text.as_ref()
13753    }
13754
13755    pub fn scroll_position(&self) -> gpui::Point<f32> {
13756        self.scroll_anchor.scroll_position(&self.display_snapshot)
13757    }
13758
13759    fn gutter_dimensions(
13760        &self,
13761        font_id: FontId,
13762        font_size: Pixels,
13763        em_width: Pixels,
13764        em_advance: Pixels,
13765        max_line_number_width: Pixels,
13766        cx: &AppContext,
13767    ) -> GutterDimensions {
13768        if !self.show_gutter {
13769            return GutterDimensions::default();
13770        }
13771        let descent = cx.text_system().descent(font_id, font_size);
13772
13773        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13774            matches!(
13775                ProjectSettings::get_global(cx).git.git_gutter,
13776                Some(GitGutterSetting::TrackedFiles)
13777            )
13778        });
13779        let gutter_settings = EditorSettings::get_global(cx).gutter;
13780        let show_line_numbers = self
13781            .show_line_numbers
13782            .unwrap_or(gutter_settings.line_numbers);
13783        let line_gutter_width = if show_line_numbers {
13784            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13785            let min_width_for_number_on_gutter = em_advance * 4.0;
13786            max_line_number_width.max(min_width_for_number_on_gutter)
13787        } else {
13788            0.0.into()
13789        };
13790
13791        let show_code_actions = self
13792            .show_code_actions
13793            .unwrap_or(gutter_settings.code_actions);
13794
13795        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13796
13797        let git_blame_entries_width =
13798            self.git_blame_gutter_max_author_length
13799                .map(|max_author_length| {
13800                    // Length of the author name, but also space for the commit hash,
13801                    // the spacing and the timestamp.
13802                    let max_char_count = max_author_length
13803                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13804                        + 7 // length of commit sha
13805                        + 14 // length of max relative timestamp ("60 minutes ago")
13806                        + 4; // gaps and margins
13807
13808                    em_advance * max_char_count
13809                });
13810
13811        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13812        left_padding += if show_code_actions || show_runnables {
13813            em_width * 3.0
13814        } else if show_git_gutter && show_line_numbers {
13815            em_width * 2.0
13816        } else if show_git_gutter || show_line_numbers {
13817            em_width
13818        } else {
13819            px(0.)
13820        };
13821
13822        let right_padding = if gutter_settings.folds && show_line_numbers {
13823            em_width * 4.0
13824        } else if gutter_settings.folds {
13825            em_width * 3.0
13826        } else if show_line_numbers {
13827            em_width
13828        } else {
13829            px(0.)
13830        };
13831
13832        GutterDimensions {
13833            left_padding,
13834            right_padding,
13835            width: line_gutter_width + left_padding + right_padding,
13836            margin: -descent,
13837            git_blame_entries_width,
13838        }
13839    }
13840
13841    pub fn render_crease_toggle(
13842        &self,
13843        buffer_row: MultiBufferRow,
13844        row_contains_cursor: bool,
13845        editor: View<Editor>,
13846        cx: &mut WindowContext,
13847    ) -> Option<AnyElement> {
13848        let folded = self.is_line_folded(buffer_row);
13849        let mut is_foldable = false;
13850
13851        if let Some(crease) = self
13852            .crease_snapshot
13853            .query_row(buffer_row, &self.buffer_snapshot)
13854        {
13855            is_foldable = true;
13856            match crease {
13857                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13858                    if let Some(render_toggle) = render_toggle {
13859                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13860                            if folded {
13861                                editor.update(cx, |editor, cx| {
13862                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13863                                });
13864                            } else {
13865                                editor.update(cx, |editor, cx| {
13866                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13867                                });
13868                            }
13869                        });
13870                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13871                    }
13872                }
13873            }
13874        }
13875
13876        is_foldable |= self.starts_indent(buffer_row);
13877
13878        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13879            Some(
13880                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13881                    .toggle_state(folded)
13882                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13883                        if folded {
13884                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13885                        } else {
13886                            this.fold_at(&FoldAt { buffer_row }, cx);
13887                        }
13888                    }))
13889                    .into_any_element(),
13890            )
13891        } else {
13892            None
13893        }
13894    }
13895
13896    pub fn render_crease_trailer(
13897        &self,
13898        buffer_row: MultiBufferRow,
13899        cx: &mut WindowContext,
13900    ) -> Option<AnyElement> {
13901        let folded = self.is_line_folded(buffer_row);
13902        if let Crease::Inline { render_trailer, .. } = self
13903            .crease_snapshot
13904            .query_row(buffer_row, &self.buffer_snapshot)?
13905        {
13906            let render_trailer = render_trailer.as_ref()?;
13907            Some(render_trailer(buffer_row, folded, cx))
13908        } else {
13909            None
13910        }
13911    }
13912}
13913
13914impl Deref for EditorSnapshot {
13915    type Target = DisplaySnapshot;
13916
13917    fn deref(&self) -> &Self::Target {
13918        &self.display_snapshot
13919    }
13920}
13921
13922#[derive(Clone, Debug, PartialEq, Eq)]
13923pub enum EditorEvent {
13924    InputIgnored {
13925        text: Arc<str>,
13926    },
13927    InputHandled {
13928        utf16_range_to_replace: Option<Range<isize>>,
13929        text: Arc<str>,
13930    },
13931    ExcerptsAdded {
13932        buffer: Model<Buffer>,
13933        predecessor: ExcerptId,
13934        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13935    },
13936    ExcerptsRemoved {
13937        ids: Vec<ExcerptId>,
13938    },
13939    BufferFoldToggled {
13940        ids: Vec<ExcerptId>,
13941        folded: bool,
13942    },
13943    ExcerptsEdited {
13944        ids: Vec<ExcerptId>,
13945    },
13946    ExcerptsExpanded {
13947        ids: Vec<ExcerptId>,
13948    },
13949    BufferEdited,
13950    Edited {
13951        transaction_id: clock::Lamport,
13952    },
13953    Reparsed(BufferId),
13954    Focused,
13955    FocusedIn,
13956    Blurred,
13957    DirtyChanged,
13958    Saved,
13959    TitleChanged,
13960    DiffBaseChanged,
13961    SelectionsChanged {
13962        local: bool,
13963    },
13964    ScrollPositionChanged {
13965        local: bool,
13966        autoscroll: bool,
13967    },
13968    Closed,
13969    TransactionUndone {
13970        transaction_id: clock::Lamport,
13971    },
13972    TransactionBegun {
13973        transaction_id: clock::Lamport,
13974    },
13975    Reloaded,
13976    CursorShapeChanged,
13977}
13978
13979impl EventEmitter<EditorEvent> for Editor {}
13980
13981impl FocusableView for Editor {
13982    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13983        self.focus_handle.clone()
13984    }
13985}
13986
13987impl Render for Editor {
13988    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13989        let settings = ThemeSettings::get_global(cx);
13990
13991        let mut text_style = match self.mode {
13992            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13993                color: cx.theme().colors().editor_foreground,
13994                font_family: settings.ui_font.family.clone(),
13995                font_features: settings.ui_font.features.clone(),
13996                font_fallbacks: settings.ui_font.fallbacks.clone(),
13997                font_size: rems(0.875).into(),
13998                font_weight: settings.ui_font.weight,
13999                line_height: relative(settings.buffer_line_height.value()),
14000                ..Default::default()
14001            },
14002            EditorMode::Full => TextStyle {
14003                color: cx.theme().colors().editor_foreground,
14004                font_family: settings.buffer_font.family.clone(),
14005                font_features: settings.buffer_font.features.clone(),
14006                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14007                font_size: settings.buffer_font_size(cx).into(),
14008                font_weight: settings.buffer_font.weight,
14009                line_height: relative(settings.buffer_line_height.value()),
14010                ..Default::default()
14011            },
14012        };
14013        if let Some(text_style_refinement) = &self.text_style_refinement {
14014            text_style.refine(text_style_refinement)
14015        }
14016
14017        let background = match self.mode {
14018            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14019            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14020            EditorMode::Full => cx.theme().colors().editor_background,
14021        };
14022
14023        EditorElement::new(
14024            cx.view(),
14025            EditorStyle {
14026                background,
14027                local_player: cx.theme().players().local(),
14028                text: text_style,
14029                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14030                syntax: cx.theme().syntax().clone(),
14031                status: cx.theme().status().clone(),
14032                inlay_hints_style: make_inlay_hints_style(cx),
14033                inline_completion_styles: make_suggestion_styles(cx),
14034                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14035            },
14036        )
14037    }
14038}
14039
14040impl ViewInputHandler for Editor {
14041    fn text_for_range(
14042        &mut self,
14043        range_utf16: Range<usize>,
14044        adjusted_range: &mut Option<Range<usize>>,
14045        cx: &mut ViewContext<Self>,
14046    ) -> Option<String> {
14047        let snapshot = self.buffer.read(cx).read(cx);
14048        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14049        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14050        if (start.0..end.0) != range_utf16 {
14051            adjusted_range.replace(start.0..end.0);
14052        }
14053        Some(snapshot.text_for_range(start..end).collect())
14054    }
14055
14056    fn selected_text_range(
14057        &mut self,
14058        ignore_disabled_input: bool,
14059        cx: &mut ViewContext<Self>,
14060    ) -> Option<UTF16Selection> {
14061        // Prevent the IME menu from appearing when holding down an alphabetic key
14062        // while input is disabled.
14063        if !ignore_disabled_input && !self.input_enabled {
14064            return None;
14065        }
14066
14067        let selection = self.selections.newest::<OffsetUtf16>(cx);
14068        let range = selection.range();
14069
14070        Some(UTF16Selection {
14071            range: range.start.0..range.end.0,
14072            reversed: selection.reversed,
14073        })
14074    }
14075
14076    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14077        let snapshot = self.buffer.read(cx).read(cx);
14078        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14079        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14080    }
14081
14082    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14083        self.clear_highlights::<InputComposition>(cx);
14084        self.ime_transaction.take();
14085    }
14086
14087    fn replace_text_in_range(
14088        &mut self,
14089        range_utf16: Option<Range<usize>>,
14090        text: &str,
14091        cx: &mut ViewContext<Self>,
14092    ) {
14093        if !self.input_enabled {
14094            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14095            return;
14096        }
14097
14098        self.transact(cx, |this, cx| {
14099            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14100                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14101                Some(this.selection_replacement_ranges(range_utf16, cx))
14102            } else {
14103                this.marked_text_ranges(cx)
14104            };
14105
14106            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14107                let newest_selection_id = this.selections.newest_anchor().id;
14108                this.selections
14109                    .all::<OffsetUtf16>(cx)
14110                    .iter()
14111                    .zip(ranges_to_replace.iter())
14112                    .find_map(|(selection, range)| {
14113                        if selection.id == newest_selection_id {
14114                            Some(
14115                                (range.start.0 as isize - selection.head().0 as isize)
14116                                    ..(range.end.0 as isize - selection.head().0 as isize),
14117                            )
14118                        } else {
14119                            None
14120                        }
14121                    })
14122            });
14123
14124            cx.emit(EditorEvent::InputHandled {
14125                utf16_range_to_replace: range_to_replace,
14126                text: text.into(),
14127            });
14128
14129            if let Some(new_selected_ranges) = new_selected_ranges {
14130                this.change_selections(None, cx, |selections| {
14131                    selections.select_ranges(new_selected_ranges)
14132                });
14133                this.backspace(&Default::default(), cx);
14134            }
14135
14136            this.handle_input(text, cx);
14137        });
14138
14139        if let Some(transaction) = self.ime_transaction {
14140            self.buffer.update(cx, |buffer, cx| {
14141                buffer.group_until_transaction(transaction, cx);
14142            });
14143        }
14144
14145        self.unmark_text(cx);
14146    }
14147
14148    fn replace_and_mark_text_in_range(
14149        &mut self,
14150        range_utf16: Option<Range<usize>>,
14151        text: &str,
14152        new_selected_range_utf16: Option<Range<usize>>,
14153        cx: &mut ViewContext<Self>,
14154    ) {
14155        if !self.input_enabled {
14156            return;
14157        }
14158
14159        let transaction = self.transact(cx, |this, cx| {
14160            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14161                let snapshot = this.buffer.read(cx).read(cx);
14162                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14163                    for marked_range in &mut marked_ranges {
14164                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14165                        marked_range.start.0 += relative_range_utf16.start;
14166                        marked_range.start =
14167                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14168                        marked_range.end =
14169                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14170                    }
14171                }
14172                Some(marked_ranges)
14173            } else if let Some(range_utf16) = range_utf16 {
14174                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14175                Some(this.selection_replacement_ranges(range_utf16, cx))
14176            } else {
14177                None
14178            };
14179
14180            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14181                let newest_selection_id = this.selections.newest_anchor().id;
14182                this.selections
14183                    .all::<OffsetUtf16>(cx)
14184                    .iter()
14185                    .zip(ranges_to_replace.iter())
14186                    .find_map(|(selection, range)| {
14187                        if selection.id == newest_selection_id {
14188                            Some(
14189                                (range.start.0 as isize - selection.head().0 as isize)
14190                                    ..(range.end.0 as isize - selection.head().0 as isize),
14191                            )
14192                        } else {
14193                            None
14194                        }
14195                    })
14196            });
14197
14198            cx.emit(EditorEvent::InputHandled {
14199                utf16_range_to_replace: range_to_replace,
14200                text: text.into(),
14201            });
14202
14203            if let Some(ranges) = ranges_to_replace {
14204                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14205            }
14206
14207            let marked_ranges = {
14208                let snapshot = this.buffer.read(cx).read(cx);
14209                this.selections
14210                    .disjoint_anchors()
14211                    .iter()
14212                    .map(|selection| {
14213                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14214                    })
14215                    .collect::<Vec<_>>()
14216            };
14217
14218            if text.is_empty() {
14219                this.unmark_text(cx);
14220            } else {
14221                this.highlight_text::<InputComposition>(
14222                    marked_ranges.clone(),
14223                    HighlightStyle {
14224                        underline: Some(UnderlineStyle {
14225                            thickness: px(1.),
14226                            color: None,
14227                            wavy: false,
14228                        }),
14229                        ..Default::default()
14230                    },
14231                    cx,
14232                );
14233            }
14234
14235            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14236            let use_autoclose = this.use_autoclose;
14237            let use_auto_surround = this.use_auto_surround;
14238            this.set_use_autoclose(false);
14239            this.set_use_auto_surround(false);
14240            this.handle_input(text, cx);
14241            this.set_use_autoclose(use_autoclose);
14242            this.set_use_auto_surround(use_auto_surround);
14243
14244            if let Some(new_selected_range) = new_selected_range_utf16 {
14245                let snapshot = this.buffer.read(cx).read(cx);
14246                let new_selected_ranges = marked_ranges
14247                    .into_iter()
14248                    .map(|marked_range| {
14249                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14250                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14251                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14252                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14253                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14254                    })
14255                    .collect::<Vec<_>>();
14256
14257                drop(snapshot);
14258                this.change_selections(None, cx, |selections| {
14259                    selections.select_ranges(new_selected_ranges)
14260                });
14261            }
14262        });
14263
14264        self.ime_transaction = self.ime_transaction.or(transaction);
14265        if let Some(transaction) = self.ime_transaction {
14266            self.buffer.update(cx, |buffer, cx| {
14267                buffer.group_until_transaction(transaction, cx);
14268            });
14269        }
14270
14271        if self.text_highlights::<InputComposition>(cx).is_none() {
14272            self.ime_transaction.take();
14273        }
14274    }
14275
14276    fn bounds_for_range(
14277        &mut self,
14278        range_utf16: Range<usize>,
14279        element_bounds: gpui::Bounds<Pixels>,
14280        cx: &mut ViewContext<Self>,
14281    ) -> Option<gpui::Bounds<Pixels>> {
14282        let text_layout_details = self.text_layout_details(cx);
14283        let gpui::Point {
14284            x: em_width,
14285            y: line_height,
14286        } = self.character_size(cx);
14287
14288        let snapshot = self.snapshot(cx);
14289        let scroll_position = snapshot.scroll_position();
14290        let scroll_left = scroll_position.x * em_width;
14291
14292        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14293        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14294            + self.gutter_dimensions.width
14295            + self.gutter_dimensions.margin;
14296        let y = line_height * (start.row().as_f32() - scroll_position.y);
14297
14298        Some(Bounds {
14299            origin: element_bounds.origin + point(x, y),
14300            size: size(em_width, line_height),
14301        })
14302    }
14303}
14304
14305trait SelectionExt {
14306    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14307    fn spanned_rows(
14308        &self,
14309        include_end_if_at_line_start: bool,
14310        map: &DisplaySnapshot,
14311    ) -> Range<MultiBufferRow>;
14312}
14313
14314impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14315    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14316        let start = self
14317            .start
14318            .to_point(&map.buffer_snapshot)
14319            .to_display_point(map);
14320        let end = self
14321            .end
14322            .to_point(&map.buffer_snapshot)
14323            .to_display_point(map);
14324        if self.reversed {
14325            end..start
14326        } else {
14327            start..end
14328        }
14329    }
14330
14331    fn spanned_rows(
14332        &self,
14333        include_end_if_at_line_start: bool,
14334        map: &DisplaySnapshot,
14335    ) -> Range<MultiBufferRow> {
14336        let start = self.start.to_point(&map.buffer_snapshot);
14337        let mut end = self.end.to_point(&map.buffer_snapshot);
14338        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14339            end.row -= 1;
14340        }
14341
14342        let buffer_start = map.prev_line_boundary(start).0;
14343        let buffer_end = map.next_line_boundary(end).0;
14344        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14345    }
14346}
14347
14348impl<T: InvalidationRegion> InvalidationStack<T> {
14349    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14350    where
14351        S: Clone + ToOffset,
14352    {
14353        while let Some(region) = self.last() {
14354            let all_selections_inside_invalidation_ranges =
14355                if selections.len() == region.ranges().len() {
14356                    selections
14357                        .iter()
14358                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14359                        .all(|(selection, invalidation_range)| {
14360                            let head = selection.head().to_offset(buffer);
14361                            invalidation_range.start <= head && invalidation_range.end >= head
14362                        })
14363                } else {
14364                    false
14365                };
14366
14367            if all_selections_inside_invalidation_ranges {
14368                break;
14369            } else {
14370                self.pop();
14371            }
14372        }
14373    }
14374}
14375
14376impl<T> Default for InvalidationStack<T> {
14377    fn default() -> Self {
14378        Self(Default::default())
14379    }
14380}
14381
14382impl<T> Deref for InvalidationStack<T> {
14383    type Target = Vec<T>;
14384
14385    fn deref(&self) -> &Self::Target {
14386        &self.0
14387    }
14388}
14389
14390impl<T> DerefMut for InvalidationStack<T> {
14391    fn deref_mut(&mut self) -> &mut Self::Target {
14392        &mut self.0
14393    }
14394}
14395
14396impl InvalidationRegion for SnippetState {
14397    fn ranges(&self) -> &[Range<Anchor>] {
14398        &self.ranges[self.active_index]
14399    }
14400}
14401
14402pub fn diagnostic_block_renderer(
14403    diagnostic: Diagnostic,
14404    max_message_rows: Option<u8>,
14405    allow_closing: bool,
14406    _is_valid: bool,
14407) -> RenderBlock {
14408    let (text_without_backticks, code_ranges) =
14409        highlight_diagnostic_message(&diagnostic, max_message_rows);
14410
14411    Arc::new(move |cx: &mut BlockContext| {
14412        let group_id: SharedString = cx.block_id.to_string().into();
14413
14414        let mut text_style = cx.text_style().clone();
14415        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14416        let theme_settings = ThemeSettings::get_global(cx);
14417        text_style.font_family = theme_settings.buffer_font.family.clone();
14418        text_style.font_style = theme_settings.buffer_font.style;
14419        text_style.font_features = theme_settings.buffer_font.features.clone();
14420        text_style.font_weight = theme_settings.buffer_font.weight;
14421
14422        let multi_line_diagnostic = diagnostic.message.contains('\n');
14423
14424        let buttons = |diagnostic: &Diagnostic| {
14425            if multi_line_diagnostic {
14426                v_flex()
14427            } else {
14428                h_flex()
14429            }
14430            .when(allow_closing, |div| {
14431                div.children(diagnostic.is_primary.then(|| {
14432                    IconButton::new("close-block", IconName::XCircle)
14433                        .icon_color(Color::Muted)
14434                        .size(ButtonSize::Compact)
14435                        .style(ButtonStyle::Transparent)
14436                        .visible_on_hover(group_id.clone())
14437                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14438                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14439                }))
14440            })
14441            .child(
14442                IconButton::new("copy-block", IconName::Copy)
14443                    .icon_color(Color::Muted)
14444                    .size(ButtonSize::Compact)
14445                    .style(ButtonStyle::Transparent)
14446                    .visible_on_hover(group_id.clone())
14447                    .on_click({
14448                        let message = diagnostic.message.clone();
14449                        move |_click, cx| {
14450                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14451                        }
14452                    })
14453                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14454            )
14455        };
14456
14457        let icon_size = buttons(&diagnostic)
14458            .into_any_element()
14459            .layout_as_root(AvailableSpace::min_size(), cx);
14460
14461        h_flex()
14462            .id(cx.block_id)
14463            .group(group_id.clone())
14464            .relative()
14465            .size_full()
14466            .block_mouse_down()
14467            .pl(cx.gutter_dimensions.width)
14468            .w(cx.max_width - cx.gutter_dimensions.full_width())
14469            .child(
14470                div()
14471                    .flex()
14472                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14473                    .flex_shrink(),
14474            )
14475            .child(buttons(&diagnostic))
14476            .child(div().flex().flex_shrink_0().child(
14477                StyledText::new(text_without_backticks.clone()).with_highlights(
14478                    &text_style,
14479                    code_ranges.iter().map(|range| {
14480                        (
14481                            range.clone(),
14482                            HighlightStyle {
14483                                font_weight: Some(FontWeight::BOLD),
14484                                ..Default::default()
14485                            },
14486                        )
14487                    }),
14488                ),
14489            ))
14490            .into_any_element()
14491    })
14492}
14493
14494pub fn highlight_diagnostic_message(
14495    diagnostic: &Diagnostic,
14496    mut max_message_rows: Option<u8>,
14497) -> (SharedString, Vec<Range<usize>>) {
14498    let mut text_without_backticks = String::new();
14499    let mut code_ranges = Vec::new();
14500
14501    if let Some(source) = &diagnostic.source {
14502        text_without_backticks.push_str(source);
14503        code_ranges.push(0..source.len());
14504        text_without_backticks.push_str(": ");
14505    }
14506
14507    let mut prev_offset = 0;
14508    let mut in_code_block = false;
14509    let has_row_limit = max_message_rows.is_some();
14510    let mut newline_indices = diagnostic
14511        .message
14512        .match_indices('\n')
14513        .filter(|_| has_row_limit)
14514        .map(|(ix, _)| ix)
14515        .fuse()
14516        .peekable();
14517
14518    for (quote_ix, _) in diagnostic
14519        .message
14520        .match_indices('`')
14521        .chain([(diagnostic.message.len(), "")])
14522    {
14523        let mut first_newline_ix = None;
14524        let mut last_newline_ix = None;
14525        while let Some(newline_ix) = newline_indices.peek() {
14526            if *newline_ix < quote_ix {
14527                if first_newline_ix.is_none() {
14528                    first_newline_ix = Some(*newline_ix);
14529                }
14530                last_newline_ix = Some(*newline_ix);
14531
14532                if let Some(rows_left) = &mut max_message_rows {
14533                    if *rows_left == 0 {
14534                        break;
14535                    } else {
14536                        *rows_left -= 1;
14537                    }
14538                }
14539                let _ = newline_indices.next();
14540            } else {
14541                break;
14542            }
14543        }
14544        let prev_len = text_without_backticks.len();
14545        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14546        text_without_backticks.push_str(new_text);
14547        if in_code_block {
14548            code_ranges.push(prev_len..text_without_backticks.len());
14549        }
14550        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14551        in_code_block = !in_code_block;
14552        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14553            text_without_backticks.push_str("...");
14554            break;
14555        }
14556    }
14557
14558    (text_without_backticks.into(), code_ranges)
14559}
14560
14561fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14562    match severity {
14563        DiagnosticSeverity::ERROR => colors.error,
14564        DiagnosticSeverity::WARNING => colors.warning,
14565        DiagnosticSeverity::INFORMATION => colors.info,
14566        DiagnosticSeverity::HINT => colors.info,
14567        _ => colors.ignored,
14568    }
14569}
14570
14571pub fn styled_runs_for_code_label<'a>(
14572    label: &'a CodeLabel,
14573    syntax_theme: &'a theme::SyntaxTheme,
14574) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14575    let fade_out = HighlightStyle {
14576        fade_out: Some(0.35),
14577        ..Default::default()
14578    };
14579
14580    let mut prev_end = label.filter_range.end;
14581    label
14582        .runs
14583        .iter()
14584        .enumerate()
14585        .flat_map(move |(ix, (range, highlight_id))| {
14586            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14587                style
14588            } else {
14589                return Default::default();
14590            };
14591            let mut muted_style = style;
14592            muted_style.highlight(fade_out);
14593
14594            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14595            if range.start >= label.filter_range.end {
14596                if range.start > prev_end {
14597                    runs.push((prev_end..range.start, fade_out));
14598                }
14599                runs.push((range.clone(), muted_style));
14600            } else if range.end <= label.filter_range.end {
14601                runs.push((range.clone(), style));
14602            } else {
14603                runs.push((range.start..label.filter_range.end, style));
14604                runs.push((label.filter_range.end..range.end, muted_style));
14605            }
14606            prev_end = cmp::max(prev_end, range.end);
14607
14608            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14609                runs.push((prev_end..label.text.len(), fade_out));
14610            }
14611
14612            runs
14613        })
14614}
14615
14616pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14617    let mut prev_index = 0;
14618    let mut prev_codepoint: Option<char> = None;
14619    text.char_indices()
14620        .chain([(text.len(), '\0')])
14621        .filter_map(move |(index, codepoint)| {
14622            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14623            let is_boundary = index == text.len()
14624                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14625                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14626            if is_boundary {
14627                let chunk = &text[prev_index..index];
14628                prev_index = index;
14629                Some(chunk)
14630            } else {
14631                None
14632            }
14633        })
14634}
14635
14636pub trait RangeToAnchorExt: Sized {
14637    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14638
14639    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14640        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14641        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14642    }
14643}
14644
14645impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14646    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14647        let start_offset = self.start.to_offset(snapshot);
14648        let end_offset = self.end.to_offset(snapshot);
14649        if start_offset == end_offset {
14650            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14651        } else {
14652            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14653        }
14654    }
14655}
14656
14657pub trait RowExt {
14658    fn as_f32(&self) -> f32;
14659
14660    fn next_row(&self) -> Self;
14661
14662    fn previous_row(&self) -> Self;
14663
14664    fn minus(&self, other: Self) -> u32;
14665}
14666
14667impl RowExt for DisplayRow {
14668    fn as_f32(&self) -> f32 {
14669        self.0 as f32
14670    }
14671
14672    fn next_row(&self) -> Self {
14673        Self(self.0 + 1)
14674    }
14675
14676    fn previous_row(&self) -> Self {
14677        Self(self.0.saturating_sub(1))
14678    }
14679
14680    fn minus(&self, other: Self) -> u32 {
14681        self.0 - other.0
14682    }
14683}
14684
14685impl RowExt for MultiBufferRow {
14686    fn as_f32(&self) -> f32 {
14687        self.0 as f32
14688    }
14689
14690    fn next_row(&self) -> Self {
14691        Self(self.0 + 1)
14692    }
14693
14694    fn previous_row(&self) -> Self {
14695        Self(self.0.saturating_sub(1))
14696    }
14697
14698    fn minus(&self, other: Self) -> u32 {
14699        self.0 - other.0
14700    }
14701}
14702
14703trait RowRangeExt {
14704    type Row;
14705
14706    fn len(&self) -> usize;
14707
14708    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14709}
14710
14711impl RowRangeExt for Range<MultiBufferRow> {
14712    type Row = MultiBufferRow;
14713
14714    fn len(&self) -> usize {
14715        (self.end.0 - self.start.0) as usize
14716    }
14717
14718    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14719        (self.start.0..self.end.0).map(MultiBufferRow)
14720    }
14721}
14722
14723impl RowRangeExt for Range<DisplayRow> {
14724    type Row = DisplayRow;
14725
14726    fn len(&self) -> usize {
14727        (self.end.0 - self.start.0) as usize
14728    }
14729
14730    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14731        (self.start.0..self.end.0).map(DisplayRow)
14732    }
14733}
14734
14735fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14736    if hunk.diff_base_byte_range.is_empty() {
14737        DiffHunkStatus::Added
14738    } else if hunk.row_range.is_empty() {
14739        DiffHunkStatus::Removed
14740    } else {
14741        DiffHunkStatus::Modified
14742    }
14743}
14744
14745/// If select range has more than one line, we
14746/// just point the cursor to range.start.
14747fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14748    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14749        range
14750    } else {
14751        range.start..range.start
14752    }
14753}
14754
14755pub struct KillRing(ClipboardItem);
14756impl Global for KillRing {}
14757
14758const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);