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(), Default::default(), 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        if self.context_menu_visible() {
 1386            match self.context_menu.borrow().as_ref() {
 1387                Some(CodeContextMenu::Completions(_)) => {
 1388                    key_context.add("menu");
 1389                    key_context.add("showing_completions")
 1390                }
 1391                Some(CodeContextMenu::CodeActions(_)) => {
 1392                    key_context.add("menu");
 1393                    key_context.add("showing_code_actions")
 1394                }
 1395                None => {}
 1396            }
 1397        }
 1398
 1399        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1400        if !self.focus_handle(cx).contains_focused(cx)
 1401            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1402        {
 1403            for addon in self.addons.values() {
 1404                addon.extend_key_context(&mut key_context, cx)
 1405            }
 1406        }
 1407
 1408        if let Some(extension) = self
 1409            .buffer
 1410            .read(cx)
 1411            .as_singleton()
 1412            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1413        {
 1414            key_context.set("extension", extension.to_string());
 1415        }
 1416
 1417        if self.has_active_inline_completion() {
 1418            key_context.add("copilot_suggestion");
 1419            key_context.add("inline_completion");
 1420        }
 1421
 1422        if !self
 1423            .selections
 1424            .disjoint
 1425            .iter()
 1426            .all(|selection| selection.start == selection.end)
 1427        {
 1428            key_context.add("selection");
 1429        }
 1430
 1431        key_context
 1432    }
 1433
 1434    pub fn new_file(
 1435        workspace: &mut Workspace,
 1436        _: &workspace::NewFile,
 1437        cx: &mut ViewContext<Workspace>,
 1438    ) {
 1439        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1440            "Failed to create buffer",
 1441            cx,
 1442            |e, _| match e.error_code() {
 1443                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1444                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1445                e.error_tag("required").unwrap_or("the latest version")
 1446            )),
 1447                _ => None,
 1448            },
 1449        );
 1450    }
 1451
 1452    pub fn new_in_workspace(
 1453        workspace: &mut Workspace,
 1454        cx: &mut ViewContext<Workspace>,
 1455    ) -> Task<Result<View<Editor>>> {
 1456        let project = workspace.project().clone();
 1457        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1458
 1459        cx.spawn(|workspace, mut cx| async move {
 1460            let buffer = create.await?;
 1461            workspace.update(&mut cx, |workspace, cx| {
 1462                let editor =
 1463                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1464                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1465                editor
 1466            })
 1467        })
 1468    }
 1469
 1470    fn new_file_vertical(
 1471        workspace: &mut Workspace,
 1472        _: &workspace::NewFileSplitVertical,
 1473        cx: &mut ViewContext<Workspace>,
 1474    ) {
 1475        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1476    }
 1477
 1478    fn new_file_horizontal(
 1479        workspace: &mut Workspace,
 1480        _: &workspace::NewFileSplitHorizontal,
 1481        cx: &mut ViewContext<Workspace>,
 1482    ) {
 1483        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1484    }
 1485
 1486    fn new_file_in_direction(
 1487        workspace: &mut Workspace,
 1488        direction: SplitDirection,
 1489        cx: &mut ViewContext<Workspace>,
 1490    ) {
 1491        let project = workspace.project().clone();
 1492        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1493
 1494        cx.spawn(|workspace, mut cx| async move {
 1495            let buffer = create.await?;
 1496            workspace.update(&mut cx, move |workspace, cx| {
 1497                workspace.split_item(
 1498                    direction,
 1499                    Box::new(
 1500                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1501                    ),
 1502                    cx,
 1503                )
 1504            })?;
 1505            anyhow::Ok(())
 1506        })
 1507        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1508            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1509                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1510                e.error_tag("required").unwrap_or("the latest version")
 1511            )),
 1512            _ => None,
 1513        });
 1514    }
 1515
 1516    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1517        self.leader_peer_id
 1518    }
 1519
 1520    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1521        &self.buffer
 1522    }
 1523
 1524    pub fn workspace(&self) -> Option<View<Workspace>> {
 1525        self.workspace.as_ref()?.0.upgrade()
 1526    }
 1527
 1528    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1529        self.buffer().read(cx).title(cx)
 1530    }
 1531
 1532    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1533        let git_blame_gutter_max_author_length = self
 1534            .render_git_blame_gutter(cx)
 1535            .then(|| {
 1536                if let Some(blame) = self.blame.as_ref() {
 1537                    let max_author_length =
 1538                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1539                    Some(max_author_length)
 1540                } else {
 1541                    None
 1542                }
 1543            })
 1544            .flatten();
 1545
 1546        EditorSnapshot {
 1547            mode: self.mode,
 1548            show_gutter: self.show_gutter,
 1549            show_line_numbers: self.show_line_numbers,
 1550            show_git_diff_gutter: self.show_git_diff_gutter,
 1551            show_code_actions: self.show_code_actions,
 1552            show_runnables: self.show_runnables,
 1553            git_blame_gutter_max_author_length,
 1554            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1555            scroll_anchor: self.scroll_manager.anchor(),
 1556            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1557            placeholder_text: self.placeholder_text.clone(),
 1558            diff_map: self.diff_map.snapshot(),
 1559            is_focused: self.focus_handle.is_focused(cx),
 1560            current_line_highlight: self
 1561                .current_line_highlight
 1562                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1563            gutter_hovered: self.gutter_hovered,
 1564        }
 1565    }
 1566
 1567    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1568        self.buffer.read(cx).language_at(point, cx)
 1569    }
 1570
 1571    pub fn file_at<T: ToOffset>(
 1572        &self,
 1573        point: T,
 1574        cx: &AppContext,
 1575    ) -> Option<Arc<dyn language::File>> {
 1576        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1577    }
 1578
 1579    pub fn active_excerpt(
 1580        &self,
 1581        cx: &AppContext,
 1582    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1583        self.buffer
 1584            .read(cx)
 1585            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1586    }
 1587
 1588    pub fn mode(&self) -> EditorMode {
 1589        self.mode
 1590    }
 1591
 1592    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1593        self.collaboration_hub.as_deref()
 1594    }
 1595
 1596    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1597        self.collaboration_hub = Some(hub);
 1598    }
 1599
 1600    pub fn set_custom_context_menu(
 1601        &mut self,
 1602        f: impl 'static
 1603            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1604    ) {
 1605        self.custom_context_menu = Some(Box::new(f))
 1606    }
 1607
 1608    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1609        self.completion_provider = provider;
 1610    }
 1611
 1612    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1613        self.semantics_provider.clone()
 1614    }
 1615
 1616    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1617        self.semantics_provider = provider;
 1618    }
 1619
 1620    pub fn set_inline_completion_provider<T>(
 1621        &mut self,
 1622        provider: Option<Model<T>>,
 1623        cx: &mut ViewContext<Self>,
 1624    ) where
 1625        T: InlineCompletionProvider,
 1626    {
 1627        self.inline_completion_provider =
 1628            provider.map(|provider| RegisteredInlineCompletionProvider {
 1629                _subscription: cx.observe(&provider, |this, _, cx| {
 1630                    if this.focus_handle.is_focused(cx) {
 1631                        this.update_visible_inline_completion(cx);
 1632                    }
 1633                }),
 1634                provider: Arc::new(provider),
 1635            });
 1636        self.refresh_inline_completion(false, false, cx);
 1637    }
 1638
 1639    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1640        self.placeholder_text.as_deref()
 1641    }
 1642
 1643    pub fn set_placeholder_text(
 1644        &mut self,
 1645        placeholder_text: impl Into<Arc<str>>,
 1646        cx: &mut ViewContext<Self>,
 1647    ) {
 1648        let placeholder_text = Some(placeholder_text.into());
 1649        if self.placeholder_text != placeholder_text {
 1650            self.placeholder_text = placeholder_text;
 1651            cx.notify();
 1652        }
 1653    }
 1654
 1655    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1656        self.cursor_shape = cursor_shape;
 1657
 1658        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1659        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1660
 1661        cx.notify();
 1662    }
 1663
 1664    pub fn set_current_line_highlight(
 1665        &mut self,
 1666        current_line_highlight: Option<CurrentLineHighlight>,
 1667    ) {
 1668        self.current_line_highlight = current_line_highlight;
 1669    }
 1670
 1671    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1672        self.collapse_matches = collapse_matches;
 1673    }
 1674
 1675    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1676        let buffers = self.buffer.read(cx).all_buffers();
 1677        let Some(lsp_store) = self.lsp_store(cx) else {
 1678            return;
 1679        };
 1680        lsp_store.update(cx, |lsp_store, cx| {
 1681            for buffer in buffers {
 1682                self.registered_buffers
 1683                    .entry(buffer.read(cx).remote_id())
 1684                    .or_insert_with(|| {
 1685                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1686                    });
 1687            }
 1688        })
 1689    }
 1690
 1691    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1692        if self.collapse_matches {
 1693            return range.start..range.start;
 1694        }
 1695        range.clone()
 1696    }
 1697
 1698    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1699        if self.display_map.read(cx).clip_at_line_ends != clip {
 1700            self.display_map
 1701                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1702        }
 1703    }
 1704
 1705    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1706        self.input_enabled = input_enabled;
 1707    }
 1708
 1709    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1710        self.enable_inline_completions = enabled;
 1711    }
 1712
 1713    pub fn set_autoindent(&mut self, autoindent: bool) {
 1714        if autoindent {
 1715            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1716        } else {
 1717            self.autoindent_mode = None;
 1718        }
 1719    }
 1720
 1721    pub fn read_only(&self, cx: &AppContext) -> bool {
 1722        self.read_only || self.buffer.read(cx).read_only()
 1723    }
 1724
 1725    pub fn set_read_only(&mut self, read_only: bool) {
 1726        self.read_only = read_only;
 1727    }
 1728
 1729    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1730        self.use_autoclose = autoclose;
 1731    }
 1732
 1733    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1734        self.use_auto_surround = auto_surround;
 1735    }
 1736
 1737    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1738        self.auto_replace_emoji_shortcode = auto_replace;
 1739    }
 1740
 1741    pub fn toggle_inline_completions(
 1742        &mut self,
 1743        _: &ToggleInlineCompletions,
 1744        cx: &mut ViewContext<Self>,
 1745    ) {
 1746        if self.show_inline_completions_override.is_some() {
 1747            self.set_show_inline_completions(None, cx);
 1748        } else {
 1749            let cursor = self.selections.newest_anchor().head();
 1750            if let Some((buffer, cursor_buffer_position)) =
 1751                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1752            {
 1753                let show_inline_completions =
 1754                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1755                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1756            }
 1757        }
 1758    }
 1759
 1760    pub fn set_show_inline_completions(
 1761        &mut self,
 1762        show_inline_completions: Option<bool>,
 1763        cx: &mut ViewContext<Self>,
 1764    ) {
 1765        self.show_inline_completions_override = show_inline_completions;
 1766        self.refresh_inline_completion(false, true, cx);
 1767    }
 1768
 1769    fn should_show_inline_completions(
 1770        &self,
 1771        buffer: &Model<Buffer>,
 1772        buffer_position: language::Anchor,
 1773        cx: &AppContext,
 1774    ) -> bool {
 1775        if !self.snippet_stack.is_empty() {
 1776            return false;
 1777        }
 1778
 1779        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1780            return false;
 1781        }
 1782
 1783        if let Some(provider) = self.inline_completion_provider() {
 1784            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1785                show_inline_completions
 1786            } else {
 1787                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1788            }
 1789        } else {
 1790            false
 1791        }
 1792    }
 1793
 1794    fn inline_completions_disabled_in_scope(
 1795        &self,
 1796        buffer: &Model<Buffer>,
 1797        buffer_position: language::Anchor,
 1798        cx: &AppContext,
 1799    ) -> bool {
 1800        let snapshot = buffer.read(cx).snapshot();
 1801        let settings = snapshot.settings_at(buffer_position, cx);
 1802
 1803        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1804            return false;
 1805        };
 1806
 1807        scope.override_name().map_or(false, |scope_name| {
 1808            settings
 1809                .inline_completions_disabled_in
 1810                .iter()
 1811                .any(|s| s == scope_name)
 1812        })
 1813    }
 1814
 1815    pub fn set_use_modal_editing(&mut self, to: bool) {
 1816        self.use_modal_editing = to;
 1817    }
 1818
 1819    pub fn use_modal_editing(&self) -> bool {
 1820        self.use_modal_editing
 1821    }
 1822
 1823    fn selections_did_change(
 1824        &mut self,
 1825        local: bool,
 1826        old_cursor_position: &Anchor,
 1827        show_completions: bool,
 1828        cx: &mut ViewContext<Self>,
 1829    ) {
 1830        cx.invalidate_character_coordinates();
 1831
 1832        // Copy selections to primary selection buffer
 1833        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1834        if local {
 1835            let selections = self.selections.all::<usize>(cx);
 1836            let buffer_handle = self.buffer.read(cx).read(cx);
 1837
 1838            let mut text = String::new();
 1839            for (index, selection) in selections.iter().enumerate() {
 1840                let text_for_selection = buffer_handle
 1841                    .text_for_range(selection.start..selection.end)
 1842                    .collect::<String>();
 1843
 1844                text.push_str(&text_for_selection);
 1845                if index != selections.len() - 1 {
 1846                    text.push('\n');
 1847                }
 1848            }
 1849
 1850            if !text.is_empty() {
 1851                cx.write_to_primary(ClipboardItem::new_string(text));
 1852            }
 1853        }
 1854
 1855        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1856            self.buffer.update(cx, |buffer, cx| {
 1857                buffer.set_active_selections(
 1858                    &self.selections.disjoint_anchors(),
 1859                    self.selections.line_mode,
 1860                    self.cursor_shape,
 1861                    cx,
 1862                )
 1863            });
 1864        }
 1865        let display_map = self
 1866            .display_map
 1867            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1868        let buffer = &display_map.buffer_snapshot;
 1869        self.add_selections_state = None;
 1870        self.select_next_state = None;
 1871        self.select_prev_state = None;
 1872        self.select_larger_syntax_node_stack.clear();
 1873        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1874        self.snippet_stack
 1875            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1876        self.take_rename(false, cx);
 1877
 1878        let new_cursor_position = self.selections.newest_anchor().head();
 1879
 1880        self.push_to_nav_history(
 1881            *old_cursor_position,
 1882            Some(new_cursor_position.to_point(buffer)),
 1883            cx,
 1884        );
 1885
 1886        if local {
 1887            let new_cursor_position = self.selections.newest_anchor().head();
 1888            let mut context_menu = self.context_menu.borrow_mut();
 1889            let completion_menu = match context_menu.as_ref() {
 1890                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1891                _ => {
 1892                    *context_menu = None;
 1893                    None
 1894                }
 1895            };
 1896
 1897            if let Some(completion_menu) = completion_menu {
 1898                let cursor_position = new_cursor_position.to_offset(buffer);
 1899                let (word_range, kind) =
 1900                    buffer.surrounding_word(completion_menu.initial_position, true);
 1901                if kind == Some(CharKind::Word)
 1902                    && word_range.to_inclusive().contains(&cursor_position)
 1903                {
 1904                    let mut completion_menu = completion_menu.clone();
 1905                    drop(context_menu);
 1906
 1907                    let query = Self::completion_query(buffer, cursor_position);
 1908                    cx.spawn(move |this, mut cx| async move {
 1909                        completion_menu
 1910                            .filter(query.as_deref(), cx.background_executor().clone())
 1911                            .await;
 1912
 1913                        this.update(&mut cx, |this, cx| {
 1914                            let mut context_menu = this.context_menu.borrow_mut();
 1915                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1916                            else {
 1917                                return;
 1918                            };
 1919
 1920                            if menu.id > completion_menu.id {
 1921                                return;
 1922                            }
 1923
 1924                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1925                            drop(context_menu);
 1926                            cx.notify();
 1927                        })
 1928                    })
 1929                    .detach();
 1930
 1931                    if show_completions {
 1932                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1933                    }
 1934                } else {
 1935                    drop(context_menu);
 1936                    self.hide_context_menu(cx);
 1937                }
 1938            } else {
 1939                drop(context_menu);
 1940            }
 1941
 1942            hide_hover(self, cx);
 1943
 1944            if old_cursor_position.to_display_point(&display_map).row()
 1945                != new_cursor_position.to_display_point(&display_map).row()
 1946            {
 1947                self.available_code_actions.take();
 1948            }
 1949            self.refresh_code_actions(cx);
 1950            self.refresh_document_highlights(cx);
 1951            refresh_matching_bracket_highlights(self, cx);
 1952            self.update_visible_inline_completion(cx);
 1953            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1954            if self.git_blame_inline_enabled {
 1955                self.start_inline_blame_timer(cx);
 1956            }
 1957        }
 1958
 1959        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1960        cx.emit(EditorEvent::SelectionsChanged { local });
 1961
 1962        if self.selections.disjoint_anchors().len() == 1 {
 1963            cx.emit(SearchEvent::ActiveMatchChanged)
 1964        }
 1965        cx.notify();
 1966    }
 1967
 1968    pub fn change_selections<R>(
 1969        &mut self,
 1970        autoscroll: Option<Autoscroll>,
 1971        cx: &mut ViewContext<Self>,
 1972        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1973    ) -> R {
 1974        self.change_selections_inner(autoscroll, true, cx, change)
 1975    }
 1976
 1977    pub fn change_selections_inner<R>(
 1978        &mut self,
 1979        autoscroll: Option<Autoscroll>,
 1980        request_completions: bool,
 1981        cx: &mut ViewContext<Self>,
 1982        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1983    ) -> R {
 1984        let old_cursor_position = self.selections.newest_anchor().head();
 1985        self.push_to_selection_history();
 1986
 1987        let (changed, result) = self.selections.change_with(cx, change);
 1988
 1989        if changed {
 1990            if let Some(autoscroll) = autoscroll {
 1991                self.request_autoscroll(autoscroll, cx);
 1992            }
 1993            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 1994
 1995            if self.should_open_signature_help_automatically(
 1996                &old_cursor_position,
 1997                self.signature_help_state.backspace_pressed(),
 1998                cx,
 1999            ) {
 2000                self.show_signature_help(&ShowSignatureHelp, cx);
 2001            }
 2002            self.signature_help_state.set_backspace_pressed(false);
 2003        }
 2004
 2005        result
 2006    }
 2007
 2008    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2009    where
 2010        I: IntoIterator<Item = (Range<S>, T)>,
 2011        S: ToOffset,
 2012        T: Into<Arc<str>>,
 2013    {
 2014        if self.read_only(cx) {
 2015            return;
 2016        }
 2017
 2018        self.buffer
 2019            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2020    }
 2021
 2022    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2023    where
 2024        I: IntoIterator<Item = (Range<S>, T)>,
 2025        S: ToOffset,
 2026        T: Into<Arc<str>>,
 2027    {
 2028        if self.read_only(cx) {
 2029            return;
 2030        }
 2031
 2032        self.buffer.update(cx, |buffer, cx| {
 2033            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2034        });
 2035    }
 2036
 2037    pub fn edit_with_block_indent<I, S, T>(
 2038        &mut self,
 2039        edits: I,
 2040        original_indent_columns: Vec<u32>,
 2041        cx: &mut ViewContext<Self>,
 2042    ) where
 2043        I: IntoIterator<Item = (Range<S>, T)>,
 2044        S: ToOffset,
 2045        T: Into<Arc<str>>,
 2046    {
 2047        if self.read_only(cx) {
 2048            return;
 2049        }
 2050
 2051        self.buffer.update(cx, |buffer, cx| {
 2052            buffer.edit(
 2053                edits,
 2054                Some(AutoindentMode::Block {
 2055                    original_indent_columns,
 2056                }),
 2057                cx,
 2058            )
 2059        });
 2060    }
 2061
 2062    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2063        self.hide_context_menu(cx);
 2064
 2065        match phase {
 2066            SelectPhase::Begin {
 2067                position,
 2068                add,
 2069                click_count,
 2070            } => self.begin_selection(position, add, click_count, cx),
 2071            SelectPhase::BeginColumnar {
 2072                position,
 2073                goal_column,
 2074                reset,
 2075            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2076            SelectPhase::Extend {
 2077                position,
 2078                click_count,
 2079            } => self.extend_selection(position, click_count, cx),
 2080            SelectPhase::Update {
 2081                position,
 2082                goal_column,
 2083                scroll_delta,
 2084            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2085            SelectPhase::End => self.end_selection(cx),
 2086        }
 2087    }
 2088
 2089    fn extend_selection(
 2090        &mut self,
 2091        position: DisplayPoint,
 2092        click_count: usize,
 2093        cx: &mut ViewContext<Self>,
 2094    ) {
 2095        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2096        let tail = self.selections.newest::<usize>(cx).tail();
 2097        self.begin_selection(position, false, click_count, cx);
 2098
 2099        let position = position.to_offset(&display_map, Bias::Left);
 2100        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2101
 2102        let mut pending_selection = self
 2103            .selections
 2104            .pending_anchor()
 2105            .expect("extend_selection not called with pending selection");
 2106        if position >= tail {
 2107            pending_selection.start = tail_anchor;
 2108        } else {
 2109            pending_selection.end = tail_anchor;
 2110            pending_selection.reversed = true;
 2111        }
 2112
 2113        let mut pending_mode = self.selections.pending_mode().unwrap();
 2114        match &mut pending_mode {
 2115            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2116            _ => {}
 2117        }
 2118
 2119        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2120            s.set_pending(pending_selection, pending_mode)
 2121        });
 2122    }
 2123
 2124    fn begin_selection(
 2125        &mut self,
 2126        position: DisplayPoint,
 2127        add: bool,
 2128        click_count: usize,
 2129        cx: &mut ViewContext<Self>,
 2130    ) {
 2131        if !self.focus_handle.is_focused(cx) {
 2132            self.last_focused_descendant = None;
 2133            cx.focus(&self.focus_handle);
 2134        }
 2135
 2136        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2137        let buffer = &display_map.buffer_snapshot;
 2138        let newest_selection = self.selections.newest_anchor().clone();
 2139        let position = display_map.clip_point(position, Bias::Left);
 2140
 2141        let start;
 2142        let end;
 2143        let mode;
 2144        let mut auto_scroll;
 2145        match click_count {
 2146            1 => {
 2147                start = buffer.anchor_before(position.to_point(&display_map));
 2148                end = start;
 2149                mode = SelectMode::Character;
 2150                auto_scroll = true;
 2151            }
 2152            2 => {
 2153                let range = movement::surrounding_word(&display_map, position);
 2154                start = buffer.anchor_before(range.start.to_point(&display_map));
 2155                end = buffer.anchor_before(range.end.to_point(&display_map));
 2156                mode = SelectMode::Word(start..end);
 2157                auto_scroll = true;
 2158            }
 2159            3 => {
 2160                let position = display_map
 2161                    .clip_point(position, Bias::Left)
 2162                    .to_point(&display_map);
 2163                let line_start = display_map.prev_line_boundary(position).0;
 2164                let next_line_start = buffer.clip_point(
 2165                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2166                    Bias::Left,
 2167                );
 2168                start = buffer.anchor_before(line_start);
 2169                end = buffer.anchor_before(next_line_start);
 2170                mode = SelectMode::Line(start..end);
 2171                auto_scroll = true;
 2172            }
 2173            _ => {
 2174                start = buffer.anchor_before(0);
 2175                end = buffer.anchor_before(buffer.len());
 2176                mode = SelectMode::All;
 2177                auto_scroll = false;
 2178            }
 2179        }
 2180        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2181
 2182        let point_to_delete: Option<usize> = {
 2183            let selected_points: Vec<Selection<Point>> =
 2184                self.selections.disjoint_in_range(start..end, cx);
 2185
 2186            if !add || click_count > 1 {
 2187                None
 2188            } else if !selected_points.is_empty() {
 2189                Some(selected_points[0].id)
 2190            } else {
 2191                let clicked_point_already_selected =
 2192                    self.selections.disjoint.iter().find(|selection| {
 2193                        selection.start.to_point(buffer) == start.to_point(buffer)
 2194                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2195                    });
 2196
 2197                clicked_point_already_selected.map(|selection| selection.id)
 2198            }
 2199        };
 2200
 2201        let selections_count = self.selections.count();
 2202
 2203        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2204            if let Some(point_to_delete) = point_to_delete {
 2205                s.delete(point_to_delete);
 2206
 2207                if selections_count == 1 {
 2208                    s.set_pending_anchor_range(start..end, mode);
 2209                }
 2210            } else {
 2211                if !add {
 2212                    s.clear_disjoint();
 2213                } else if click_count > 1 {
 2214                    s.delete(newest_selection.id)
 2215                }
 2216
 2217                s.set_pending_anchor_range(start..end, mode);
 2218            }
 2219        });
 2220    }
 2221
 2222    fn begin_columnar_selection(
 2223        &mut self,
 2224        position: DisplayPoint,
 2225        goal_column: u32,
 2226        reset: bool,
 2227        cx: &mut ViewContext<Self>,
 2228    ) {
 2229        if !self.focus_handle.is_focused(cx) {
 2230            self.last_focused_descendant = None;
 2231            cx.focus(&self.focus_handle);
 2232        }
 2233
 2234        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2235
 2236        if reset {
 2237            let pointer_position = display_map
 2238                .buffer_snapshot
 2239                .anchor_before(position.to_point(&display_map));
 2240
 2241            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2242                s.clear_disjoint();
 2243                s.set_pending_anchor_range(
 2244                    pointer_position..pointer_position,
 2245                    SelectMode::Character,
 2246                );
 2247            });
 2248        }
 2249
 2250        let tail = self.selections.newest::<Point>(cx).tail();
 2251        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2252
 2253        if !reset {
 2254            self.select_columns(
 2255                tail.to_display_point(&display_map),
 2256                position,
 2257                goal_column,
 2258                &display_map,
 2259                cx,
 2260            );
 2261        }
 2262    }
 2263
 2264    fn update_selection(
 2265        &mut self,
 2266        position: DisplayPoint,
 2267        goal_column: u32,
 2268        scroll_delta: gpui::Point<f32>,
 2269        cx: &mut ViewContext<Self>,
 2270    ) {
 2271        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2272
 2273        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2274            let tail = tail.to_display_point(&display_map);
 2275            self.select_columns(tail, position, goal_column, &display_map, cx);
 2276        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2277            let buffer = self.buffer.read(cx).snapshot(cx);
 2278            let head;
 2279            let tail;
 2280            let mode = self.selections.pending_mode().unwrap();
 2281            match &mode {
 2282                SelectMode::Character => {
 2283                    head = position.to_point(&display_map);
 2284                    tail = pending.tail().to_point(&buffer);
 2285                }
 2286                SelectMode::Word(original_range) => {
 2287                    let original_display_range = original_range.start.to_display_point(&display_map)
 2288                        ..original_range.end.to_display_point(&display_map);
 2289                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2290                        ..original_display_range.end.to_point(&display_map);
 2291                    if movement::is_inside_word(&display_map, position)
 2292                        || original_display_range.contains(&position)
 2293                    {
 2294                        let word_range = movement::surrounding_word(&display_map, position);
 2295                        if word_range.start < original_display_range.start {
 2296                            head = word_range.start.to_point(&display_map);
 2297                        } else {
 2298                            head = word_range.end.to_point(&display_map);
 2299                        }
 2300                    } else {
 2301                        head = position.to_point(&display_map);
 2302                    }
 2303
 2304                    if head <= original_buffer_range.start {
 2305                        tail = original_buffer_range.end;
 2306                    } else {
 2307                        tail = original_buffer_range.start;
 2308                    }
 2309                }
 2310                SelectMode::Line(original_range) => {
 2311                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2312
 2313                    let position = display_map
 2314                        .clip_point(position, Bias::Left)
 2315                        .to_point(&display_map);
 2316                    let line_start = display_map.prev_line_boundary(position).0;
 2317                    let next_line_start = buffer.clip_point(
 2318                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2319                        Bias::Left,
 2320                    );
 2321
 2322                    if line_start < original_range.start {
 2323                        head = line_start
 2324                    } else {
 2325                        head = next_line_start
 2326                    }
 2327
 2328                    if head <= original_range.start {
 2329                        tail = original_range.end;
 2330                    } else {
 2331                        tail = original_range.start;
 2332                    }
 2333                }
 2334                SelectMode::All => {
 2335                    return;
 2336                }
 2337            };
 2338
 2339            if head < tail {
 2340                pending.start = buffer.anchor_before(head);
 2341                pending.end = buffer.anchor_before(tail);
 2342                pending.reversed = true;
 2343            } else {
 2344                pending.start = buffer.anchor_before(tail);
 2345                pending.end = buffer.anchor_before(head);
 2346                pending.reversed = false;
 2347            }
 2348
 2349            self.change_selections(None, cx, |s| {
 2350                s.set_pending(pending, mode);
 2351            });
 2352        } else {
 2353            log::error!("update_selection dispatched with no pending selection");
 2354            return;
 2355        }
 2356
 2357        self.apply_scroll_delta(scroll_delta, cx);
 2358        cx.notify();
 2359    }
 2360
 2361    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2362        self.columnar_selection_tail.take();
 2363        if self.selections.pending_anchor().is_some() {
 2364            let selections = self.selections.all::<usize>(cx);
 2365            self.change_selections(None, cx, |s| {
 2366                s.select(selections);
 2367                s.clear_pending();
 2368            });
 2369        }
 2370    }
 2371
 2372    fn select_columns(
 2373        &mut self,
 2374        tail: DisplayPoint,
 2375        head: DisplayPoint,
 2376        goal_column: u32,
 2377        display_map: &DisplaySnapshot,
 2378        cx: &mut ViewContext<Self>,
 2379    ) {
 2380        let start_row = cmp::min(tail.row(), head.row());
 2381        let end_row = cmp::max(tail.row(), head.row());
 2382        let start_column = cmp::min(tail.column(), goal_column);
 2383        let end_column = cmp::max(tail.column(), goal_column);
 2384        let reversed = start_column < tail.column();
 2385
 2386        let selection_ranges = (start_row.0..=end_row.0)
 2387            .map(DisplayRow)
 2388            .filter_map(|row| {
 2389                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2390                    let start = display_map
 2391                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2392                        .to_point(display_map);
 2393                    let end = display_map
 2394                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2395                        .to_point(display_map);
 2396                    if reversed {
 2397                        Some(end..start)
 2398                    } else {
 2399                        Some(start..end)
 2400                    }
 2401                } else {
 2402                    None
 2403                }
 2404            })
 2405            .collect::<Vec<_>>();
 2406
 2407        self.change_selections(None, cx, |s| {
 2408            s.select_ranges(selection_ranges);
 2409        });
 2410        cx.notify();
 2411    }
 2412
 2413    pub fn has_pending_nonempty_selection(&self) -> bool {
 2414        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2415            Some(Selection { start, end, .. }) => start != end,
 2416            None => false,
 2417        };
 2418
 2419        pending_nonempty_selection
 2420            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2421    }
 2422
 2423    pub fn has_pending_selection(&self) -> bool {
 2424        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2425    }
 2426
 2427    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2428        if self.clear_expanded_diff_hunks(cx) {
 2429            cx.notify();
 2430            return;
 2431        }
 2432        if self.dismiss_menus_and_popups(true, cx) {
 2433            return;
 2434        }
 2435
 2436        if self.mode == EditorMode::Full
 2437            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2438        {
 2439            return;
 2440        }
 2441
 2442        cx.propagate();
 2443    }
 2444
 2445    pub fn dismiss_menus_and_popups(
 2446        &mut self,
 2447        should_report_inline_completion_event: bool,
 2448        cx: &mut ViewContext<Self>,
 2449    ) -> bool {
 2450        if self.take_rename(false, cx).is_some() {
 2451            return true;
 2452        }
 2453
 2454        if hide_hover(self, cx) {
 2455            return true;
 2456        }
 2457
 2458        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2459            return true;
 2460        }
 2461
 2462        if self.hide_context_menu(cx).is_some() {
 2463            return true;
 2464        }
 2465
 2466        if self.mouse_context_menu.take().is_some() {
 2467            return true;
 2468        }
 2469
 2470        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2471            return true;
 2472        }
 2473
 2474        if self.snippet_stack.pop().is_some() {
 2475            return true;
 2476        }
 2477
 2478        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2479            self.dismiss_diagnostics(cx);
 2480            return true;
 2481        }
 2482
 2483        false
 2484    }
 2485
 2486    fn linked_editing_ranges_for(
 2487        &self,
 2488        selection: Range<text::Anchor>,
 2489        cx: &AppContext,
 2490    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2491        if self.linked_edit_ranges.is_empty() {
 2492            return None;
 2493        }
 2494        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2495            selection.end.buffer_id.and_then(|end_buffer_id| {
 2496                if selection.start.buffer_id != Some(end_buffer_id) {
 2497                    return None;
 2498                }
 2499                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2500                let snapshot = buffer.read(cx).snapshot();
 2501                self.linked_edit_ranges
 2502                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2503                    .map(|ranges| (ranges, snapshot, buffer))
 2504            })?;
 2505        use text::ToOffset as TO;
 2506        // find offset from the start of current range to current cursor position
 2507        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2508
 2509        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2510        let start_difference = start_offset - start_byte_offset;
 2511        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2512        let end_difference = end_offset - start_byte_offset;
 2513        // Current range has associated linked ranges.
 2514        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2515        for range in linked_ranges.iter() {
 2516            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2517            let end_offset = start_offset + end_difference;
 2518            let start_offset = start_offset + start_difference;
 2519            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2520                continue;
 2521            }
 2522            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2523                if s.start.buffer_id != selection.start.buffer_id
 2524                    || s.end.buffer_id != selection.end.buffer_id
 2525                {
 2526                    return false;
 2527                }
 2528                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2529                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2530            }) {
 2531                continue;
 2532            }
 2533            let start = buffer_snapshot.anchor_after(start_offset);
 2534            let end = buffer_snapshot.anchor_after(end_offset);
 2535            linked_edits
 2536                .entry(buffer.clone())
 2537                .or_default()
 2538                .push(start..end);
 2539        }
 2540        Some(linked_edits)
 2541    }
 2542
 2543    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2544        let text: Arc<str> = text.into();
 2545
 2546        if self.read_only(cx) {
 2547            return;
 2548        }
 2549
 2550        let selections = self.selections.all_adjusted(cx);
 2551        let mut bracket_inserted = false;
 2552        let mut edits = Vec::new();
 2553        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2554        let mut new_selections = Vec::with_capacity(selections.len());
 2555        let mut new_autoclose_regions = Vec::new();
 2556        let snapshot = self.buffer.read(cx).read(cx);
 2557
 2558        for (selection, autoclose_region) in
 2559            self.selections_with_autoclose_regions(selections, &snapshot)
 2560        {
 2561            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2562                // Determine if the inserted text matches the opening or closing
 2563                // bracket of any of this language's bracket pairs.
 2564                let mut bracket_pair = None;
 2565                let mut is_bracket_pair_start = false;
 2566                let mut is_bracket_pair_end = false;
 2567                if !text.is_empty() {
 2568                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2569                    //  and they are removing the character that triggered IME popup.
 2570                    for (pair, enabled) in scope.brackets() {
 2571                        if !pair.close && !pair.surround {
 2572                            continue;
 2573                        }
 2574
 2575                        if enabled && pair.start.ends_with(text.as_ref()) {
 2576                            let prefix_len = pair.start.len() - text.len();
 2577                            let preceding_text_matches_prefix = prefix_len == 0
 2578                                || (selection.start.column >= (prefix_len as u32)
 2579                                    && snapshot.contains_str_at(
 2580                                        Point::new(
 2581                                            selection.start.row,
 2582                                            selection.start.column - (prefix_len as u32),
 2583                                        ),
 2584                                        &pair.start[..prefix_len],
 2585                                    ));
 2586                            if preceding_text_matches_prefix {
 2587                                bracket_pair = Some(pair.clone());
 2588                                is_bracket_pair_start = true;
 2589                                break;
 2590                            }
 2591                        }
 2592                        if pair.end.as_str() == text.as_ref() {
 2593                            bracket_pair = Some(pair.clone());
 2594                            is_bracket_pair_end = true;
 2595                            break;
 2596                        }
 2597                    }
 2598                }
 2599
 2600                if let Some(bracket_pair) = bracket_pair {
 2601                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2602                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2603                    let auto_surround =
 2604                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2605                    if selection.is_empty() {
 2606                        if is_bracket_pair_start {
 2607                            // If the inserted text is a suffix of an opening bracket and the
 2608                            // selection is preceded by the rest of the opening bracket, then
 2609                            // insert the closing bracket.
 2610                            let following_text_allows_autoclose = snapshot
 2611                                .chars_at(selection.start)
 2612                                .next()
 2613                                .map_or(true, |c| scope.should_autoclose_before(c));
 2614
 2615                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2616                                && bracket_pair.start.len() == 1
 2617                            {
 2618                                let target = bracket_pair.start.chars().next().unwrap();
 2619                                let current_line_count = snapshot
 2620                                    .reversed_chars_at(selection.start)
 2621                                    .take_while(|&c| c != '\n')
 2622                                    .filter(|&c| c == target)
 2623                                    .count();
 2624                                current_line_count % 2 == 1
 2625                            } else {
 2626                                false
 2627                            };
 2628
 2629                            if autoclose
 2630                                && bracket_pair.close
 2631                                && following_text_allows_autoclose
 2632                                && !is_closing_quote
 2633                            {
 2634                                let anchor = snapshot.anchor_before(selection.end);
 2635                                new_selections.push((selection.map(|_| anchor), text.len()));
 2636                                new_autoclose_regions.push((
 2637                                    anchor,
 2638                                    text.len(),
 2639                                    selection.id,
 2640                                    bracket_pair.clone(),
 2641                                ));
 2642                                edits.push((
 2643                                    selection.range(),
 2644                                    format!("{}{}", text, bracket_pair.end).into(),
 2645                                ));
 2646                                bracket_inserted = true;
 2647                                continue;
 2648                            }
 2649                        }
 2650
 2651                        if let Some(region) = autoclose_region {
 2652                            // If the selection is followed by an auto-inserted closing bracket,
 2653                            // then don't insert that closing bracket again; just move the selection
 2654                            // past the closing bracket.
 2655                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2656                                && text.as_ref() == region.pair.end.as_str();
 2657                            if should_skip {
 2658                                let anchor = snapshot.anchor_after(selection.end);
 2659                                new_selections
 2660                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2661                                continue;
 2662                            }
 2663                        }
 2664
 2665                        let always_treat_brackets_as_autoclosed = snapshot
 2666                            .settings_at(selection.start, cx)
 2667                            .always_treat_brackets_as_autoclosed;
 2668                        if always_treat_brackets_as_autoclosed
 2669                            && is_bracket_pair_end
 2670                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2671                        {
 2672                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2673                            // and the inserted text is a closing bracket and the selection is followed
 2674                            // by the closing bracket then move the selection past the closing bracket.
 2675                            let anchor = snapshot.anchor_after(selection.end);
 2676                            new_selections.push((selection.map(|_| anchor), text.len()));
 2677                            continue;
 2678                        }
 2679                    }
 2680                    // If an opening bracket is 1 character long and is typed while
 2681                    // text is selected, then surround that text with the bracket pair.
 2682                    else if auto_surround
 2683                        && bracket_pair.surround
 2684                        && is_bracket_pair_start
 2685                        && bracket_pair.start.chars().count() == 1
 2686                    {
 2687                        edits.push((selection.start..selection.start, text.clone()));
 2688                        edits.push((
 2689                            selection.end..selection.end,
 2690                            bracket_pair.end.as_str().into(),
 2691                        ));
 2692                        bracket_inserted = true;
 2693                        new_selections.push((
 2694                            Selection {
 2695                                id: selection.id,
 2696                                start: snapshot.anchor_after(selection.start),
 2697                                end: snapshot.anchor_before(selection.end),
 2698                                reversed: selection.reversed,
 2699                                goal: selection.goal,
 2700                            },
 2701                            0,
 2702                        ));
 2703                        continue;
 2704                    }
 2705                }
 2706            }
 2707
 2708            if self.auto_replace_emoji_shortcode
 2709                && selection.is_empty()
 2710                && text.as_ref().ends_with(':')
 2711            {
 2712                if let Some(possible_emoji_short_code) =
 2713                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2714                {
 2715                    if !possible_emoji_short_code.is_empty() {
 2716                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2717                            let emoji_shortcode_start = Point::new(
 2718                                selection.start.row,
 2719                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2720                            );
 2721
 2722                            // Remove shortcode from buffer
 2723                            edits.push((
 2724                                emoji_shortcode_start..selection.start,
 2725                                "".to_string().into(),
 2726                            ));
 2727                            new_selections.push((
 2728                                Selection {
 2729                                    id: selection.id,
 2730                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2731                                    end: snapshot.anchor_before(selection.start),
 2732                                    reversed: selection.reversed,
 2733                                    goal: selection.goal,
 2734                                },
 2735                                0,
 2736                            ));
 2737
 2738                            // Insert emoji
 2739                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2740                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2741                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2742
 2743                            continue;
 2744                        }
 2745                    }
 2746                }
 2747            }
 2748
 2749            // If not handling any auto-close operation, then just replace the selected
 2750            // text with the given input and move the selection to the end of the
 2751            // newly inserted text.
 2752            let anchor = snapshot.anchor_after(selection.end);
 2753            if !self.linked_edit_ranges.is_empty() {
 2754                let start_anchor = snapshot.anchor_before(selection.start);
 2755
 2756                let is_word_char = text.chars().next().map_or(true, |char| {
 2757                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2758                    classifier.is_word(char)
 2759                });
 2760
 2761                if is_word_char {
 2762                    if let Some(ranges) = self
 2763                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2764                    {
 2765                        for (buffer, edits) in ranges {
 2766                            linked_edits
 2767                                .entry(buffer.clone())
 2768                                .or_default()
 2769                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2770                        }
 2771                    }
 2772                }
 2773            }
 2774
 2775            new_selections.push((selection.map(|_| anchor), 0));
 2776            edits.push((selection.start..selection.end, text.clone()));
 2777        }
 2778
 2779        drop(snapshot);
 2780
 2781        self.transact(cx, |this, cx| {
 2782            this.buffer.update(cx, |buffer, cx| {
 2783                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2784            });
 2785            for (buffer, edits) in linked_edits {
 2786                buffer.update(cx, |buffer, cx| {
 2787                    let snapshot = buffer.snapshot();
 2788                    let edits = edits
 2789                        .into_iter()
 2790                        .map(|(range, text)| {
 2791                            use text::ToPoint as TP;
 2792                            let end_point = TP::to_point(&range.end, &snapshot);
 2793                            let start_point = TP::to_point(&range.start, &snapshot);
 2794                            (start_point..end_point, text)
 2795                        })
 2796                        .sorted_by_key(|(range, _)| range.start)
 2797                        .collect::<Vec<_>>();
 2798                    buffer.edit(edits, None, cx);
 2799                })
 2800            }
 2801            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2802            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2803            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2804            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2805                .zip(new_selection_deltas)
 2806                .map(|(selection, delta)| Selection {
 2807                    id: selection.id,
 2808                    start: selection.start + delta,
 2809                    end: selection.end + delta,
 2810                    reversed: selection.reversed,
 2811                    goal: SelectionGoal::None,
 2812                })
 2813                .collect::<Vec<_>>();
 2814
 2815            let mut i = 0;
 2816            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2817                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2818                let start = map.buffer_snapshot.anchor_before(position);
 2819                let end = map.buffer_snapshot.anchor_after(position);
 2820                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2821                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2822                        Ordering::Less => i += 1,
 2823                        Ordering::Greater => break,
 2824                        Ordering::Equal => {
 2825                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2826                                Ordering::Less => i += 1,
 2827                                Ordering::Equal => break,
 2828                                Ordering::Greater => break,
 2829                            }
 2830                        }
 2831                    }
 2832                }
 2833                this.autoclose_regions.insert(
 2834                    i,
 2835                    AutocloseRegion {
 2836                        selection_id,
 2837                        range: start..end,
 2838                        pair,
 2839                    },
 2840                );
 2841            }
 2842
 2843            let had_active_inline_completion = this.has_active_inline_completion();
 2844            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2845                s.select(new_selections)
 2846            });
 2847
 2848            if !bracket_inserted {
 2849                if let Some(on_type_format_task) =
 2850                    this.trigger_on_type_formatting(text.to_string(), cx)
 2851                {
 2852                    on_type_format_task.detach_and_log_err(cx);
 2853                }
 2854            }
 2855
 2856            let editor_settings = EditorSettings::get_global(cx);
 2857            if bracket_inserted
 2858                && (editor_settings.auto_signature_help
 2859                    || editor_settings.show_signature_help_after_edits)
 2860            {
 2861                this.show_signature_help(&ShowSignatureHelp, cx);
 2862            }
 2863
 2864            let trigger_in_words = !had_active_inline_completion;
 2865            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2866            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2867            this.refresh_inline_completion(true, false, cx);
 2868        });
 2869    }
 2870
 2871    fn find_possible_emoji_shortcode_at_position(
 2872        snapshot: &MultiBufferSnapshot,
 2873        position: Point,
 2874    ) -> Option<String> {
 2875        let mut chars = Vec::new();
 2876        let mut found_colon = false;
 2877        for char in snapshot.reversed_chars_at(position).take(100) {
 2878            // Found a possible emoji shortcode in the middle of the buffer
 2879            if found_colon {
 2880                if char.is_whitespace() {
 2881                    chars.reverse();
 2882                    return Some(chars.iter().collect());
 2883                }
 2884                // If the previous character is not a whitespace, we are in the middle of a word
 2885                // and we only want to complete the shortcode if the word is made up of other emojis
 2886                let mut containing_word = String::new();
 2887                for ch in snapshot
 2888                    .reversed_chars_at(position)
 2889                    .skip(chars.len() + 1)
 2890                    .take(100)
 2891                {
 2892                    if ch.is_whitespace() {
 2893                        break;
 2894                    }
 2895                    containing_word.push(ch);
 2896                }
 2897                let containing_word = containing_word.chars().rev().collect::<String>();
 2898                if util::word_consists_of_emojis(containing_word.as_str()) {
 2899                    chars.reverse();
 2900                    return Some(chars.iter().collect());
 2901                }
 2902            }
 2903
 2904            if char.is_whitespace() || !char.is_ascii() {
 2905                return None;
 2906            }
 2907            if char == ':' {
 2908                found_colon = true;
 2909            } else {
 2910                chars.push(char);
 2911            }
 2912        }
 2913        // Found a possible emoji shortcode at the beginning of the buffer
 2914        chars.reverse();
 2915        Some(chars.iter().collect())
 2916    }
 2917
 2918    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2919        self.transact(cx, |this, cx| {
 2920            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2921                let selections = this.selections.all::<usize>(cx);
 2922                let multi_buffer = this.buffer.read(cx);
 2923                let buffer = multi_buffer.snapshot(cx);
 2924                selections
 2925                    .iter()
 2926                    .map(|selection| {
 2927                        let start_point = selection.start.to_point(&buffer);
 2928                        let mut indent =
 2929                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2930                        indent.len = cmp::min(indent.len, start_point.column);
 2931                        let start = selection.start;
 2932                        let end = selection.end;
 2933                        let selection_is_empty = start == end;
 2934                        let language_scope = buffer.language_scope_at(start);
 2935                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2936                            &language_scope
 2937                        {
 2938                            let leading_whitespace_len = buffer
 2939                                .reversed_chars_at(start)
 2940                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2941                                .map(|c| c.len_utf8())
 2942                                .sum::<usize>();
 2943
 2944                            let trailing_whitespace_len = buffer
 2945                                .chars_at(end)
 2946                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2947                                .map(|c| c.len_utf8())
 2948                                .sum::<usize>();
 2949
 2950                            let insert_extra_newline =
 2951                                language.brackets().any(|(pair, enabled)| {
 2952                                    let pair_start = pair.start.trim_end();
 2953                                    let pair_end = pair.end.trim_start();
 2954
 2955                                    enabled
 2956                                        && pair.newline
 2957                                        && buffer.contains_str_at(
 2958                                            end + trailing_whitespace_len,
 2959                                            pair_end,
 2960                                        )
 2961                                        && buffer.contains_str_at(
 2962                                            (start - leading_whitespace_len)
 2963                                                .saturating_sub(pair_start.len()),
 2964                                            pair_start,
 2965                                        )
 2966                                });
 2967
 2968                            // Comment extension on newline is allowed only for cursor selections
 2969                            let comment_delimiter = maybe!({
 2970                                if !selection_is_empty {
 2971                                    return None;
 2972                                }
 2973
 2974                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 2975                                    return None;
 2976                                }
 2977
 2978                                let delimiters = language.line_comment_prefixes();
 2979                                let max_len_of_delimiter =
 2980                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 2981                                let (snapshot, range) =
 2982                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 2983
 2984                                let mut index_of_first_non_whitespace = 0;
 2985                                let comment_candidate = snapshot
 2986                                    .chars_for_range(range)
 2987                                    .skip_while(|c| {
 2988                                        let should_skip = c.is_whitespace();
 2989                                        if should_skip {
 2990                                            index_of_first_non_whitespace += 1;
 2991                                        }
 2992                                        should_skip
 2993                                    })
 2994                                    .take(max_len_of_delimiter)
 2995                                    .collect::<String>();
 2996                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 2997                                    comment_candidate.starts_with(comment_prefix.as_ref())
 2998                                })?;
 2999                                let cursor_is_placed_after_comment_marker =
 3000                                    index_of_first_non_whitespace + comment_prefix.len()
 3001                                        <= start_point.column as usize;
 3002                                if cursor_is_placed_after_comment_marker {
 3003                                    Some(comment_prefix.clone())
 3004                                } else {
 3005                                    None
 3006                                }
 3007                            });
 3008                            (comment_delimiter, insert_extra_newline)
 3009                        } else {
 3010                            (None, false)
 3011                        };
 3012
 3013                        let capacity_for_delimiter = comment_delimiter
 3014                            .as_deref()
 3015                            .map(str::len)
 3016                            .unwrap_or_default();
 3017                        let mut new_text =
 3018                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3019                        new_text.push('\n');
 3020                        new_text.extend(indent.chars());
 3021                        if let Some(delimiter) = &comment_delimiter {
 3022                            new_text.push_str(delimiter);
 3023                        }
 3024                        if insert_extra_newline {
 3025                            new_text = new_text.repeat(2);
 3026                        }
 3027
 3028                        let anchor = buffer.anchor_after(end);
 3029                        let new_selection = selection.map(|_| anchor);
 3030                        (
 3031                            (start..end, new_text),
 3032                            (insert_extra_newline, new_selection),
 3033                        )
 3034                    })
 3035                    .unzip()
 3036            };
 3037
 3038            this.edit_with_autoindent(edits, cx);
 3039            let buffer = this.buffer.read(cx).snapshot(cx);
 3040            let new_selections = selection_fixup_info
 3041                .into_iter()
 3042                .map(|(extra_newline_inserted, new_selection)| {
 3043                    let mut cursor = new_selection.end.to_point(&buffer);
 3044                    if extra_newline_inserted {
 3045                        cursor.row -= 1;
 3046                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3047                    }
 3048                    new_selection.map(|_| cursor)
 3049                })
 3050                .collect();
 3051
 3052            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3053            this.refresh_inline_completion(true, false, cx);
 3054        });
 3055    }
 3056
 3057    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3058        let buffer = self.buffer.read(cx);
 3059        let snapshot = buffer.snapshot(cx);
 3060
 3061        let mut edits = Vec::new();
 3062        let mut rows = Vec::new();
 3063
 3064        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3065            let cursor = selection.head();
 3066            let row = cursor.row;
 3067
 3068            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3069
 3070            let newline = "\n".to_string();
 3071            edits.push((start_of_line..start_of_line, newline));
 3072
 3073            rows.push(row + rows_inserted as u32);
 3074        }
 3075
 3076        self.transact(cx, |editor, cx| {
 3077            editor.edit(edits, cx);
 3078
 3079            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3080                let mut index = 0;
 3081                s.move_cursors_with(|map, _, _| {
 3082                    let row = rows[index];
 3083                    index += 1;
 3084
 3085                    let point = Point::new(row, 0);
 3086                    let boundary = map.next_line_boundary(point).1;
 3087                    let clipped = map.clip_point(boundary, Bias::Left);
 3088
 3089                    (clipped, SelectionGoal::None)
 3090                });
 3091            });
 3092
 3093            let mut indent_edits = Vec::new();
 3094            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3095            for row in rows {
 3096                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3097                for (row, indent) in indents {
 3098                    if indent.len == 0 {
 3099                        continue;
 3100                    }
 3101
 3102                    let text = match indent.kind {
 3103                        IndentKind::Space => " ".repeat(indent.len as usize),
 3104                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3105                    };
 3106                    let point = Point::new(row.0, 0);
 3107                    indent_edits.push((point..point, text));
 3108                }
 3109            }
 3110            editor.edit(indent_edits, cx);
 3111        });
 3112    }
 3113
 3114    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3115        let buffer = self.buffer.read(cx);
 3116        let snapshot = buffer.snapshot(cx);
 3117
 3118        let mut edits = Vec::new();
 3119        let mut rows = Vec::new();
 3120        let mut rows_inserted = 0;
 3121
 3122        for selection in self.selections.all_adjusted(cx) {
 3123            let cursor = selection.head();
 3124            let row = cursor.row;
 3125
 3126            let point = Point::new(row + 1, 0);
 3127            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3128
 3129            let newline = "\n".to_string();
 3130            edits.push((start_of_line..start_of_line, newline));
 3131
 3132            rows_inserted += 1;
 3133            rows.push(row + rows_inserted);
 3134        }
 3135
 3136        self.transact(cx, |editor, cx| {
 3137            editor.edit(edits, cx);
 3138
 3139            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3140                let mut index = 0;
 3141                s.move_cursors_with(|map, _, _| {
 3142                    let row = rows[index];
 3143                    index += 1;
 3144
 3145                    let point = Point::new(row, 0);
 3146                    let boundary = map.next_line_boundary(point).1;
 3147                    let clipped = map.clip_point(boundary, Bias::Left);
 3148
 3149                    (clipped, SelectionGoal::None)
 3150                });
 3151            });
 3152
 3153            let mut indent_edits = Vec::new();
 3154            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3155            for row in rows {
 3156                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3157                for (row, indent) in indents {
 3158                    if indent.len == 0 {
 3159                        continue;
 3160                    }
 3161
 3162                    let text = match indent.kind {
 3163                        IndentKind::Space => " ".repeat(indent.len as usize),
 3164                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3165                    };
 3166                    let point = Point::new(row.0, 0);
 3167                    indent_edits.push((point..point, text));
 3168                }
 3169            }
 3170            editor.edit(indent_edits, cx);
 3171        });
 3172    }
 3173
 3174    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3175        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3176            original_indent_columns: Vec::new(),
 3177        });
 3178        self.insert_with_autoindent_mode(text, autoindent, cx);
 3179    }
 3180
 3181    fn insert_with_autoindent_mode(
 3182        &mut self,
 3183        text: &str,
 3184        autoindent_mode: Option<AutoindentMode>,
 3185        cx: &mut ViewContext<Self>,
 3186    ) {
 3187        if self.read_only(cx) {
 3188            return;
 3189        }
 3190
 3191        let text: Arc<str> = text.into();
 3192        self.transact(cx, |this, cx| {
 3193            let old_selections = this.selections.all_adjusted(cx);
 3194            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3195                let anchors = {
 3196                    let snapshot = buffer.read(cx);
 3197                    old_selections
 3198                        .iter()
 3199                        .map(|s| {
 3200                            let anchor = snapshot.anchor_after(s.head());
 3201                            s.map(|_| anchor)
 3202                        })
 3203                        .collect::<Vec<_>>()
 3204                };
 3205                buffer.edit(
 3206                    old_selections
 3207                        .iter()
 3208                        .map(|s| (s.start..s.end, text.clone())),
 3209                    autoindent_mode,
 3210                    cx,
 3211                );
 3212                anchors
 3213            });
 3214
 3215            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3216                s.select_anchors(selection_anchors);
 3217            })
 3218        });
 3219    }
 3220
 3221    fn trigger_completion_on_input(
 3222        &mut self,
 3223        text: &str,
 3224        trigger_in_words: bool,
 3225        cx: &mut ViewContext<Self>,
 3226    ) {
 3227        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3228            self.show_completions(
 3229                &ShowCompletions {
 3230                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3231                },
 3232                cx,
 3233            );
 3234        } else {
 3235            self.hide_context_menu(cx);
 3236        }
 3237    }
 3238
 3239    fn is_completion_trigger(
 3240        &self,
 3241        text: &str,
 3242        trigger_in_words: bool,
 3243        cx: &mut ViewContext<Self>,
 3244    ) -> bool {
 3245        let position = self.selections.newest_anchor().head();
 3246        let multibuffer = self.buffer.read(cx);
 3247        let Some(buffer) = position
 3248            .buffer_id
 3249            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3250        else {
 3251            return false;
 3252        };
 3253
 3254        if let Some(completion_provider) = &self.completion_provider {
 3255            completion_provider.is_completion_trigger(
 3256                &buffer,
 3257                position.text_anchor,
 3258                text,
 3259                trigger_in_words,
 3260                cx,
 3261            )
 3262        } else {
 3263            false
 3264        }
 3265    }
 3266
 3267    /// If any empty selections is touching the start of its innermost containing autoclose
 3268    /// region, expand it to select the brackets.
 3269    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3270        let selections = self.selections.all::<usize>(cx);
 3271        let buffer = self.buffer.read(cx).read(cx);
 3272        let new_selections = self
 3273            .selections_with_autoclose_regions(selections, &buffer)
 3274            .map(|(mut selection, region)| {
 3275                if !selection.is_empty() {
 3276                    return selection;
 3277                }
 3278
 3279                if let Some(region) = region {
 3280                    let mut range = region.range.to_offset(&buffer);
 3281                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3282                        range.start -= region.pair.start.len();
 3283                        if buffer.contains_str_at(range.start, &region.pair.start)
 3284                            && buffer.contains_str_at(range.end, &region.pair.end)
 3285                        {
 3286                            range.end += region.pair.end.len();
 3287                            selection.start = range.start;
 3288                            selection.end = range.end;
 3289
 3290                            return selection;
 3291                        }
 3292                    }
 3293                }
 3294
 3295                let always_treat_brackets_as_autoclosed = buffer
 3296                    .settings_at(selection.start, cx)
 3297                    .always_treat_brackets_as_autoclosed;
 3298
 3299                if !always_treat_brackets_as_autoclosed {
 3300                    return selection;
 3301                }
 3302
 3303                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3304                    for (pair, enabled) in scope.brackets() {
 3305                        if !enabled || !pair.close {
 3306                            continue;
 3307                        }
 3308
 3309                        if buffer.contains_str_at(selection.start, &pair.end) {
 3310                            let pair_start_len = pair.start.len();
 3311                            if buffer.contains_str_at(
 3312                                selection.start.saturating_sub(pair_start_len),
 3313                                &pair.start,
 3314                            ) {
 3315                                selection.start -= pair_start_len;
 3316                                selection.end += pair.end.len();
 3317
 3318                                return selection;
 3319                            }
 3320                        }
 3321                    }
 3322                }
 3323
 3324                selection
 3325            })
 3326            .collect();
 3327
 3328        drop(buffer);
 3329        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3330    }
 3331
 3332    /// Iterate the given selections, and for each one, find the smallest surrounding
 3333    /// autoclose region. This uses the ordering of the selections and the autoclose
 3334    /// regions to avoid repeated comparisons.
 3335    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3336        &'a self,
 3337        selections: impl IntoIterator<Item = Selection<D>>,
 3338        buffer: &'a MultiBufferSnapshot,
 3339    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3340        let mut i = 0;
 3341        let mut regions = self.autoclose_regions.as_slice();
 3342        selections.into_iter().map(move |selection| {
 3343            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3344
 3345            let mut enclosing = None;
 3346            while let Some(pair_state) = regions.get(i) {
 3347                if pair_state.range.end.to_offset(buffer) < range.start {
 3348                    regions = &regions[i + 1..];
 3349                    i = 0;
 3350                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3351                    break;
 3352                } else {
 3353                    if pair_state.selection_id == selection.id {
 3354                        enclosing = Some(pair_state);
 3355                    }
 3356                    i += 1;
 3357                }
 3358            }
 3359
 3360            (selection, enclosing)
 3361        })
 3362    }
 3363
 3364    /// Remove any autoclose regions that no longer contain their selection.
 3365    fn invalidate_autoclose_regions(
 3366        &mut self,
 3367        mut selections: &[Selection<Anchor>],
 3368        buffer: &MultiBufferSnapshot,
 3369    ) {
 3370        self.autoclose_regions.retain(|state| {
 3371            let mut i = 0;
 3372            while let Some(selection) = selections.get(i) {
 3373                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3374                    selections = &selections[1..];
 3375                    continue;
 3376                }
 3377                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3378                    break;
 3379                }
 3380                if selection.id == state.selection_id {
 3381                    return true;
 3382                } else {
 3383                    i += 1;
 3384                }
 3385            }
 3386            false
 3387        });
 3388    }
 3389
 3390    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3391        let offset = position.to_offset(buffer);
 3392        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3393        if offset > word_range.start && kind == Some(CharKind::Word) {
 3394            Some(
 3395                buffer
 3396                    .text_for_range(word_range.start..offset)
 3397                    .collect::<String>(),
 3398            )
 3399        } else {
 3400            None
 3401        }
 3402    }
 3403
 3404    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3405        self.refresh_inlay_hints(
 3406            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3407            cx,
 3408        );
 3409    }
 3410
 3411    pub fn inlay_hints_enabled(&self) -> bool {
 3412        self.inlay_hint_cache.enabled
 3413    }
 3414
 3415    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3416        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3417            return;
 3418        }
 3419
 3420        let reason_description = reason.description();
 3421        let ignore_debounce = matches!(
 3422            reason,
 3423            InlayHintRefreshReason::SettingsChange(_)
 3424                | InlayHintRefreshReason::Toggle(_)
 3425                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3426        );
 3427        let (invalidate_cache, required_languages) = match reason {
 3428            InlayHintRefreshReason::Toggle(enabled) => {
 3429                self.inlay_hint_cache.enabled = enabled;
 3430                if enabled {
 3431                    (InvalidationStrategy::RefreshRequested, None)
 3432                } else {
 3433                    self.inlay_hint_cache.clear();
 3434                    self.splice_inlays(
 3435                        self.visible_inlay_hints(cx)
 3436                            .iter()
 3437                            .map(|inlay| inlay.id)
 3438                            .collect(),
 3439                        Vec::new(),
 3440                        cx,
 3441                    );
 3442                    return;
 3443                }
 3444            }
 3445            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3446                match self.inlay_hint_cache.update_settings(
 3447                    &self.buffer,
 3448                    new_settings,
 3449                    self.visible_inlay_hints(cx),
 3450                    cx,
 3451                ) {
 3452                    ControlFlow::Break(Some(InlaySplice {
 3453                        to_remove,
 3454                        to_insert,
 3455                    })) => {
 3456                        self.splice_inlays(to_remove, to_insert, cx);
 3457                        return;
 3458                    }
 3459                    ControlFlow::Break(None) => return,
 3460                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3461                }
 3462            }
 3463            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3464                if let Some(InlaySplice {
 3465                    to_remove,
 3466                    to_insert,
 3467                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3468                {
 3469                    self.splice_inlays(to_remove, to_insert, cx);
 3470                }
 3471                return;
 3472            }
 3473            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3474            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3475                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3476            }
 3477            InlayHintRefreshReason::RefreshRequested => {
 3478                (InvalidationStrategy::RefreshRequested, None)
 3479            }
 3480        };
 3481
 3482        if let Some(InlaySplice {
 3483            to_remove,
 3484            to_insert,
 3485        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3486            reason_description,
 3487            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3488            invalidate_cache,
 3489            ignore_debounce,
 3490            cx,
 3491        ) {
 3492            self.splice_inlays(to_remove, to_insert, cx);
 3493        }
 3494    }
 3495
 3496    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3497        self.display_map
 3498            .read(cx)
 3499            .current_inlays()
 3500            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3501            .cloned()
 3502            .collect()
 3503    }
 3504
 3505    pub fn excerpts_for_inlay_hints_query(
 3506        &self,
 3507        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3508        cx: &mut ViewContext<Editor>,
 3509    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3510        let Some(project) = self.project.as_ref() else {
 3511            return HashMap::default();
 3512        };
 3513        let project = project.read(cx);
 3514        let multi_buffer = self.buffer().read(cx);
 3515        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3516        let multi_buffer_visible_start = self
 3517            .scroll_manager
 3518            .anchor()
 3519            .anchor
 3520            .to_point(&multi_buffer_snapshot);
 3521        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3522            multi_buffer_visible_start
 3523                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3524            Bias::Left,
 3525        );
 3526        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3527        multi_buffer
 3528            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3529            .into_iter()
 3530            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3531            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3532                let buffer = buffer_handle.read(cx);
 3533                let buffer_file = project::File::from_dyn(buffer.file())?;
 3534                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3535                let worktree_entry = buffer_worktree
 3536                    .read(cx)
 3537                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3538                if worktree_entry.is_ignored {
 3539                    return None;
 3540                }
 3541
 3542                let language = buffer.language()?;
 3543                if let Some(restrict_to_languages) = restrict_to_languages {
 3544                    if !restrict_to_languages.contains(language) {
 3545                        return None;
 3546                    }
 3547                }
 3548                Some((
 3549                    excerpt_id,
 3550                    (
 3551                        buffer_handle,
 3552                        buffer.version().clone(),
 3553                        excerpt_visible_range,
 3554                    ),
 3555                ))
 3556            })
 3557            .collect()
 3558    }
 3559
 3560    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3561        TextLayoutDetails {
 3562            text_system: cx.text_system().clone(),
 3563            editor_style: self.style.clone().unwrap(),
 3564            rem_size: cx.rem_size(),
 3565            scroll_anchor: self.scroll_manager.anchor(),
 3566            visible_rows: self.visible_line_count(),
 3567            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3568        }
 3569    }
 3570
 3571    fn splice_inlays(
 3572        &self,
 3573        to_remove: Vec<InlayId>,
 3574        to_insert: Vec<Inlay>,
 3575        cx: &mut ViewContext<Self>,
 3576    ) {
 3577        self.display_map.update(cx, |display_map, cx| {
 3578            display_map.splice_inlays(to_remove, to_insert, cx)
 3579        });
 3580        cx.notify();
 3581    }
 3582
 3583    fn trigger_on_type_formatting(
 3584        &self,
 3585        input: String,
 3586        cx: &mut ViewContext<Self>,
 3587    ) -> Option<Task<Result<()>>> {
 3588        if input.len() != 1 {
 3589            return None;
 3590        }
 3591
 3592        let project = self.project.as_ref()?;
 3593        let position = self.selections.newest_anchor().head();
 3594        let (buffer, buffer_position) = self
 3595            .buffer
 3596            .read(cx)
 3597            .text_anchor_for_position(position, cx)?;
 3598
 3599        let settings = language_settings::language_settings(
 3600            buffer
 3601                .read(cx)
 3602                .language_at(buffer_position)
 3603                .map(|l| l.name()),
 3604            buffer.read(cx).file(),
 3605            cx,
 3606        );
 3607        if !settings.use_on_type_format {
 3608            return None;
 3609        }
 3610
 3611        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3612        // hence we do LSP request & edit on host side only — add formats to host's history.
 3613        let push_to_lsp_host_history = true;
 3614        // If this is not the host, append its history with new edits.
 3615        let push_to_client_history = project.read(cx).is_via_collab();
 3616
 3617        let on_type_formatting = project.update(cx, |project, cx| {
 3618            project.on_type_format(
 3619                buffer.clone(),
 3620                buffer_position,
 3621                input,
 3622                push_to_lsp_host_history,
 3623                cx,
 3624            )
 3625        });
 3626        Some(cx.spawn(|editor, mut cx| async move {
 3627            if let Some(transaction) = on_type_formatting.await? {
 3628                if push_to_client_history {
 3629                    buffer
 3630                        .update(&mut cx, |buffer, _| {
 3631                            buffer.push_transaction(transaction, Instant::now());
 3632                        })
 3633                        .ok();
 3634                }
 3635                editor.update(&mut cx, |editor, cx| {
 3636                    editor.refresh_document_highlights(cx);
 3637                })?;
 3638            }
 3639            Ok(())
 3640        }))
 3641    }
 3642
 3643    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3644        if self.pending_rename.is_some() {
 3645            return;
 3646        }
 3647
 3648        let Some(provider) = self.completion_provider.as_ref() else {
 3649            return;
 3650        };
 3651
 3652        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3653            return;
 3654        }
 3655
 3656        let position = self.selections.newest_anchor().head();
 3657        let (buffer, buffer_position) =
 3658            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3659                output
 3660            } else {
 3661                return;
 3662            };
 3663        let show_completion_documentation = buffer
 3664            .read(cx)
 3665            .snapshot()
 3666            .settings_at(buffer_position, cx)
 3667            .show_completion_documentation;
 3668
 3669        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3670
 3671        let aside_was_displayed = match self.context_menu.borrow().deref() {
 3672            Some(CodeContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
 3673            _ => false,
 3674        };
 3675        let trigger_kind = match &options.trigger {
 3676            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3677                CompletionTriggerKind::TRIGGER_CHARACTER
 3678            }
 3679            _ => CompletionTriggerKind::INVOKED,
 3680        };
 3681        let completion_context = CompletionContext {
 3682            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3683                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3684                    Some(String::from(trigger))
 3685                } else {
 3686                    None
 3687                }
 3688            }),
 3689            trigger_kind,
 3690        };
 3691        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3692        let sort_completions = provider.sort_completions();
 3693
 3694        let id = post_inc(&mut self.next_completion_id);
 3695        let task = cx.spawn(|editor, mut cx| {
 3696            async move {
 3697                editor.update(&mut cx, |this, _| {
 3698                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3699                })?;
 3700                let completions = completions.await.log_err();
 3701                let menu = if let Some(completions) = completions {
 3702                    let mut menu = CompletionsMenu::new(
 3703                        id,
 3704                        sort_completions,
 3705                        show_completion_documentation,
 3706                        position,
 3707                        buffer.clone(),
 3708                        completions.into(),
 3709                        aside_was_displayed,
 3710                    );
 3711                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3712                        .await;
 3713
 3714                    if menu.matches.is_empty() {
 3715                        None
 3716                    } else {
 3717                        Some(menu)
 3718                    }
 3719                } else {
 3720                    None
 3721                };
 3722
 3723                editor.update(&mut cx, |editor, cx| {
 3724                    let mut context_menu = editor.context_menu.borrow_mut();
 3725                    match context_menu.as_ref() {
 3726                        None => {}
 3727                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3728                            if prev_menu.id > id {
 3729                                return;
 3730                            }
 3731                        }
 3732                        _ => return,
 3733                    }
 3734
 3735                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3736                        let mut menu = menu.unwrap();
 3737                        menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
 3738                        *context_menu = Some(CodeContextMenu::Completions(menu));
 3739                        drop(context_menu);
 3740                        cx.notify();
 3741                    } else if editor.completion_tasks.len() <= 1 {
 3742                        // If there are no more completion tasks and the last menu was
 3743                        // empty, we should hide it. If it was already hidden, we should
 3744                        // also show the copilot completion when available.
 3745                        drop(context_menu);
 3746                        editor.hide_context_menu(cx);
 3747                    }
 3748                })?;
 3749
 3750                Ok::<_, anyhow::Error>(())
 3751            }
 3752            .log_err()
 3753        });
 3754
 3755        self.completion_tasks.push((id, task));
 3756    }
 3757
 3758    pub fn confirm_completion(
 3759        &mut self,
 3760        action: &ConfirmCompletion,
 3761        cx: &mut ViewContext<Self>,
 3762    ) -> Option<Task<Result<()>>> {
 3763        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3764    }
 3765
 3766    pub fn compose_completion(
 3767        &mut self,
 3768        action: &ComposeCompletion,
 3769        cx: &mut ViewContext<Self>,
 3770    ) -> Option<Task<Result<()>>> {
 3771        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3772    }
 3773
 3774    fn do_completion(
 3775        &mut self,
 3776        item_ix: Option<usize>,
 3777        intent: CompletionIntent,
 3778        cx: &mut ViewContext<Editor>,
 3779    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3780        use language::ToOffset as _;
 3781
 3782        self.discard_inline_completion(true, cx);
 3783        let completions_menu =
 3784            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3785                menu
 3786            } else {
 3787                return None;
 3788            };
 3789
 3790        let mat = completions_menu
 3791            .matches
 3792            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3793        let buffer_handle = completions_menu.buffer;
 3794        let completions = completions_menu.completions.borrow_mut();
 3795        let completion = completions.get(mat.candidate_id)?;
 3796        cx.stop_propagation();
 3797
 3798        let snippet;
 3799        let text;
 3800
 3801        if completion.is_snippet() {
 3802            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3803            text = snippet.as_ref().unwrap().text.clone();
 3804        } else {
 3805            snippet = None;
 3806            text = completion.new_text.clone();
 3807        };
 3808        let selections = self.selections.all::<usize>(cx);
 3809        let buffer = buffer_handle.read(cx);
 3810        let old_range = completion.old_range.to_offset(buffer);
 3811        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3812
 3813        let newest_selection = self.selections.newest_anchor();
 3814        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3815            return None;
 3816        }
 3817
 3818        let lookbehind = newest_selection
 3819            .start
 3820            .text_anchor
 3821            .to_offset(buffer)
 3822            .saturating_sub(old_range.start);
 3823        let lookahead = old_range
 3824            .end
 3825            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3826        let mut common_prefix_len = old_text
 3827            .bytes()
 3828            .zip(text.bytes())
 3829            .take_while(|(a, b)| a == b)
 3830            .count();
 3831
 3832        let snapshot = self.buffer.read(cx).snapshot(cx);
 3833        let mut range_to_replace: Option<Range<isize>> = None;
 3834        let mut ranges = Vec::new();
 3835        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3836        for selection in &selections {
 3837            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3838                let start = selection.start.saturating_sub(lookbehind);
 3839                let end = selection.end + lookahead;
 3840                if selection.id == newest_selection.id {
 3841                    range_to_replace = Some(
 3842                        ((start + common_prefix_len) as isize - selection.start as isize)
 3843                            ..(end as isize - selection.start as isize),
 3844                    );
 3845                }
 3846                ranges.push(start + common_prefix_len..end);
 3847            } else {
 3848                common_prefix_len = 0;
 3849                ranges.clear();
 3850                ranges.extend(selections.iter().map(|s| {
 3851                    if s.id == newest_selection.id {
 3852                        range_to_replace = Some(
 3853                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3854                                - selection.start as isize
 3855                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3856                                    - selection.start as isize,
 3857                        );
 3858                        old_range.clone()
 3859                    } else {
 3860                        s.start..s.end
 3861                    }
 3862                }));
 3863                break;
 3864            }
 3865            if !self.linked_edit_ranges.is_empty() {
 3866                let start_anchor = snapshot.anchor_before(selection.head());
 3867                let end_anchor = snapshot.anchor_after(selection.tail());
 3868                if let Some(ranges) = self
 3869                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3870                {
 3871                    for (buffer, edits) in ranges {
 3872                        linked_edits.entry(buffer.clone()).or_default().extend(
 3873                            edits
 3874                                .into_iter()
 3875                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3876                        );
 3877                    }
 3878                }
 3879            }
 3880        }
 3881        let text = &text[common_prefix_len..];
 3882
 3883        cx.emit(EditorEvent::InputHandled {
 3884            utf16_range_to_replace: range_to_replace,
 3885            text: text.into(),
 3886        });
 3887
 3888        self.transact(cx, |this, cx| {
 3889            if let Some(mut snippet) = snippet {
 3890                snippet.text = text.to_string();
 3891                for tabstop in snippet
 3892                    .tabstops
 3893                    .iter_mut()
 3894                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3895                {
 3896                    tabstop.start -= common_prefix_len as isize;
 3897                    tabstop.end -= common_prefix_len as isize;
 3898                }
 3899
 3900                this.insert_snippet(&ranges, snippet, cx).log_err();
 3901            } else {
 3902                this.buffer.update(cx, |buffer, cx| {
 3903                    buffer.edit(
 3904                        ranges.iter().map(|range| (range.clone(), text)),
 3905                        this.autoindent_mode.clone(),
 3906                        cx,
 3907                    );
 3908                });
 3909            }
 3910            for (buffer, edits) in linked_edits {
 3911                buffer.update(cx, |buffer, cx| {
 3912                    let snapshot = buffer.snapshot();
 3913                    let edits = edits
 3914                        .into_iter()
 3915                        .map(|(range, text)| {
 3916                            use text::ToPoint as TP;
 3917                            let end_point = TP::to_point(&range.end, &snapshot);
 3918                            let start_point = TP::to_point(&range.start, &snapshot);
 3919                            (start_point..end_point, text)
 3920                        })
 3921                        .sorted_by_key(|(range, _)| range.start)
 3922                        .collect::<Vec<_>>();
 3923                    buffer.edit(edits, None, cx);
 3924                })
 3925            }
 3926
 3927            this.refresh_inline_completion(true, false, cx);
 3928        });
 3929
 3930        let show_new_completions_on_confirm = completion
 3931            .confirm
 3932            .as_ref()
 3933            .map_or(false, |confirm| confirm(intent, cx));
 3934        if show_new_completions_on_confirm {
 3935            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3936        }
 3937
 3938        let provider = self.completion_provider.as_ref()?;
 3939        let apply_edits = provider.apply_additional_edits_for_completion(
 3940            buffer_handle,
 3941            completion.clone(),
 3942            true,
 3943            cx,
 3944        );
 3945
 3946        let editor_settings = EditorSettings::get_global(cx);
 3947        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3948            // After the code completion is finished, users often want to know what signatures are needed.
 3949            // so we should automatically call signature_help
 3950            self.show_signature_help(&ShowSignatureHelp, cx);
 3951        }
 3952
 3953        Some(cx.foreground_executor().spawn(async move {
 3954            apply_edits.await?;
 3955            Ok(())
 3956        }))
 3957    }
 3958
 3959    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3960        let mut context_menu = self.context_menu.borrow_mut();
 3961        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 3962            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 3963                // Toggle if we're selecting the same one
 3964                *context_menu = None;
 3965                cx.notify();
 3966                return;
 3967            } else {
 3968                // Otherwise, clear it and start a new one
 3969                *context_menu = None;
 3970                cx.notify();
 3971            }
 3972        }
 3973        drop(context_menu);
 3974        let snapshot = self.snapshot(cx);
 3975        let deployed_from_indicator = action.deployed_from_indicator;
 3976        let mut task = self.code_actions_task.take();
 3977        let action = action.clone();
 3978        cx.spawn(|editor, mut cx| async move {
 3979            while let Some(prev_task) = task {
 3980                prev_task.await.log_err();
 3981                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 3982            }
 3983
 3984            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 3985                if editor.focus_handle.is_focused(cx) {
 3986                    let multibuffer_point = action
 3987                        .deployed_from_indicator
 3988                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 3989                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 3990                    let (buffer, buffer_row) = snapshot
 3991                        .buffer_snapshot
 3992                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 3993                        .and_then(|(buffer_snapshot, range)| {
 3994                            editor
 3995                                .buffer
 3996                                .read(cx)
 3997                                .buffer(buffer_snapshot.remote_id())
 3998                                .map(|buffer| (buffer, range.start.row))
 3999                        })?;
 4000                    let (_, code_actions) = editor
 4001                        .available_code_actions
 4002                        .clone()
 4003                        .and_then(|(location, code_actions)| {
 4004                            let snapshot = location.buffer.read(cx).snapshot();
 4005                            let point_range = location.range.to_point(&snapshot);
 4006                            let point_range = point_range.start.row..=point_range.end.row;
 4007                            if point_range.contains(&buffer_row) {
 4008                                Some((location, code_actions))
 4009                            } else {
 4010                                None
 4011                            }
 4012                        })
 4013                        .unzip();
 4014                    let buffer_id = buffer.read(cx).remote_id();
 4015                    let tasks = editor
 4016                        .tasks
 4017                        .get(&(buffer_id, buffer_row))
 4018                        .map(|t| Arc::new(t.to_owned()));
 4019                    if tasks.is_none() && code_actions.is_none() {
 4020                        return None;
 4021                    }
 4022
 4023                    editor.completion_tasks.clear();
 4024                    editor.discard_inline_completion(false, cx);
 4025                    let task_context =
 4026                        tasks
 4027                            .as_ref()
 4028                            .zip(editor.project.clone())
 4029                            .map(|(tasks, project)| {
 4030                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4031                            });
 4032
 4033                    Some(cx.spawn(|editor, mut cx| async move {
 4034                        let task_context = match task_context {
 4035                            Some(task_context) => task_context.await,
 4036                            None => None,
 4037                        };
 4038                        let resolved_tasks =
 4039                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4040                                Rc::new(ResolvedTasks {
 4041                                    templates: tasks.resolve(&task_context).collect(),
 4042                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4043                                        multibuffer_point.row,
 4044                                        tasks.column,
 4045                                    )),
 4046                                })
 4047                            });
 4048                        let spawn_straight_away = resolved_tasks
 4049                            .as_ref()
 4050                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4051                            && code_actions
 4052                                .as_ref()
 4053                                .map_or(true, |actions| actions.is_empty());
 4054                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4055                            *editor.context_menu.borrow_mut() =
 4056                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4057                                    buffer,
 4058                                    actions: CodeActionContents {
 4059                                        tasks: resolved_tasks,
 4060                                        actions: code_actions,
 4061                                    },
 4062                                    selected_item: Default::default(),
 4063                                    scroll_handle: UniformListScrollHandle::default(),
 4064                                    deployed_from_indicator,
 4065                                }));
 4066                            if spawn_straight_away {
 4067                                if let Some(task) = editor.confirm_code_action(
 4068                                    &ConfirmCodeAction { item_ix: Some(0) },
 4069                                    cx,
 4070                                ) {
 4071                                    cx.notify();
 4072                                    return task;
 4073                                }
 4074                            }
 4075                            cx.notify();
 4076                            Task::ready(Ok(()))
 4077                        }) {
 4078                            task.await
 4079                        } else {
 4080                            Ok(())
 4081                        }
 4082                    }))
 4083                } else {
 4084                    Some(Task::ready(Ok(())))
 4085                }
 4086            })?;
 4087            if let Some(task) = spawned_test_task {
 4088                task.await?;
 4089            }
 4090
 4091            Ok::<_, anyhow::Error>(())
 4092        })
 4093        .detach_and_log_err(cx);
 4094    }
 4095
 4096    pub fn confirm_code_action(
 4097        &mut self,
 4098        action: &ConfirmCodeAction,
 4099        cx: &mut ViewContext<Self>,
 4100    ) -> Option<Task<Result<()>>> {
 4101        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4102            menu
 4103        } else {
 4104            return None;
 4105        };
 4106        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4107        let action = actions_menu.actions.get(action_ix)?;
 4108        let title = action.label();
 4109        let buffer = actions_menu.buffer;
 4110        let workspace = self.workspace()?;
 4111
 4112        match action {
 4113            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4114                workspace.update(cx, |workspace, cx| {
 4115                    workspace::tasks::schedule_resolved_task(
 4116                        workspace,
 4117                        task_source_kind,
 4118                        resolved_task,
 4119                        false,
 4120                        cx,
 4121                    );
 4122
 4123                    Some(Task::ready(Ok(())))
 4124                })
 4125            }
 4126            CodeActionsItem::CodeAction {
 4127                excerpt_id,
 4128                action,
 4129                provider,
 4130            } => {
 4131                let apply_code_action =
 4132                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4133                let workspace = workspace.downgrade();
 4134                Some(cx.spawn(|editor, cx| async move {
 4135                    let project_transaction = apply_code_action.await?;
 4136                    Self::open_project_transaction(
 4137                        &editor,
 4138                        workspace,
 4139                        project_transaction,
 4140                        title,
 4141                        cx,
 4142                    )
 4143                    .await
 4144                }))
 4145            }
 4146        }
 4147    }
 4148
 4149    pub async fn open_project_transaction(
 4150        this: &WeakView<Editor>,
 4151        workspace: WeakView<Workspace>,
 4152        transaction: ProjectTransaction,
 4153        title: String,
 4154        mut cx: AsyncWindowContext,
 4155    ) -> Result<()> {
 4156        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4157        cx.update(|cx| {
 4158            entries.sort_unstable_by_key(|(buffer, _)| {
 4159                buffer.read(cx).file().map(|f| f.path().clone())
 4160            });
 4161        })?;
 4162
 4163        // If the project transaction's edits are all contained within this editor, then
 4164        // avoid opening a new editor to display them.
 4165
 4166        if let Some((buffer, transaction)) = entries.first() {
 4167            if entries.len() == 1 {
 4168                let excerpt = this.update(&mut cx, |editor, cx| {
 4169                    editor
 4170                        .buffer()
 4171                        .read(cx)
 4172                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4173                })?;
 4174                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4175                    if excerpted_buffer == *buffer {
 4176                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4177                            let excerpt_range = excerpt_range.to_offset(buffer);
 4178                            buffer
 4179                                .edited_ranges_for_transaction::<usize>(transaction)
 4180                                .all(|range| {
 4181                                    excerpt_range.start <= range.start
 4182                                        && excerpt_range.end >= range.end
 4183                                })
 4184                        })?;
 4185
 4186                        if all_edits_within_excerpt {
 4187                            return Ok(());
 4188                        }
 4189                    }
 4190                }
 4191            }
 4192        } else {
 4193            return Ok(());
 4194        }
 4195
 4196        let mut ranges_to_highlight = Vec::new();
 4197        let excerpt_buffer = cx.new_model(|cx| {
 4198            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4199            for (buffer_handle, transaction) in &entries {
 4200                let buffer = buffer_handle.read(cx);
 4201                ranges_to_highlight.extend(
 4202                    multibuffer.push_excerpts_with_context_lines(
 4203                        buffer_handle.clone(),
 4204                        buffer
 4205                            .edited_ranges_for_transaction::<usize>(transaction)
 4206                            .collect(),
 4207                        DEFAULT_MULTIBUFFER_CONTEXT,
 4208                        cx,
 4209                    ),
 4210                );
 4211            }
 4212            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4213            multibuffer
 4214        })?;
 4215
 4216        workspace.update(&mut cx, |workspace, cx| {
 4217            let project = workspace.project().clone();
 4218            let editor =
 4219                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4220            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4221            editor.update(cx, |editor, cx| {
 4222                editor.highlight_background::<Self>(
 4223                    &ranges_to_highlight,
 4224                    |theme| theme.editor_highlighted_line_background,
 4225                    cx,
 4226                );
 4227            });
 4228        })?;
 4229
 4230        Ok(())
 4231    }
 4232
 4233    pub fn clear_code_action_providers(&mut self) {
 4234        self.code_action_providers.clear();
 4235        self.available_code_actions.take();
 4236    }
 4237
 4238    pub fn push_code_action_provider(
 4239        &mut self,
 4240        provider: Rc<dyn CodeActionProvider>,
 4241        cx: &mut ViewContext<Self>,
 4242    ) {
 4243        self.code_action_providers.push(provider);
 4244        self.refresh_code_actions(cx);
 4245    }
 4246
 4247    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4248        let buffer = self.buffer.read(cx);
 4249        let newest_selection = self.selections.newest_anchor().clone();
 4250        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4251        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4252        if start_buffer != end_buffer {
 4253            return None;
 4254        }
 4255
 4256        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4257            cx.background_executor()
 4258                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4259                .await;
 4260
 4261            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4262                let providers = this.code_action_providers.clone();
 4263                let tasks = this
 4264                    .code_action_providers
 4265                    .iter()
 4266                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4267                    .collect::<Vec<_>>();
 4268                (providers, tasks)
 4269            })?;
 4270
 4271            let mut actions = Vec::new();
 4272            for (provider, provider_actions) in
 4273                providers.into_iter().zip(future::join_all(tasks).await)
 4274            {
 4275                if let Some(provider_actions) = provider_actions.log_err() {
 4276                    actions.extend(provider_actions.into_iter().map(|action| {
 4277                        AvailableCodeAction {
 4278                            excerpt_id: newest_selection.start.excerpt_id,
 4279                            action,
 4280                            provider: provider.clone(),
 4281                        }
 4282                    }));
 4283                }
 4284            }
 4285
 4286            this.update(&mut cx, |this, cx| {
 4287                this.available_code_actions = if actions.is_empty() {
 4288                    None
 4289                } else {
 4290                    Some((
 4291                        Location {
 4292                            buffer: start_buffer,
 4293                            range: start..end,
 4294                        },
 4295                        actions.into(),
 4296                    ))
 4297                };
 4298                cx.notify();
 4299            })
 4300        }));
 4301        None
 4302    }
 4303
 4304    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4305        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4306            self.show_git_blame_inline = false;
 4307
 4308            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4309                cx.background_executor().timer(delay).await;
 4310
 4311                this.update(&mut cx, |this, cx| {
 4312                    this.show_git_blame_inline = true;
 4313                    cx.notify();
 4314                })
 4315                .log_err();
 4316            }));
 4317        }
 4318    }
 4319
 4320    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4321        if self.pending_rename.is_some() {
 4322            return None;
 4323        }
 4324
 4325        let provider = self.semantics_provider.clone()?;
 4326        let buffer = self.buffer.read(cx);
 4327        let newest_selection = self.selections.newest_anchor().clone();
 4328        let cursor_position = newest_selection.head();
 4329        let (cursor_buffer, cursor_buffer_position) =
 4330            buffer.text_anchor_for_position(cursor_position, cx)?;
 4331        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4332        if cursor_buffer != tail_buffer {
 4333            return None;
 4334        }
 4335        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4336        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4337            cx.background_executor()
 4338                .timer(Duration::from_millis(debounce))
 4339                .await;
 4340
 4341            let highlights = if let Some(highlights) = cx
 4342                .update(|cx| {
 4343                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4344                })
 4345                .ok()
 4346                .flatten()
 4347            {
 4348                highlights.await.log_err()
 4349            } else {
 4350                None
 4351            };
 4352
 4353            if let Some(highlights) = highlights {
 4354                this.update(&mut cx, |this, cx| {
 4355                    if this.pending_rename.is_some() {
 4356                        return;
 4357                    }
 4358
 4359                    let buffer_id = cursor_position.buffer_id;
 4360                    let buffer = this.buffer.read(cx);
 4361                    if !buffer
 4362                        .text_anchor_for_position(cursor_position, cx)
 4363                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4364                    {
 4365                        return;
 4366                    }
 4367
 4368                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4369                    let mut write_ranges = Vec::new();
 4370                    let mut read_ranges = Vec::new();
 4371                    for highlight in highlights {
 4372                        for (excerpt_id, excerpt_range) in
 4373                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4374                        {
 4375                            let start = highlight
 4376                                .range
 4377                                .start
 4378                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4379                            let end = highlight
 4380                                .range
 4381                                .end
 4382                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4383                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4384                                continue;
 4385                            }
 4386
 4387                            let range = Anchor {
 4388                                buffer_id,
 4389                                excerpt_id,
 4390                                text_anchor: start,
 4391                            }..Anchor {
 4392                                buffer_id,
 4393                                excerpt_id,
 4394                                text_anchor: end,
 4395                            };
 4396                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4397                                write_ranges.push(range);
 4398                            } else {
 4399                                read_ranges.push(range);
 4400                            }
 4401                        }
 4402                    }
 4403
 4404                    this.highlight_background::<DocumentHighlightRead>(
 4405                        &read_ranges,
 4406                        |theme| theme.editor_document_highlight_read_background,
 4407                        cx,
 4408                    );
 4409                    this.highlight_background::<DocumentHighlightWrite>(
 4410                        &write_ranges,
 4411                        |theme| theme.editor_document_highlight_write_background,
 4412                        cx,
 4413                    );
 4414                    cx.notify();
 4415                })
 4416                .log_err();
 4417            }
 4418        }));
 4419        None
 4420    }
 4421
 4422    pub fn refresh_inline_completion(
 4423        &mut self,
 4424        debounce: bool,
 4425        user_requested: bool,
 4426        cx: &mut ViewContext<Self>,
 4427    ) -> Option<()> {
 4428        let provider = self.inline_completion_provider()?;
 4429        let cursor = self.selections.newest_anchor().head();
 4430        let (buffer, cursor_buffer_position) =
 4431            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4432
 4433        if !user_requested
 4434            && (!self.enable_inline_completions
 4435                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4436                || !self.is_focused(cx))
 4437        {
 4438            self.discard_inline_completion(false, cx);
 4439            return None;
 4440        }
 4441
 4442        self.update_visible_inline_completion(cx);
 4443        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4444        Some(())
 4445    }
 4446
 4447    fn cycle_inline_completion(
 4448        &mut self,
 4449        direction: Direction,
 4450        cx: &mut ViewContext<Self>,
 4451    ) -> Option<()> {
 4452        let provider = self.inline_completion_provider()?;
 4453        let cursor = self.selections.newest_anchor().head();
 4454        let (buffer, cursor_buffer_position) =
 4455            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4456        if !self.enable_inline_completions
 4457            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4458        {
 4459            return None;
 4460        }
 4461
 4462        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4463        self.update_visible_inline_completion(cx);
 4464
 4465        Some(())
 4466    }
 4467
 4468    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4469        if !self.has_active_inline_completion() {
 4470            self.refresh_inline_completion(false, true, cx);
 4471            return;
 4472        }
 4473
 4474        self.update_visible_inline_completion(cx);
 4475    }
 4476
 4477    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4478        self.show_cursor_names(cx);
 4479    }
 4480
 4481    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4482        self.show_cursor_names = true;
 4483        cx.notify();
 4484        cx.spawn(|this, mut cx| async move {
 4485            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4486            this.update(&mut cx, |this, cx| {
 4487                this.show_cursor_names = false;
 4488                cx.notify()
 4489            })
 4490            .ok()
 4491        })
 4492        .detach();
 4493    }
 4494
 4495    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4496        if self.has_active_inline_completion() {
 4497            self.cycle_inline_completion(Direction::Next, cx);
 4498        } else {
 4499            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4500            if is_copilot_disabled {
 4501                cx.propagate();
 4502            }
 4503        }
 4504    }
 4505
 4506    pub fn previous_inline_completion(
 4507        &mut self,
 4508        _: &PreviousInlineCompletion,
 4509        cx: &mut ViewContext<Self>,
 4510    ) {
 4511        if self.has_active_inline_completion() {
 4512            self.cycle_inline_completion(Direction::Prev, cx);
 4513        } else {
 4514            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4515            if is_copilot_disabled {
 4516                cx.propagate();
 4517            }
 4518        }
 4519    }
 4520
 4521    pub fn accept_inline_completion(
 4522        &mut self,
 4523        _: &AcceptInlineCompletion,
 4524        cx: &mut ViewContext<Self>,
 4525    ) {
 4526        self.hide_context_menu(cx);
 4527
 4528        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4529            return;
 4530        };
 4531
 4532        self.report_inline_completion_event(true, cx);
 4533
 4534        match &active_inline_completion.completion {
 4535            InlineCompletion::Move(position) => {
 4536                let position = *position;
 4537                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4538                    selections.select_anchor_ranges([position..position]);
 4539                });
 4540            }
 4541            InlineCompletion::Edit(edits) => {
 4542                if let Some(provider) = self.inline_completion_provider() {
 4543                    provider.accept(cx);
 4544                }
 4545
 4546                let snapshot = self.buffer.read(cx).snapshot(cx);
 4547                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4548
 4549                self.buffer.update(cx, |buffer, cx| {
 4550                    buffer.edit(edits.iter().cloned(), None, cx)
 4551                });
 4552
 4553                self.change_selections(None, cx, |s| {
 4554                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4555                });
 4556
 4557                self.update_visible_inline_completion(cx);
 4558                if self.active_inline_completion.is_none() {
 4559                    self.refresh_inline_completion(true, true, cx);
 4560                }
 4561
 4562                cx.notify();
 4563            }
 4564        }
 4565    }
 4566
 4567    pub fn accept_partial_inline_completion(
 4568        &mut self,
 4569        _: &AcceptPartialInlineCompletion,
 4570        cx: &mut ViewContext<Self>,
 4571    ) {
 4572        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4573            return;
 4574        };
 4575        if self.selections.count() != 1 {
 4576            return;
 4577        }
 4578
 4579        self.report_inline_completion_event(true, cx);
 4580
 4581        match &active_inline_completion.completion {
 4582            InlineCompletion::Move(position) => {
 4583                let position = *position;
 4584                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4585                    selections.select_anchor_ranges([position..position]);
 4586                });
 4587            }
 4588            InlineCompletion::Edit(edits) => {
 4589                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4590                    let text = edits[0].1.as_str();
 4591                    let mut partial_completion = text
 4592                        .chars()
 4593                        .by_ref()
 4594                        .take_while(|c| c.is_alphabetic())
 4595                        .collect::<String>();
 4596                    if partial_completion.is_empty() {
 4597                        partial_completion = text
 4598                            .chars()
 4599                            .by_ref()
 4600                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4601                            .collect::<String>();
 4602                    }
 4603
 4604                    cx.emit(EditorEvent::InputHandled {
 4605                        utf16_range_to_replace: None,
 4606                        text: partial_completion.clone().into(),
 4607                    });
 4608
 4609                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4610
 4611                    self.refresh_inline_completion(true, true, cx);
 4612                    cx.notify();
 4613                }
 4614            }
 4615        }
 4616    }
 4617
 4618    fn discard_inline_completion(
 4619        &mut self,
 4620        should_report_inline_completion_event: bool,
 4621        cx: &mut ViewContext<Self>,
 4622    ) -> bool {
 4623        if should_report_inline_completion_event {
 4624            self.report_inline_completion_event(false, cx);
 4625        }
 4626
 4627        if let Some(provider) = self.inline_completion_provider() {
 4628            provider.discard(cx);
 4629        }
 4630
 4631        self.take_active_inline_completion(cx).is_some()
 4632    }
 4633
 4634    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4635        let Some(provider) = self.inline_completion_provider() else {
 4636            return;
 4637        };
 4638        let Some(project) = self.project.as_ref() else {
 4639            return;
 4640        };
 4641        let Some((_, buffer, _)) = self
 4642            .buffer
 4643            .read(cx)
 4644            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4645        else {
 4646            return;
 4647        };
 4648
 4649        let project = project.read(cx);
 4650        let extension = buffer
 4651            .read(cx)
 4652            .file()
 4653            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4654        project.client().telemetry().report_inline_completion_event(
 4655            provider.name().into(),
 4656            accepted,
 4657            extension,
 4658        );
 4659    }
 4660
 4661    pub fn has_active_inline_completion(&self) -> bool {
 4662        self.active_inline_completion.is_some()
 4663    }
 4664
 4665    fn take_active_inline_completion(
 4666        &mut self,
 4667        cx: &mut ViewContext<Self>,
 4668    ) -> Option<InlineCompletion> {
 4669        let active_inline_completion = self.active_inline_completion.take()?;
 4670        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4671        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4672        Some(active_inline_completion.completion)
 4673    }
 4674
 4675    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4676        let selection = self.selections.newest_anchor();
 4677        let cursor = selection.head();
 4678        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4679        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4680        let excerpt_id = cursor.excerpt_id;
 4681
 4682        if !offset_selection.is_empty()
 4683            || self
 4684                .active_inline_completion
 4685                .as_ref()
 4686                .map_or(false, |completion| {
 4687                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4688                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4689                    !invalidation_range.contains(&offset_selection.head())
 4690                })
 4691        {
 4692            self.discard_inline_completion(false, cx);
 4693            return None;
 4694        }
 4695
 4696        self.take_active_inline_completion(cx);
 4697        let provider = self.inline_completion_provider()?;
 4698
 4699        let (buffer, cursor_buffer_position) =
 4700            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4701
 4702        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4703        let edits = completion
 4704            .edits
 4705            .into_iter()
 4706            .map(|(range, new_text)| {
 4707                (
 4708                    multibuffer
 4709                        .anchor_in_excerpt(excerpt_id, range.start)
 4710                        .unwrap()
 4711                        ..multibuffer
 4712                            .anchor_in_excerpt(excerpt_id, range.end)
 4713                            .unwrap(),
 4714                    new_text,
 4715                )
 4716            })
 4717            .collect::<Vec<_>>();
 4718        if edits.is_empty() {
 4719            return None;
 4720        }
 4721
 4722        let first_edit_start = edits.first().unwrap().0.start;
 4723        let edit_start_row = first_edit_start
 4724            .to_point(&multibuffer)
 4725            .row
 4726            .saturating_sub(2);
 4727
 4728        let last_edit_end = edits.last().unwrap().0.end;
 4729        let edit_end_row = cmp::min(
 4730            multibuffer.max_point().row,
 4731            last_edit_end.to_point(&multibuffer).row + 2,
 4732        );
 4733
 4734        let cursor_row = cursor.to_point(&multibuffer).row;
 4735
 4736        let mut inlay_ids = Vec::new();
 4737        let invalidation_row_range;
 4738        let completion;
 4739        if cursor_row < edit_start_row {
 4740            invalidation_row_range = cursor_row..edit_end_row;
 4741            completion = InlineCompletion::Move(first_edit_start);
 4742        } else if cursor_row > edit_end_row {
 4743            invalidation_row_range = edit_start_row..cursor_row;
 4744            completion = InlineCompletion::Move(first_edit_start);
 4745        } else {
 4746            if edits
 4747                .iter()
 4748                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4749            {
 4750                let mut inlays = Vec::new();
 4751                for (range, new_text) in &edits {
 4752                    let inlay = Inlay::inline_completion(
 4753                        post_inc(&mut self.next_inlay_id),
 4754                        range.start,
 4755                        new_text.as_str(),
 4756                    );
 4757                    inlay_ids.push(inlay.id);
 4758                    inlays.push(inlay);
 4759                }
 4760
 4761                self.splice_inlays(vec![], inlays, cx);
 4762            } else {
 4763                let background_color = cx.theme().status().deleted_background;
 4764                self.highlight_text::<InlineCompletionHighlight>(
 4765                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4766                    HighlightStyle {
 4767                        background_color: Some(background_color),
 4768                        ..Default::default()
 4769                    },
 4770                    cx,
 4771                );
 4772            }
 4773
 4774            invalidation_row_range = edit_start_row..edit_end_row;
 4775            completion = InlineCompletion::Edit(edits);
 4776        };
 4777
 4778        let invalidation_range = multibuffer
 4779            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4780            ..multibuffer.anchor_after(Point::new(
 4781                invalidation_row_range.end,
 4782                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4783            ));
 4784
 4785        self.active_inline_completion = Some(InlineCompletionState {
 4786            inlay_ids,
 4787            completion,
 4788            invalidation_range,
 4789        });
 4790        cx.notify();
 4791
 4792        Some(())
 4793    }
 4794
 4795    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4796        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4797    }
 4798
 4799    fn render_code_actions_indicator(
 4800        &self,
 4801        _style: &EditorStyle,
 4802        row: DisplayRow,
 4803        is_active: bool,
 4804        cx: &mut ViewContext<Self>,
 4805    ) -> Option<IconButton> {
 4806        if self.available_code_actions.is_some() {
 4807            Some(
 4808                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4809                    .shape(ui::IconButtonShape::Square)
 4810                    .icon_size(IconSize::XSmall)
 4811                    .icon_color(Color::Muted)
 4812                    .toggle_state(is_active)
 4813                    .tooltip({
 4814                        let focus_handle = self.focus_handle.clone();
 4815                        move |cx| {
 4816                            Tooltip::for_action_in(
 4817                                "Toggle Code Actions",
 4818                                &ToggleCodeActions {
 4819                                    deployed_from_indicator: None,
 4820                                },
 4821                                &focus_handle,
 4822                                cx,
 4823                            )
 4824                        }
 4825                    })
 4826                    .on_click(cx.listener(move |editor, _e, cx| {
 4827                        editor.focus(cx);
 4828                        editor.toggle_code_actions(
 4829                            &ToggleCodeActions {
 4830                                deployed_from_indicator: Some(row),
 4831                            },
 4832                            cx,
 4833                        );
 4834                    })),
 4835            )
 4836        } else {
 4837            None
 4838        }
 4839    }
 4840
 4841    fn clear_tasks(&mut self) {
 4842        self.tasks.clear()
 4843    }
 4844
 4845    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4846        if self.tasks.insert(key, value).is_some() {
 4847            // This case should hopefully be rare, but just in case...
 4848            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4849        }
 4850    }
 4851
 4852    fn build_tasks_context(
 4853        project: &Model<Project>,
 4854        buffer: &Model<Buffer>,
 4855        buffer_row: u32,
 4856        tasks: &Arc<RunnableTasks>,
 4857        cx: &mut ViewContext<Self>,
 4858    ) -> Task<Option<task::TaskContext>> {
 4859        let position = Point::new(buffer_row, tasks.column);
 4860        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4861        let location = Location {
 4862            buffer: buffer.clone(),
 4863            range: range_start..range_start,
 4864        };
 4865        // Fill in the environmental variables from the tree-sitter captures
 4866        let mut captured_task_variables = TaskVariables::default();
 4867        for (capture_name, value) in tasks.extra_variables.clone() {
 4868            captured_task_variables.insert(
 4869                task::VariableName::Custom(capture_name.into()),
 4870                value.clone(),
 4871            );
 4872        }
 4873        project.update(cx, |project, cx| {
 4874            project.task_store().update(cx, |task_store, cx| {
 4875                task_store.task_context_for_location(captured_task_variables, location, cx)
 4876            })
 4877        })
 4878    }
 4879
 4880    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4881        let Some((workspace, _)) = self.workspace.clone() else {
 4882            return;
 4883        };
 4884        let Some(project) = self.project.clone() else {
 4885            return;
 4886        };
 4887
 4888        // Try to find a closest, enclosing node using tree-sitter that has a
 4889        // task
 4890        let Some((buffer, buffer_row, tasks)) = self
 4891            .find_enclosing_node_task(cx)
 4892            // Or find the task that's closest in row-distance.
 4893            .or_else(|| self.find_closest_task(cx))
 4894        else {
 4895            return;
 4896        };
 4897
 4898        let reveal_strategy = action.reveal;
 4899        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 4900        cx.spawn(|_, mut cx| async move {
 4901            let context = task_context.await?;
 4902            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 4903
 4904            let resolved = resolved_task.resolved.as_mut()?;
 4905            resolved.reveal = reveal_strategy;
 4906
 4907            workspace
 4908                .update(&mut cx, |workspace, cx| {
 4909                    workspace::tasks::schedule_resolved_task(
 4910                        workspace,
 4911                        task_source_kind,
 4912                        resolved_task,
 4913                        false,
 4914                        cx,
 4915                    );
 4916                })
 4917                .ok()
 4918        })
 4919        .detach();
 4920    }
 4921
 4922    fn find_closest_task(
 4923        &mut self,
 4924        cx: &mut ViewContext<Self>,
 4925    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4926        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 4927
 4928        let ((buffer_id, row), tasks) = self
 4929            .tasks
 4930            .iter()
 4931            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 4932
 4933        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 4934        let tasks = Arc::new(tasks.to_owned());
 4935        Some((buffer, *row, tasks))
 4936    }
 4937
 4938    fn find_enclosing_node_task(
 4939        &mut self,
 4940        cx: &mut ViewContext<Self>,
 4941    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4942        let snapshot = self.buffer.read(cx).snapshot(cx);
 4943        let offset = self.selections.newest::<usize>(cx).head();
 4944        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 4945        let buffer_id = excerpt.buffer().remote_id();
 4946
 4947        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 4948        let mut cursor = layer.node().walk();
 4949
 4950        while cursor.goto_first_child_for_byte(offset).is_some() {
 4951            if cursor.node().end_byte() == offset {
 4952                cursor.goto_next_sibling();
 4953            }
 4954        }
 4955
 4956        // Ascend to the smallest ancestor that contains the range and has a task.
 4957        loop {
 4958            let node = cursor.node();
 4959            let node_range = node.byte_range();
 4960            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 4961
 4962            // Check if this node contains our offset
 4963            if node_range.start <= offset && node_range.end >= offset {
 4964                // If it contains offset, check for task
 4965                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 4966                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 4967                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 4968                }
 4969            }
 4970
 4971            if !cursor.goto_parent() {
 4972                break;
 4973            }
 4974        }
 4975        None
 4976    }
 4977
 4978    fn render_run_indicator(
 4979        &self,
 4980        _style: &EditorStyle,
 4981        is_active: bool,
 4982        row: DisplayRow,
 4983        cx: &mut ViewContext<Self>,
 4984    ) -> IconButton {
 4985        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 4986            .shape(ui::IconButtonShape::Square)
 4987            .icon_size(IconSize::XSmall)
 4988            .icon_color(Color::Muted)
 4989            .toggle_state(is_active)
 4990            .on_click(cx.listener(move |editor, _e, cx| {
 4991                editor.focus(cx);
 4992                editor.toggle_code_actions(
 4993                    &ToggleCodeActions {
 4994                        deployed_from_indicator: Some(row),
 4995                    },
 4996                    cx,
 4997                );
 4998            }))
 4999    }
 5000
 5001    pub fn context_menu_visible(&self) -> bool {
 5002        self.context_menu
 5003            .borrow()
 5004            .as_ref()
 5005            .map_or(false, |menu| menu.visible())
 5006    }
 5007
 5008    fn render_context_menu(
 5009        &self,
 5010        cursor_position: DisplayPoint,
 5011        style: &EditorStyle,
 5012        max_height: Pixels,
 5013        cx: &mut ViewContext<Editor>,
 5014    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5015        self.context_menu.borrow().as_ref().map(|menu| {
 5016            menu.render(
 5017                cursor_position,
 5018                style,
 5019                max_height,
 5020                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5021                cx,
 5022            )
 5023        })
 5024    }
 5025
 5026    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5027        cx.notify();
 5028        self.completion_tasks.clear();
 5029        self.context_menu.borrow_mut().take()
 5030    }
 5031
 5032    fn show_snippet_choices(
 5033        &mut self,
 5034        choices: &Vec<String>,
 5035        selection: Range<Anchor>,
 5036        cx: &mut ViewContext<Self>,
 5037    ) {
 5038        if selection.start.buffer_id.is_none() {
 5039            return;
 5040        }
 5041        let buffer_id = selection.start.buffer_id.unwrap();
 5042        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5043        let id = post_inc(&mut self.next_completion_id);
 5044
 5045        if let Some(buffer) = buffer {
 5046            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5047                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5048            ));
 5049        }
 5050    }
 5051
 5052    pub fn insert_snippet(
 5053        &mut self,
 5054        insertion_ranges: &[Range<usize>],
 5055        snippet: Snippet,
 5056        cx: &mut ViewContext<Self>,
 5057    ) -> Result<()> {
 5058        struct Tabstop<T> {
 5059            is_end_tabstop: bool,
 5060            ranges: Vec<Range<T>>,
 5061            choices: Option<Vec<String>>,
 5062        }
 5063
 5064        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5065            let snippet_text: Arc<str> = snippet.text.clone().into();
 5066            buffer.edit(
 5067                insertion_ranges
 5068                    .iter()
 5069                    .cloned()
 5070                    .map(|range| (range, snippet_text.clone())),
 5071                Some(AutoindentMode::EachLine),
 5072                cx,
 5073            );
 5074
 5075            let snapshot = &*buffer.read(cx);
 5076            let snippet = &snippet;
 5077            snippet
 5078                .tabstops
 5079                .iter()
 5080                .map(|tabstop| {
 5081                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5082                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5083                    });
 5084                    let mut tabstop_ranges = tabstop
 5085                        .ranges
 5086                        .iter()
 5087                        .flat_map(|tabstop_range| {
 5088                            let mut delta = 0_isize;
 5089                            insertion_ranges.iter().map(move |insertion_range| {
 5090                                let insertion_start = insertion_range.start as isize + delta;
 5091                                delta +=
 5092                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5093
 5094                                let start = ((insertion_start + tabstop_range.start) as usize)
 5095                                    .min(snapshot.len());
 5096                                let end = ((insertion_start + tabstop_range.end) as usize)
 5097                                    .min(snapshot.len());
 5098                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5099                            })
 5100                        })
 5101                        .collect::<Vec<_>>();
 5102                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5103
 5104                    Tabstop {
 5105                        is_end_tabstop,
 5106                        ranges: tabstop_ranges,
 5107                        choices: tabstop.choices.clone(),
 5108                    }
 5109                })
 5110                .collect::<Vec<_>>()
 5111        });
 5112        if let Some(tabstop) = tabstops.first() {
 5113            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5114                s.select_ranges(tabstop.ranges.iter().cloned());
 5115            });
 5116
 5117            if let Some(choices) = &tabstop.choices {
 5118                if let Some(selection) = tabstop.ranges.first() {
 5119                    self.show_snippet_choices(choices, selection.clone(), cx)
 5120                }
 5121            }
 5122
 5123            // If we're already at the last tabstop and it's at the end of the snippet,
 5124            // we're done, we don't need to keep the state around.
 5125            if !tabstop.is_end_tabstop {
 5126                let choices = tabstops
 5127                    .iter()
 5128                    .map(|tabstop| tabstop.choices.clone())
 5129                    .collect();
 5130
 5131                let ranges = tabstops
 5132                    .into_iter()
 5133                    .map(|tabstop| tabstop.ranges)
 5134                    .collect::<Vec<_>>();
 5135
 5136                self.snippet_stack.push(SnippetState {
 5137                    active_index: 0,
 5138                    ranges,
 5139                    choices,
 5140                });
 5141            }
 5142
 5143            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5144            if self.autoclose_regions.is_empty() {
 5145                let snapshot = self.buffer.read(cx).snapshot(cx);
 5146                for selection in &mut self.selections.all::<Point>(cx) {
 5147                    let selection_head = selection.head();
 5148                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5149                        continue;
 5150                    };
 5151
 5152                    let mut bracket_pair = None;
 5153                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5154                    let prev_chars = snapshot
 5155                        .reversed_chars_at(selection_head)
 5156                        .collect::<String>();
 5157                    for (pair, enabled) in scope.brackets() {
 5158                        if enabled
 5159                            && pair.close
 5160                            && prev_chars.starts_with(pair.start.as_str())
 5161                            && next_chars.starts_with(pair.end.as_str())
 5162                        {
 5163                            bracket_pair = Some(pair.clone());
 5164                            break;
 5165                        }
 5166                    }
 5167                    if let Some(pair) = bracket_pair {
 5168                        let start = snapshot.anchor_after(selection_head);
 5169                        let end = snapshot.anchor_after(selection_head);
 5170                        self.autoclose_regions.push(AutocloseRegion {
 5171                            selection_id: selection.id,
 5172                            range: start..end,
 5173                            pair,
 5174                        });
 5175                    }
 5176                }
 5177            }
 5178        }
 5179        Ok(())
 5180    }
 5181
 5182    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5183        self.move_to_snippet_tabstop(Bias::Right, cx)
 5184    }
 5185
 5186    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5187        self.move_to_snippet_tabstop(Bias::Left, cx)
 5188    }
 5189
 5190    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5191        if let Some(mut snippet) = self.snippet_stack.pop() {
 5192            match bias {
 5193                Bias::Left => {
 5194                    if snippet.active_index > 0 {
 5195                        snippet.active_index -= 1;
 5196                    } else {
 5197                        self.snippet_stack.push(snippet);
 5198                        return false;
 5199                    }
 5200                }
 5201                Bias::Right => {
 5202                    if snippet.active_index + 1 < snippet.ranges.len() {
 5203                        snippet.active_index += 1;
 5204                    } else {
 5205                        self.snippet_stack.push(snippet);
 5206                        return false;
 5207                    }
 5208                }
 5209            }
 5210            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5211                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5212                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5213                });
 5214
 5215                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5216                    if let Some(selection) = current_ranges.first() {
 5217                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5218                    }
 5219                }
 5220
 5221                // If snippet state is not at the last tabstop, push it back on the stack
 5222                if snippet.active_index + 1 < snippet.ranges.len() {
 5223                    self.snippet_stack.push(snippet);
 5224                }
 5225                return true;
 5226            }
 5227        }
 5228
 5229        false
 5230    }
 5231
 5232    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5233        self.transact(cx, |this, cx| {
 5234            this.select_all(&SelectAll, cx);
 5235            this.insert("", cx);
 5236        });
 5237    }
 5238
 5239    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5240        self.transact(cx, |this, cx| {
 5241            this.select_autoclose_pair(cx);
 5242            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5243            if !this.linked_edit_ranges.is_empty() {
 5244                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5245                let snapshot = this.buffer.read(cx).snapshot(cx);
 5246
 5247                for selection in selections.iter() {
 5248                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5249                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5250                    if selection_start.buffer_id != selection_end.buffer_id {
 5251                        continue;
 5252                    }
 5253                    if let Some(ranges) =
 5254                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5255                    {
 5256                        for (buffer, entries) in ranges {
 5257                            linked_ranges.entry(buffer).or_default().extend(entries);
 5258                        }
 5259                    }
 5260                }
 5261            }
 5262
 5263            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5264            if !this.selections.line_mode {
 5265                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5266                for selection in &mut selections {
 5267                    if selection.is_empty() {
 5268                        let old_head = selection.head();
 5269                        let mut new_head =
 5270                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5271                                .to_point(&display_map);
 5272                        if let Some((buffer, line_buffer_range)) = display_map
 5273                            .buffer_snapshot
 5274                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5275                        {
 5276                            let indent_size =
 5277                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5278                            let indent_len = match indent_size.kind {
 5279                                IndentKind::Space => {
 5280                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5281                                }
 5282                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5283                            };
 5284                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5285                                let indent_len = indent_len.get();
 5286                                new_head = cmp::min(
 5287                                    new_head,
 5288                                    MultiBufferPoint::new(
 5289                                        old_head.row,
 5290                                        ((old_head.column - 1) / indent_len) * indent_len,
 5291                                    ),
 5292                                );
 5293                            }
 5294                        }
 5295
 5296                        selection.set_head(new_head, SelectionGoal::None);
 5297                    }
 5298                }
 5299            }
 5300
 5301            this.signature_help_state.set_backspace_pressed(true);
 5302            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5303            this.insert("", cx);
 5304            let empty_str: Arc<str> = Arc::from("");
 5305            for (buffer, edits) in linked_ranges {
 5306                let snapshot = buffer.read(cx).snapshot();
 5307                use text::ToPoint as TP;
 5308
 5309                let edits = edits
 5310                    .into_iter()
 5311                    .map(|range| {
 5312                        let end_point = TP::to_point(&range.end, &snapshot);
 5313                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5314
 5315                        if end_point == start_point {
 5316                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5317                                .saturating_sub(1);
 5318                            start_point = TP::to_point(&offset, &snapshot);
 5319                        };
 5320
 5321                        (start_point..end_point, empty_str.clone())
 5322                    })
 5323                    .sorted_by_key(|(range, _)| range.start)
 5324                    .collect::<Vec<_>>();
 5325                buffer.update(cx, |this, cx| {
 5326                    this.edit(edits, None, cx);
 5327                })
 5328            }
 5329            this.refresh_inline_completion(true, false, cx);
 5330            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5331        });
 5332    }
 5333
 5334    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5335        self.transact(cx, |this, cx| {
 5336            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5337                let line_mode = s.line_mode;
 5338                s.move_with(|map, selection| {
 5339                    if selection.is_empty() && !line_mode {
 5340                        let cursor = movement::right(map, selection.head());
 5341                        selection.end = cursor;
 5342                        selection.reversed = true;
 5343                        selection.goal = SelectionGoal::None;
 5344                    }
 5345                })
 5346            });
 5347            this.insert("", cx);
 5348            this.refresh_inline_completion(true, false, cx);
 5349        });
 5350    }
 5351
 5352    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5353        if self.move_to_prev_snippet_tabstop(cx) {
 5354            return;
 5355        }
 5356
 5357        self.outdent(&Outdent, cx);
 5358    }
 5359
 5360    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5361        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5362            return;
 5363        }
 5364
 5365        let mut selections = self.selections.all_adjusted(cx);
 5366        let buffer = self.buffer.read(cx);
 5367        let snapshot = buffer.snapshot(cx);
 5368        let rows_iter = selections.iter().map(|s| s.head().row);
 5369        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5370
 5371        let mut edits = Vec::new();
 5372        let mut prev_edited_row = 0;
 5373        let mut row_delta = 0;
 5374        for selection in &mut selections {
 5375            if selection.start.row != prev_edited_row {
 5376                row_delta = 0;
 5377            }
 5378            prev_edited_row = selection.end.row;
 5379
 5380            // If the selection is non-empty, then increase the indentation of the selected lines.
 5381            if !selection.is_empty() {
 5382                row_delta =
 5383                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5384                continue;
 5385            }
 5386
 5387            // If the selection is empty and the cursor is in the leading whitespace before the
 5388            // suggested indentation, then auto-indent the line.
 5389            let cursor = selection.head();
 5390            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5391            if let Some(suggested_indent) =
 5392                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5393            {
 5394                if cursor.column < suggested_indent.len
 5395                    && cursor.column <= current_indent.len
 5396                    && current_indent.len <= suggested_indent.len
 5397                {
 5398                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5399                    selection.end = selection.start;
 5400                    if row_delta == 0 {
 5401                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5402                            cursor.row,
 5403                            current_indent,
 5404                            suggested_indent,
 5405                        ));
 5406                        row_delta = suggested_indent.len - current_indent.len;
 5407                    }
 5408                    continue;
 5409                }
 5410            }
 5411
 5412            // Otherwise, insert a hard or soft tab.
 5413            let settings = buffer.settings_at(cursor, cx);
 5414            let tab_size = if settings.hard_tabs {
 5415                IndentSize::tab()
 5416            } else {
 5417                let tab_size = settings.tab_size.get();
 5418                let char_column = snapshot
 5419                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5420                    .flat_map(str::chars)
 5421                    .count()
 5422                    + row_delta as usize;
 5423                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5424                IndentSize::spaces(chars_to_next_tab_stop)
 5425            };
 5426            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5427            selection.end = selection.start;
 5428            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5429            row_delta += tab_size.len;
 5430        }
 5431
 5432        self.transact(cx, |this, cx| {
 5433            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5434            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5435            this.refresh_inline_completion(true, false, cx);
 5436        });
 5437    }
 5438
 5439    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5440        if self.read_only(cx) {
 5441            return;
 5442        }
 5443        let mut selections = self.selections.all::<Point>(cx);
 5444        let mut prev_edited_row = 0;
 5445        let mut row_delta = 0;
 5446        let mut edits = Vec::new();
 5447        let buffer = self.buffer.read(cx);
 5448        let snapshot = buffer.snapshot(cx);
 5449        for selection in &mut selections {
 5450            if selection.start.row != prev_edited_row {
 5451                row_delta = 0;
 5452            }
 5453            prev_edited_row = selection.end.row;
 5454
 5455            row_delta =
 5456                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5457        }
 5458
 5459        self.transact(cx, |this, cx| {
 5460            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5461            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5462        });
 5463    }
 5464
 5465    fn indent_selection(
 5466        buffer: &MultiBuffer,
 5467        snapshot: &MultiBufferSnapshot,
 5468        selection: &mut Selection<Point>,
 5469        edits: &mut Vec<(Range<Point>, String)>,
 5470        delta_for_start_row: u32,
 5471        cx: &AppContext,
 5472    ) -> u32 {
 5473        let settings = buffer.settings_at(selection.start, cx);
 5474        let tab_size = settings.tab_size.get();
 5475        let indent_kind = if settings.hard_tabs {
 5476            IndentKind::Tab
 5477        } else {
 5478            IndentKind::Space
 5479        };
 5480        let mut start_row = selection.start.row;
 5481        let mut end_row = selection.end.row + 1;
 5482
 5483        // If a selection ends at the beginning of a line, don't indent
 5484        // that last line.
 5485        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5486            end_row -= 1;
 5487        }
 5488
 5489        // Avoid re-indenting a row that has already been indented by a
 5490        // previous selection, but still update this selection's column
 5491        // to reflect that indentation.
 5492        if delta_for_start_row > 0 {
 5493            start_row += 1;
 5494            selection.start.column += delta_for_start_row;
 5495            if selection.end.row == selection.start.row {
 5496                selection.end.column += delta_for_start_row;
 5497            }
 5498        }
 5499
 5500        let mut delta_for_end_row = 0;
 5501        let has_multiple_rows = start_row + 1 != end_row;
 5502        for row in start_row..end_row {
 5503            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5504            let indent_delta = match (current_indent.kind, indent_kind) {
 5505                (IndentKind::Space, IndentKind::Space) => {
 5506                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5507                    IndentSize::spaces(columns_to_next_tab_stop)
 5508                }
 5509                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5510                (_, IndentKind::Tab) => IndentSize::tab(),
 5511            };
 5512
 5513            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5514                0
 5515            } else {
 5516                selection.start.column
 5517            };
 5518            let row_start = Point::new(row, start);
 5519            edits.push((
 5520                row_start..row_start,
 5521                indent_delta.chars().collect::<String>(),
 5522            ));
 5523
 5524            // Update this selection's endpoints to reflect the indentation.
 5525            if row == selection.start.row {
 5526                selection.start.column += indent_delta.len;
 5527            }
 5528            if row == selection.end.row {
 5529                selection.end.column += indent_delta.len;
 5530                delta_for_end_row = indent_delta.len;
 5531            }
 5532        }
 5533
 5534        if selection.start.row == selection.end.row {
 5535            delta_for_start_row + delta_for_end_row
 5536        } else {
 5537            delta_for_end_row
 5538        }
 5539    }
 5540
 5541    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5542        if self.read_only(cx) {
 5543            return;
 5544        }
 5545        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5546        let selections = self.selections.all::<Point>(cx);
 5547        let mut deletion_ranges = Vec::new();
 5548        let mut last_outdent = None;
 5549        {
 5550            let buffer = self.buffer.read(cx);
 5551            let snapshot = buffer.snapshot(cx);
 5552            for selection in &selections {
 5553                let settings = buffer.settings_at(selection.start, cx);
 5554                let tab_size = settings.tab_size.get();
 5555                let mut rows = selection.spanned_rows(false, &display_map);
 5556
 5557                // Avoid re-outdenting a row that has already been outdented by a
 5558                // previous selection.
 5559                if let Some(last_row) = last_outdent {
 5560                    if last_row == rows.start {
 5561                        rows.start = rows.start.next_row();
 5562                    }
 5563                }
 5564                let has_multiple_rows = rows.len() > 1;
 5565                for row in rows.iter_rows() {
 5566                    let indent_size = snapshot.indent_size_for_line(row);
 5567                    if indent_size.len > 0 {
 5568                        let deletion_len = match indent_size.kind {
 5569                            IndentKind::Space => {
 5570                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5571                                if columns_to_prev_tab_stop == 0 {
 5572                                    tab_size
 5573                                } else {
 5574                                    columns_to_prev_tab_stop
 5575                                }
 5576                            }
 5577                            IndentKind::Tab => 1,
 5578                        };
 5579                        let start = if has_multiple_rows
 5580                            || deletion_len > selection.start.column
 5581                            || indent_size.len < selection.start.column
 5582                        {
 5583                            0
 5584                        } else {
 5585                            selection.start.column - deletion_len
 5586                        };
 5587                        deletion_ranges.push(
 5588                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5589                        );
 5590                        last_outdent = Some(row);
 5591                    }
 5592                }
 5593            }
 5594        }
 5595
 5596        self.transact(cx, |this, cx| {
 5597            this.buffer.update(cx, |buffer, cx| {
 5598                let empty_str: Arc<str> = Arc::default();
 5599                buffer.edit(
 5600                    deletion_ranges
 5601                        .into_iter()
 5602                        .map(|range| (range, empty_str.clone())),
 5603                    None,
 5604                    cx,
 5605                );
 5606            });
 5607            let selections = this.selections.all::<usize>(cx);
 5608            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5609        });
 5610    }
 5611
 5612    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5613        if self.read_only(cx) {
 5614            return;
 5615        }
 5616        let selections = self
 5617            .selections
 5618            .all::<usize>(cx)
 5619            .into_iter()
 5620            .map(|s| s.range());
 5621
 5622        self.transact(cx, |this, cx| {
 5623            this.buffer.update(cx, |buffer, cx| {
 5624                buffer.autoindent_ranges(selections, cx);
 5625            });
 5626            let selections = this.selections.all::<usize>(cx);
 5627            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5628        });
 5629    }
 5630
 5631    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5632        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5633        let selections = self.selections.all::<Point>(cx);
 5634
 5635        let mut new_cursors = Vec::new();
 5636        let mut edit_ranges = Vec::new();
 5637        let mut selections = selections.iter().peekable();
 5638        while let Some(selection) = selections.next() {
 5639            let mut rows = selection.spanned_rows(false, &display_map);
 5640            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5641
 5642            // Accumulate contiguous regions of rows that we want to delete.
 5643            while let Some(next_selection) = selections.peek() {
 5644                let next_rows = next_selection.spanned_rows(false, &display_map);
 5645                if next_rows.start <= rows.end {
 5646                    rows.end = next_rows.end;
 5647                    selections.next().unwrap();
 5648                } else {
 5649                    break;
 5650                }
 5651            }
 5652
 5653            let buffer = &display_map.buffer_snapshot;
 5654            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5655            let edit_end;
 5656            let cursor_buffer_row;
 5657            if buffer.max_point().row >= rows.end.0 {
 5658                // If there's a line after the range, delete the \n from the end of the row range
 5659                // and position the cursor on the next line.
 5660                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5661                cursor_buffer_row = rows.end;
 5662            } else {
 5663                // If there isn't a line after the range, delete the \n from the line before the
 5664                // start of the row range and position the cursor there.
 5665                edit_start = edit_start.saturating_sub(1);
 5666                edit_end = buffer.len();
 5667                cursor_buffer_row = rows.start.previous_row();
 5668            }
 5669
 5670            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5671            *cursor.column_mut() =
 5672                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5673
 5674            new_cursors.push((
 5675                selection.id,
 5676                buffer.anchor_after(cursor.to_point(&display_map)),
 5677            ));
 5678            edit_ranges.push(edit_start..edit_end);
 5679        }
 5680
 5681        self.transact(cx, |this, cx| {
 5682            let buffer = this.buffer.update(cx, |buffer, cx| {
 5683                let empty_str: Arc<str> = Arc::default();
 5684                buffer.edit(
 5685                    edit_ranges
 5686                        .into_iter()
 5687                        .map(|range| (range, empty_str.clone())),
 5688                    None,
 5689                    cx,
 5690                );
 5691                buffer.snapshot(cx)
 5692            });
 5693            let new_selections = new_cursors
 5694                .into_iter()
 5695                .map(|(id, cursor)| {
 5696                    let cursor = cursor.to_point(&buffer);
 5697                    Selection {
 5698                        id,
 5699                        start: cursor,
 5700                        end: cursor,
 5701                        reversed: false,
 5702                        goal: SelectionGoal::None,
 5703                    }
 5704                })
 5705                .collect();
 5706
 5707            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5708                s.select(new_selections);
 5709            });
 5710        });
 5711    }
 5712
 5713    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5714        if self.read_only(cx) {
 5715            return;
 5716        }
 5717        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5718        for selection in self.selections.all::<Point>(cx) {
 5719            let start = MultiBufferRow(selection.start.row);
 5720            // Treat single line selections as if they include the next line. Otherwise this action
 5721            // would do nothing for single line selections individual cursors.
 5722            let end = if selection.start.row == selection.end.row {
 5723                MultiBufferRow(selection.start.row + 1)
 5724            } else {
 5725                MultiBufferRow(selection.end.row)
 5726            };
 5727
 5728            if let Some(last_row_range) = row_ranges.last_mut() {
 5729                if start <= last_row_range.end {
 5730                    last_row_range.end = end;
 5731                    continue;
 5732                }
 5733            }
 5734            row_ranges.push(start..end);
 5735        }
 5736
 5737        let snapshot = self.buffer.read(cx).snapshot(cx);
 5738        let mut cursor_positions = Vec::new();
 5739        for row_range in &row_ranges {
 5740            let anchor = snapshot.anchor_before(Point::new(
 5741                row_range.end.previous_row().0,
 5742                snapshot.line_len(row_range.end.previous_row()),
 5743            ));
 5744            cursor_positions.push(anchor..anchor);
 5745        }
 5746
 5747        self.transact(cx, |this, cx| {
 5748            for row_range in row_ranges.into_iter().rev() {
 5749                for row in row_range.iter_rows().rev() {
 5750                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5751                    let next_line_row = row.next_row();
 5752                    let indent = snapshot.indent_size_for_line(next_line_row);
 5753                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5754
 5755                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5756                        " "
 5757                    } else {
 5758                        ""
 5759                    };
 5760
 5761                    this.buffer.update(cx, |buffer, cx| {
 5762                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5763                    });
 5764                }
 5765            }
 5766
 5767            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5768                s.select_anchor_ranges(cursor_positions)
 5769            });
 5770        });
 5771    }
 5772
 5773    pub fn sort_lines_case_sensitive(
 5774        &mut self,
 5775        _: &SortLinesCaseSensitive,
 5776        cx: &mut ViewContext<Self>,
 5777    ) {
 5778        self.manipulate_lines(cx, |lines| lines.sort())
 5779    }
 5780
 5781    pub fn sort_lines_case_insensitive(
 5782        &mut self,
 5783        _: &SortLinesCaseInsensitive,
 5784        cx: &mut ViewContext<Self>,
 5785    ) {
 5786        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5787    }
 5788
 5789    pub fn unique_lines_case_insensitive(
 5790        &mut self,
 5791        _: &UniqueLinesCaseInsensitive,
 5792        cx: &mut ViewContext<Self>,
 5793    ) {
 5794        self.manipulate_lines(cx, |lines| {
 5795            let mut seen = HashSet::default();
 5796            lines.retain(|line| seen.insert(line.to_lowercase()));
 5797        })
 5798    }
 5799
 5800    pub fn unique_lines_case_sensitive(
 5801        &mut self,
 5802        _: &UniqueLinesCaseSensitive,
 5803        cx: &mut ViewContext<Self>,
 5804    ) {
 5805        self.manipulate_lines(cx, |lines| {
 5806            let mut seen = HashSet::default();
 5807            lines.retain(|line| seen.insert(*line));
 5808        })
 5809    }
 5810
 5811    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5812        let mut revert_changes = HashMap::default();
 5813        let snapshot = self.snapshot(cx);
 5814        for hunk in hunks_for_ranges(
 5815            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5816            &snapshot,
 5817        ) {
 5818            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5819        }
 5820        if !revert_changes.is_empty() {
 5821            self.transact(cx, |editor, cx| {
 5822                editor.revert(revert_changes, cx);
 5823            });
 5824        }
 5825    }
 5826
 5827    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5828        let Some(project) = self.project.clone() else {
 5829            return;
 5830        };
 5831        self.reload(project, cx).detach_and_notify_err(cx);
 5832    }
 5833
 5834    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5835        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5836        if !revert_changes.is_empty() {
 5837            self.transact(cx, |editor, cx| {
 5838                editor.revert(revert_changes, cx);
 5839            });
 5840        }
 5841    }
 5842
 5843    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5844        let snapshot = self.buffer.read(cx).read(cx);
 5845        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5846            drop(snapshot);
 5847            let mut revert_changes = HashMap::default();
 5848            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5849            if !revert_changes.is_empty() {
 5850                self.revert(revert_changes, cx)
 5851            }
 5852        }
 5853    }
 5854
 5855    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5856        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5857            let project_path = buffer.read(cx).project_path(cx)?;
 5858            let project = self.project.as_ref()?.read(cx);
 5859            let entry = project.entry_for_path(&project_path, cx)?;
 5860            let parent = match &entry.canonical_path {
 5861                Some(canonical_path) => canonical_path.to_path_buf(),
 5862                None => project.absolute_path(&project_path, cx)?,
 5863            }
 5864            .parent()?
 5865            .to_path_buf();
 5866            Some(parent)
 5867        }) {
 5868            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5869        }
 5870    }
 5871
 5872    fn gather_revert_changes(
 5873        &mut self,
 5874        selections: &[Selection<Point>],
 5875        cx: &mut ViewContext<'_, Editor>,
 5876    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5877        let mut revert_changes = HashMap::default();
 5878        let snapshot = self.snapshot(cx);
 5879        for hunk in hunks_for_selections(&snapshot, selections) {
 5880            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5881        }
 5882        revert_changes
 5883    }
 5884
 5885    pub fn prepare_revert_change(
 5886        &mut self,
 5887        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5888        hunk: &MultiBufferDiffHunk,
 5889        cx: &AppContext,
 5890    ) -> Option<()> {
 5891        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 5892        let buffer = buffer.read(cx);
 5893        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 5894        let original_text = change_set
 5895            .read(cx)
 5896            .base_text
 5897            .as_ref()?
 5898            .read(cx)
 5899            .as_rope()
 5900            .slice(hunk.diff_base_byte_range.clone());
 5901        let buffer_snapshot = buffer.snapshot();
 5902        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5903        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5904            probe
 5905                .0
 5906                .start
 5907                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5908                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5909        }) {
 5910            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5911            Some(())
 5912        } else {
 5913            None
 5914        }
 5915    }
 5916
 5917    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5918        self.manipulate_lines(cx, |lines| lines.reverse())
 5919    }
 5920
 5921    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5922        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5923    }
 5924
 5925    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5926    where
 5927        Fn: FnMut(&mut Vec<&str>),
 5928    {
 5929        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5930        let buffer = self.buffer.read(cx).snapshot(cx);
 5931
 5932        let mut edits = Vec::new();
 5933
 5934        let selections = self.selections.all::<Point>(cx);
 5935        let mut selections = selections.iter().peekable();
 5936        let mut contiguous_row_selections = Vec::new();
 5937        let mut new_selections = Vec::new();
 5938        let mut added_lines = 0;
 5939        let mut removed_lines = 0;
 5940
 5941        while let Some(selection) = selections.next() {
 5942            let (start_row, end_row) = consume_contiguous_rows(
 5943                &mut contiguous_row_selections,
 5944                selection,
 5945                &display_map,
 5946                &mut selections,
 5947            );
 5948
 5949            let start_point = Point::new(start_row.0, 0);
 5950            let end_point = Point::new(
 5951                end_row.previous_row().0,
 5952                buffer.line_len(end_row.previous_row()),
 5953            );
 5954            let text = buffer
 5955                .text_for_range(start_point..end_point)
 5956                .collect::<String>();
 5957
 5958            let mut lines = text.split('\n').collect_vec();
 5959
 5960            let lines_before = lines.len();
 5961            callback(&mut lines);
 5962            let lines_after = lines.len();
 5963
 5964            edits.push((start_point..end_point, lines.join("\n")));
 5965
 5966            // Selections must change based on added and removed line count
 5967            let start_row =
 5968                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5969            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5970            new_selections.push(Selection {
 5971                id: selection.id,
 5972                start: start_row,
 5973                end: end_row,
 5974                goal: SelectionGoal::None,
 5975                reversed: selection.reversed,
 5976            });
 5977
 5978            if lines_after > lines_before {
 5979                added_lines += lines_after - lines_before;
 5980            } else if lines_before > lines_after {
 5981                removed_lines += lines_before - lines_after;
 5982            }
 5983        }
 5984
 5985        self.transact(cx, |this, cx| {
 5986            let buffer = this.buffer.update(cx, |buffer, cx| {
 5987                buffer.edit(edits, None, cx);
 5988                buffer.snapshot(cx)
 5989            });
 5990
 5991            // Recalculate offsets on newly edited buffer
 5992            let new_selections = new_selections
 5993                .iter()
 5994                .map(|s| {
 5995                    let start_point = Point::new(s.start.0, 0);
 5996                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 5997                    Selection {
 5998                        id: s.id,
 5999                        start: buffer.point_to_offset(start_point),
 6000                        end: buffer.point_to_offset(end_point),
 6001                        goal: s.goal,
 6002                        reversed: s.reversed,
 6003                    }
 6004                })
 6005                .collect();
 6006
 6007            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6008                s.select(new_selections);
 6009            });
 6010
 6011            this.request_autoscroll(Autoscroll::fit(), cx);
 6012        });
 6013    }
 6014
 6015    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6016        self.manipulate_text(cx, |text| text.to_uppercase())
 6017    }
 6018
 6019    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6020        self.manipulate_text(cx, |text| text.to_lowercase())
 6021    }
 6022
 6023    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6024        self.manipulate_text(cx, |text| {
 6025            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6026            // https://github.com/rutrum/convert-case/issues/16
 6027            text.split('\n')
 6028                .map(|line| line.to_case(Case::Title))
 6029                .join("\n")
 6030        })
 6031    }
 6032
 6033    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6034        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6035    }
 6036
 6037    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6038        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6039    }
 6040
 6041    pub fn convert_to_upper_camel_case(
 6042        &mut self,
 6043        _: &ConvertToUpperCamelCase,
 6044        cx: &mut ViewContext<Self>,
 6045    ) {
 6046        self.manipulate_text(cx, |text| {
 6047            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6048            // https://github.com/rutrum/convert-case/issues/16
 6049            text.split('\n')
 6050                .map(|line| line.to_case(Case::UpperCamel))
 6051                .join("\n")
 6052        })
 6053    }
 6054
 6055    pub fn convert_to_lower_camel_case(
 6056        &mut self,
 6057        _: &ConvertToLowerCamelCase,
 6058        cx: &mut ViewContext<Self>,
 6059    ) {
 6060        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6061    }
 6062
 6063    pub fn convert_to_opposite_case(
 6064        &mut self,
 6065        _: &ConvertToOppositeCase,
 6066        cx: &mut ViewContext<Self>,
 6067    ) {
 6068        self.manipulate_text(cx, |text| {
 6069            text.chars()
 6070                .fold(String::with_capacity(text.len()), |mut t, c| {
 6071                    if c.is_uppercase() {
 6072                        t.extend(c.to_lowercase());
 6073                    } else {
 6074                        t.extend(c.to_uppercase());
 6075                    }
 6076                    t
 6077                })
 6078        })
 6079    }
 6080
 6081    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6082    where
 6083        Fn: FnMut(&str) -> String,
 6084    {
 6085        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6086        let buffer = self.buffer.read(cx).snapshot(cx);
 6087
 6088        let mut new_selections = Vec::new();
 6089        let mut edits = Vec::new();
 6090        let mut selection_adjustment = 0i32;
 6091
 6092        for selection in self.selections.all::<usize>(cx) {
 6093            let selection_is_empty = selection.is_empty();
 6094
 6095            let (start, end) = if selection_is_empty {
 6096                let word_range = movement::surrounding_word(
 6097                    &display_map,
 6098                    selection.start.to_display_point(&display_map),
 6099                );
 6100                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6101                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6102                (start, end)
 6103            } else {
 6104                (selection.start, selection.end)
 6105            };
 6106
 6107            let text = buffer.text_for_range(start..end).collect::<String>();
 6108            let old_length = text.len() as i32;
 6109            let text = callback(&text);
 6110
 6111            new_selections.push(Selection {
 6112                start: (start as i32 - selection_adjustment) as usize,
 6113                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6114                goal: SelectionGoal::None,
 6115                ..selection
 6116            });
 6117
 6118            selection_adjustment += old_length - text.len() as i32;
 6119
 6120            edits.push((start..end, text));
 6121        }
 6122
 6123        self.transact(cx, |this, cx| {
 6124            this.buffer.update(cx, |buffer, cx| {
 6125                buffer.edit(edits, None, cx);
 6126            });
 6127
 6128            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6129                s.select(new_selections);
 6130            });
 6131
 6132            this.request_autoscroll(Autoscroll::fit(), cx);
 6133        });
 6134    }
 6135
 6136    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6137        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6138        let buffer = &display_map.buffer_snapshot;
 6139        let selections = self.selections.all::<Point>(cx);
 6140
 6141        let mut edits = Vec::new();
 6142        let mut selections_iter = selections.iter().peekable();
 6143        while let Some(selection) = selections_iter.next() {
 6144            let mut rows = selection.spanned_rows(false, &display_map);
 6145            // duplicate line-wise
 6146            if whole_lines || selection.start == selection.end {
 6147                // Avoid duplicating the same lines twice.
 6148                while let Some(next_selection) = selections_iter.peek() {
 6149                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6150                    if next_rows.start < rows.end {
 6151                        rows.end = next_rows.end;
 6152                        selections_iter.next().unwrap();
 6153                    } else {
 6154                        break;
 6155                    }
 6156                }
 6157
 6158                // Copy the text from the selected row region and splice it either at the start
 6159                // or end of the region.
 6160                let start = Point::new(rows.start.0, 0);
 6161                let end = Point::new(
 6162                    rows.end.previous_row().0,
 6163                    buffer.line_len(rows.end.previous_row()),
 6164                );
 6165                let text = buffer
 6166                    .text_for_range(start..end)
 6167                    .chain(Some("\n"))
 6168                    .collect::<String>();
 6169                let insert_location = if upwards {
 6170                    Point::new(rows.end.0, 0)
 6171                } else {
 6172                    start
 6173                };
 6174                edits.push((insert_location..insert_location, text));
 6175            } else {
 6176                // duplicate character-wise
 6177                let start = selection.start;
 6178                let end = selection.end;
 6179                let text = buffer.text_for_range(start..end).collect::<String>();
 6180                edits.push((selection.end..selection.end, text));
 6181            }
 6182        }
 6183
 6184        self.transact(cx, |this, cx| {
 6185            this.buffer.update(cx, |buffer, cx| {
 6186                buffer.edit(edits, None, cx);
 6187            });
 6188
 6189            this.request_autoscroll(Autoscroll::fit(), cx);
 6190        });
 6191    }
 6192
 6193    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6194        self.duplicate(true, true, cx);
 6195    }
 6196
 6197    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6198        self.duplicate(false, true, cx);
 6199    }
 6200
 6201    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6202        self.duplicate(false, false, cx);
 6203    }
 6204
 6205    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6206        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6207        let buffer = self.buffer.read(cx).snapshot(cx);
 6208
 6209        let mut edits = Vec::new();
 6210        let mut unfold_ranges = Vec::new();
 6211        let mut refold_creases = Vec::new();
 6212
 6213        let selections = self.selections.all::<Point>(cx);
 6214        let mut selections = selections.iter().peekable();
 6215        let mut contiguous_row_selections = Vec::new();
 6216        let mut new_selections = Vec::new();
 6217
 6218        while let Some(selection) = selections.next() {
 6219            // Find all the selections that span a contiguous row range
 6220            let (start_row, end_row) = consume_contiguous_rows(
 6221                &mut contiguous_row_selections,
 6222                selection,
 6223                &display_map,
 6224                &mut selections,
 6225            );
 6226
 6227            // Move the text spanned by the row range to be before the line preceding the row range
 6228            if start_row.0 > 0 {
 6229                let range_to_move = Point::new(
 6230                    start_row.previous_row().0,
 6231                    buffer.line_len(start_row.previous_row()),
 6232                )
 6233                    ..Point::new(
 6234                        end_row.previous_row().0,
 6235                        buffer.line_len(end_row.previous_row()),
 6236                    );
 6237                let insertion_point = display_map
 6238                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6239                    .0;
 6240
 6241                // Don't move lines across excerpts
 6242                if buffer
 6243                    .excerpt_boundaries_in_range((
 6244                        Bound::Excluded(insertion_point),
 6245                        Bound::Included(range_to_move.end),
 6246                    ))
 6247                    .next()
 6248                    .is_none()
 6249                {
 6250                    let text = buffer
 6251                        .text_for_range(range_to_move.clone())
 6252                        .flat_map(|s| s.chars())
 6253                        .skip(1)
 6254                        .chain(['\n'])
 6255                        .collect::<String>();
 6256
 6257                    edits.push((
 6258                        buffer.anchor_after(range_to_move.start)
 6259                            ..buffer.anchor_before(range_to_move.end),
 6260                        String::new(),
 6261                    ));
 6262                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6263                    edits.push((insertion_anchor..insertion_anchor, text));
 6264
 6265                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6266
 6267                    // Move selections up
 6268                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6269                        |mut selection| {
 6270                            selection.start.row -= row_delta;
 6271                            selection.end.row -= row_delta;
 6272                            selection
 6273                        },
 6274                    ));
 6275
 6276                    // Move folds up
 6277                    unfold_ranges.push(range_to_move.clone());
 6278                    for fold in display_map.folds_in_range(
 6279                        buffer.anchor_before(range_to_move.start)
 6280                            ..buffer.anchor_after(range_to_move.end),
 6281                    ) {
 6282                        let mut start = fold.range.start.to_point(&buffer);
 6283                        let mut end = fold.range.end.to_point(&buffer);
 6284                        start.row -= row_delta;
 6285                        end.row -= row_delta;
 6286                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6287                    }
 6288                }
 6289            }
 6290
 6291            // If we didn't move line(s), preserve the existing selections
 6292            new_selections.append(&mut contiguous_row_selections);
 6293        }
 6294
 6295        self.transact(cx, |this, cx| {
 6296            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6297            this.buffer.update(cx, |buffer, cx| {
 6298                for (range, text) in edits {
 6299                    buffer.edit([(range, text)], None, cx);
 6300                }
 6301            });
 6302            this.fold_creases(refold_creases, true, cx);
 6303            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6304                s.select(new_selections);
 6305            })
 6306        });
 6307    }
 6308
 6309    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6310        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6311        let buffer = self.buffer.read(cx).snapshot(cx);
 6312
 6313        let mut edits = Vec::new();
 6314        let mut unfold_ranges = Vec::new();
 6315        let mut refold_creases = Vec::new();
 6316
 6317        let selections = self.selections.all::<Point>(cx);
 6318        let mut selections = selections.iter().peekable();
 6319        let mut contiguous_row_selections = Vec::new();
 6320        let mut new_selections = Vec::new();
 6321
 6322        while let Some(selection) = selections.next() {
 6323            // Find all the selections that span a contiguous row range
 6324            let (start_row, end_row) = consume_contiguous_rows(
 6325                &mut contiguous_row_selections,
 6326                selection,
 6327                &display_map,
 6328                &mut selections,
 6329            );
 6330
 6331            // Move the text spanned by the row range to be after the last line of the row range
 6332            if end_row.0 <= buffer.max_point().row {
 6333                let range_to_move =
 6334                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6335                let insertion_point = display_map
 6336                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6337                    .0;
 6338
 6339                // Don't move lines across excerpt boundaries
 6340                if buffer
 6341                    .excerpt_boundaries_in_range((
 6342                        Bound::Excluded(range_to_move.start),
 6343                        Bound::Included(insertion_point),
 6344                    ))
 6345                    .next()
 6346                    .is_none()
 6347                {
 6348                    let mut text = String::from("\n");
 6349                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6350                    text.pop(); // Drop trailing newline
 6351                    edits.push((
 6352                        buffer.anchor_after(range_to_move.start)
 6353                            ..buffer.anchor_before(range_to_move.end),
 6354                        String::new(),
 6355                    ));
 6356                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6357                    edits.push((insertion_anchor..insertion_anchor, text));
 6358
 6359                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6360
 6361                    // Move selections down
 6362                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6363                        |mut selection| {
 6364                            selection.start.row += row_delta;
 6365                            selection.end.row += row_delta;
 6366                            selection
 6367                        },
 6368                    ));
 6369
 6370                    // Move folds down
 6371                    unfold_ranges.push(range_to_move.clone());
 6372                    for fold in display_map.folds_in_range(
 6373                        buffer.anchor_before(range_to_move.start)
 6374                            ..buffer.anchor_after(range_to_move.end),
 6375                    ) {
 6376                        let mut start = fold.range.start.to_point(&buffer);
 6377                        let mut end = fold.range.end.to_point(&buffer);
 6378                        start.row += row_delta;
 6379                        end.row += row_delta;
 6380                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6381                    }
 6382                }
 6383            }
 6384
 6385            // If we didn't move line(s), preserve the existing selections
 6386            new_selections.append(&mut contiguous_row_selections);
 6387        }
 6388
 6389        self.transact(cx, |this, cx| {
 6390            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6391            this.buffer.update(cx, |buffer, cx| {
 6392                for (range, text) in edits {
 6393                    buffer.edit([(range, text)], None, cx);
 6394                }
 6395            });
 6396            this.fold_creases(refold_creases, true, cx);
 6397            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6398        });
 6399    }
 6400
 6401    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6402        let text_layout_details = &self.text_layout_details(cx);
 6403        self.transact(cx, |this, cx| {
 6404            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6405                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6406                let line_mode = s.line_mode;
 6407                s.move_with(|display_map, selection| {
 6408                    if !selection.is_empty() || line_mode {
 6409                        return;
 6410                    }
 6411
 6412                    let mut head = selection.head();
 6413                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6414                    if head.column() == display_map.line_len(head.row()) {
 6415                        transpose_offset = display_map
 6416                            .buffer_snapshot
 6417                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6418                    }
 6419
 6420                    if transpose_offset == 0 {
 6421                        return;
 6422                    }
 6423
 6424                    *head.column_mut() += 1;
 6425                    head = display_map.clip_point(head, Bias::Right);
 6426                    let goal = SelectionGoal::HorizontalPosition(
 6427                        display_map
 6428                            .x_for_display_point(head, text_layout_details)
 6429                            .into(),
 6430                    );
 6431                    selection.collapse_to(head, goal);
 6432
 6433                    let transpose_start = display_map
 6434                        .buffer_snapshot
 6435                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6436                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6437                        let transpose_end = display_map
 6438                            .buffer_snapshot
 6439                            .clip_offset(transpose_offset + 1, Bias::Right);
 6440                        if let Some(ch) =
 6441                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6442                        {
 6443                            edits.push((transpose_start..transpose_offset, String::new()));
 6444                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6445                        }
 6446                    }
 6447                });
 6448                edits
 6449            });
 6450            this.buffer
 6451                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6452            let selections = this.selections.all::<usize>(cx);
 6453            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6454                s.select(selections);
 6455            });
 6456        });
 6457    }
 6458
 6459    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6460        self.rewrap_impl(IsVimMode::No, cx)
 6461    }
 6462
 6463    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6464        let buffer = self.buffer.read(cx).snapshot(cx);
 6465        let selections = self.selections.all::<Point>(cx);
 6466        let mut selections = selections.iter().peekable();
 6467
 6468        let mut edits = Vec::new();
 6469        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6470
 6471        while let Some(selection) = selections.next() {
 6472            let mut start_row = selection.start.row;
 6473            let mut end_row = selection.end.row;
 6474
 6475            // Skip selections that overlap with a range that has already been rewrapped.
 6476            let selection_range = start_row..end_row;
 6477            if rewrapped_row_ranges
 6478                .iter()
 6479                .any(|range| range.overlaps(&selection_range))
 6480            {
 6481                continue;
 6482            }
 6483
 6484            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6485
 6486            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6487                match language_scope.language_name().0.as_ref() {
 6488                    "Markdown" | "Plain Text" => {
 6489                        should_rewrap = true;
 6490                    }
 6491                    _ => {}
 6492                }
 6493            }
 6494
 6495            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6496
 6497            // Since not all lines in the selection may be at the same indent
 6498            // level, choose the indent size that is the most common between all
 6499            // of the lines.
 6500            //
 6501            // If there is a tie, we use the deepest indent.
 6502            let (indent_size, indent_end) = {
 6503                let mut indent_size_occurrences = HashMap::default();
 6504                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6505
 6506                for row in start_row..=end_row {
 6507                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6508                    rows_by_indent_size.entry(indent).or_default().push(row);
 6509                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6510                }
 6511
 6512                let indent_size = indent_size_occurrences
 6513                    .into_iter()
 6514                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6515                    .map(|(indent, _)| indent)
 6516                    .unwrap_or_default();
 6517                let row = rows_by_indent_size[&indent_size][0];
 6518                let indent_end = Point::new(row, indent_size.len);
 6519
 6520                (indent_size, indent_end)
 6521            };
 6522
 6523            let mut line_prefix = indent_size.chars().collect::<String>();
 6524
 6525            if let Some(comment_prefix) =
 6526                buffer
 6527                    .language_scope_at(selection.head())
 6528                    .and_then(|language| {
 6529                        language
 6530                            .line_comment_prefixes()
 6531                            .iter()
 6532                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6533                            .cloned()
 6534                    })
 6535            {
 6536                line_prefix.push_str(&comment_prefix);
 6537                should_rewrap = true;
 6538            }
 6539
 6540            if !should_rewrap {
 6541                continue;
 6542            }
 6543
 6544            if selection.is_empty() {
 6545                'expand_upwards: while start_row > 0 {
 6546                    let prev_row = start_row - 1;
 6547                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6548                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6549                    {
 6550                        start_row = prev_row;
 6551                    } else {
 6552                        break 'expand_upwards;
 6553                    }
 6554                }
 6555
 6556                'expand_downwards: while end_row < buffer.max_point().row {
 6557                    let next_row = end_row + 1;
 6558                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6559                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6560                    {
 6561                        end_row = next_row;
 6562                    } else {
 6563                        break 'expand_downwards;
 6564                    }
 6565                }
 6566            }
 6567
 6568            let start = Point::new(start_row, 0);
 6569            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6570            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6571            let Some(lines_without_prefixes) = selection_text
 6572                .lines()
 6573                .map(|line| {
 6574                    line.strip_prefix(&line_prefix)
 6575                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6576                        .ok_or_else(|| {
 6577                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6578                        })
 6579                })
 6580                .collect::<Result<Vec<_>, _>>()
 6581                .log_err()
 6582            else {
 6583                continue;
 6584            };
 6585
 6586            let wrap_column = buffer
 6587                .settings_at(Point::new(start_row, 0), cx)
 6588                .preferred_line_length as usize;
 6589            let wrapped_text = wrap_with_prefix(
 6590                line_prefix,
 6591                lines_without_prefixes.join(" "),
 6592                wrap_column,
 6593                tab_size,
 6594            );
 6595
 6596            // TODO: should always use char-based diff while still supporting cursor behavior that
 6597            // matches vim.
 6598            let diff = match is_vim_mode {
 6599                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6600                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6601            };
 6602            let mut offset = start.to_offset(&buffer);
 6603            let mut moved_since_edit = true;
 6604
 6605            for change in diff.iter_all_changes() {
 6606                let value = change.value();
 6607                match change.tag() {
 6608                    ChangeTag::Equal => {
 6609                        offset += value.len();
 6610                        moved_since_edit = true;
 6611                    }
 6612                    ChangeTag::Delete => {
 6613                        let start = buffer.anchor_after(offset);
 6614                        let end = buffer.anchor_before(offset + value.len());
 6615
 6616                        if moved_since_edit {
 6617                            edits.push((start..end, String::new()));
 6618                        } else {
 6619                            edits.last_mut().unwrap().0.end = end;
 6620                        }
 6621
 6622                        offset += value.len();
 6623                        moved_since_edit = false;
 6624                    }
 6625                    ChangeTag::Insert => {
 6626                        if moved_since_edit {
 6627                            let anchor = buffer.anchor_after(offset);
 6628                            edits.push((anchor..anchor, value.to_string()));
 6629                        } else {
 6630                            edits.last_mut().unwrap().1.push_str(value);
 6631                        }
 6632
 6633                        moved_since_edit = false;
 6634                    }
 6635                }
 6636            }
 6637
 6638            rewrapped_row_ranges.push(start_row..=end_row);
 6639        }
 6640
 6641        self.buffer
 6642            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6643    }
 6644
 6645    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6646        let mut text = String::new();
 6647        let buffer = self.buffer.read(cx).snapshot(cx);
 6648        let mut selections = self.selections.all::<Point>(cx);
 6649        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6650        {
 6651            let max_point = buffer.max_point();
 6652            let mut is_first = true;
 6653            for selection in &mut selections {
 6654                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6655                if is_entire_line {
 6656                    selection.start = Point::new(selection.start.row, 0);
 6657                    if !selection.is_empty() && selection.end.column == 0 {
 6658                        selection.end = cmp::min(max_point, selection.end);
 6659                    } else {
 6660                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6661                    }
 6662                    selection.goal = SelectionGoal::None;
 6663                }
 6664                if is_first {
 6665                    is_first = false;
 6666                } else {
 6667                    text += "\n";
 6668                }
 6669                let mut len = 0;
 6670                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6671                    text.push_str(chunk);
 6672                    len += chunk.len();
 6673                }
 6674                clipboard_selections.push(ClipboardSelection {
 6675                    len,
 6676                    is_entire_line,
 6677                    first_line_indent: buffer
 6678                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6679                        .len,
 6680                });
 6681            }
 6682        }
 6683
 6684        self.transact(cx, |this, cx| {
 6685            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6686                s.select(selections);
 6687            });
 6688            this.insert("", cx);
 6689        });
 6690        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6691    }
 6692
 6693    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6694        let item = self.cut_common(cx);
 6695        cx.write_to_clipboard(item);
 6696    }
 6697
 6698    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6699        self.change_selections(None, cx, |s| {
 6700            s.move_with(|snapshot, sel| {
 6701                if sel.is_empty() {
 6702                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6703                }
 6704            });
 6705        });
 6706        let item = self.cut_common(cx);
 6707        cx.set_global(KillRing(item))
 6708    }
 6709
 6710    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6711        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6712            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6713                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6714            } else {
 6715                return;
 6716            }
 6717        } else {
 6718            return;
 6719        };
 6720        self.do_paste(&text, metadata, false, cx);
 6721    }
 6722
 6723    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6724        let selections = self.selections.all::<Point>(cx);
 6725        let buffer = self.buffer.read(cx).read(cx);
 6726        let mut text = String::new();
 6727
 6728        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6729        {
 6730            let max_point = buffer.max_point();
 6731            let mut is_first = true;
 6732            for selection in selections.iter() {
 6733                let mut start = selection.start;
 6734                let mut end = selection.end;
 6735                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6736                if is_entire_line {
 6737                    start = Point::new(start.row, 0);
 6738                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6739                }
 6740                if is_first {
 6741                    is_first = false;
 6742                } else {
 6743                    text += "\n";
 6744                }
 6745                let mut len = 0;
 6746                for chunk in buffer.text_for_range(start..end) {
 6747                    text.push_str(chunk);
 6748                    len += chunk.len();
 6749                }
 6750                clipboard_selections.push(ClipboardSelection {
 6751                    len,
 6752                    is_entire_line,
 6753                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6754                });
 6755            }
 6756        }
 6757
 6758        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6759            text,
 6760            clipboard_selections,
 6761        ));
 6762    }
 6763
 6764    pub fn do_paste(
 6765        &mut self,
 6766        text: &String,
 6767        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6768        handle_entire_lines: bool,
 6769        cx: &mut ViewContext<Self>,
 6770    ) {
 6771        if self.read_only(cx) {
 6772            return;
 6773        }
 6774
 6775        let clipboard_text = Cow::Borrowed(text);
 6776
 6777        self.transact(cx, |this, cx| {
 6778            if let Some(mut clipboard_selections) = clipboard_selections {
 6779                let old_selections = this.selections.all::<usize>(cx);
 6780                let all_selections_were_entire_line =
 6781                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6782                let first_selection_indent_column =
 6783                    clipboard_selections.first().map(|s| s.first_line_indent);
 6784                if clipboard_selections.len() != old_selections.len() {
 6785                    clipboard_selections.drain(..);
 6786                }
 6787                let cursor_offset = this.selections.last::<usize>(cx).head();
 6788                let mut auto_indent_on_paste = true;
 6789
 6790                this.buffer.update(cx, |buffer, cx| {
 6791                    let snapshot = buffer.read(cx);
 6792                    auto_indent_on_paste =
 6793                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6794
 6795                    let mut start_offset = 0;
 6796                    let mut edits = Vec::new();
 6797                    let mut original_indent_columns = Vec::new();
 6798                    for (ix, selection) in old_selections.iter().enumerate() {
 6799                        let to_insert;
 6800                        let entire_line;
 6801                        let original_indent_column;
 6802                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6803                            let end_offset = start_offset + clipboard_selection.len;
 6804                            to_insert = &clipboard_text[start_offset..end_offset];
 6805                            entire_line = clipboard_selection.is_entire_line;
 6806                            start_offset = end_offset + 1;
 6807                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6808                        } else {
 6809                            to_insert = clipboard_text.as_str();
 6810                            entire_line = all_selections_were_entire_line;
 6811                            original_indent_column = first_selection_indent_column
 6812                        }
 6813
 6814                        // If the corresponding selection was empty when this slice of the
 6815                        // clipboard text was written, then the entire line containing the
 6816                        // selection was copied. If this selection is also currently empty,
 6817                        // then paste the line before the current line of the buffer.
 6818                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6819                            let column = selection.start.to_point(&snapshot).column as usize;
 6820                            let line_start = selection.start - column;
 6821                            line_start..line_start
 6822                        } else {
 6823                            selection.range()
 6824                        };
 6825
 6826                        edits.push((range, to_insert));
 6827                        original_indent_columns.extend(original_indent_column);
 6828                    }
 6829                    drop(snapshot);
 6830
 6831                    buffer.edit(
 6832                        edits,
 6833                        if auto_indent_on_paste {
 6834                            Some(AutoindentMode::Block {
 6835                                original_indent_columns,
 6836                            })
 6837                        } else {
 6838                            None
 6839                        },
 6840                        cx,
 6841                    );
 6842                });
 6843
 6844                let selections = this.selections.all::<usize>(cx);
 6845                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6846            } else {
 6847                this.insert(&clipboard_text, cx);
 6848            }
 6849        });
 6850    }
 6851
 6852    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6853        if let Some(item) = cx.read_from_clipboard() {
 6854            let entries = item.entries();
 6855
 6856            match entries.first() {
 6857                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6858                // of all the pasted entries.
 6859                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6860                    .do_paste(
 6861                        clipboard_string.text(),
 6862                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 6863                        true,
 6864                        cx,
 6865                    ),
 6866                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 6867            }
 6868        }
 6869    }
 6870
 6871    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6872        if self.read_only(cx) {
 6873            return;
 6874        }
 6875
 6876        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6877            if let Some((selections, _)) =
 6878                self.selection_history.transaction(transaction_id).cloned()
 6879            {
 6880                self.change_selections(None, cx, |s| {
 6881                    s.select_anchors(selections.to_vec());
 6882                });
 6883            }
 6884            self.request_autoscroll(Autoscroll::fit(), cx);
 6885            self.unmark_text(cx);
 6886            self.refresh_inline_completion(true, false, cx);
 6887            cx.emit(EditorEvent::Edited { transaction_id });
 6888            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6889        }
 6890    }
 6891
 6892    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6893        if self.read_only(cx) {
 6894            return;
 6895        }
 6896
 6897        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6898            if let Some((_, Some(selections))) =
 6899                self.selection_history.transaction(transaction_id).cloned()
 6900            {
 6901                self.change_selections(None, cx, |s| {
 6902                    s.select_anchors(selections.to_vec());
 6903                });
 6904            }
 6905            self.request_autoscroll(Autoscroll::fit(), cx);
 6906            self.unmark_text(cx);
 6907            self.refresh_inline_completion(true, false, cx);
 6908            cx.emit(EditorEvent::Edited { transaction_id });
 6909        }
 6910    }
 6911
 6912    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6913        self.buffer
 6914            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6915    }
 6916
 6917    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6918        self.buffer
 6919            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6920    }
 6921
 6922    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6923        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6924            let line_mode = s.line_mode;
 6925            s.move_with(|map, selection| {
 6926                let cursor = if selection.is_empty() && !line_mode {
 6927                    movement::left(map, selection.start)
 6928                } else {
 6929                    selection.start
 6930                };
 6931                selection.collapse_to(cursor, SelectionGoal::None);
 6932            });
 6933        })
 6934    }
 6935
 6936    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6937        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6938            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6939        })
 6940    }
 6941
 6942    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6943        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6944            let line_mode = s.line_mode;
 6945            s.move_with(|map, selection| {
 6946                let cursor = if selection.is_empty() && !line_mode {
 6947                    movement::right(map, selection.end)
 6948                } else {
 6949                    selection.end
 6950                };
 6951                selection.collapse_to(cursor, SelectionGoal::None)
 6952            });
 6953        })
 6954    }
 6955
 6956    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6957        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6958            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6959        })
 6960    }
 6961
 6962    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6963        if self.take_rename(true, cx).is_some() {
 6964            return;
 6965        }
 6966
 6967        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6968            cx.propagate();
 6969            return;
 6970        }
 6971
 6972        let text_layout_details = &self.text_layout_details(cx);
 6973        let selection_count = self.selections.count();
 6974        let first_selection = self.selections.first_anchor();
 6975
 6976        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6977            let line_mode = s.line_mode;
 6978            s.move_with(|map, selection| {
 6979                if !selection.is_empty() && !line_mode {
 6980                    selection.goal = SelectionGoal::None;
 6981                }
 6982                let (cursor, goal) = movement::up(
 6983                    map,
 6984                    selection.start,
 6985                    selection.goal,
 6986                    false,
 6987                    text_layout_details,
 6988                );
 6989                selection.collapse_to(cursor, goal);
 6990            });
 6991        });
 6992
 6993        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6994        {
 6995            cx.propagate();
 6996        }
 6997    }
 6998
 6999    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7000        if self.take_rename(true, cx).is_some() {
 7001            return;
 7002        }
 7003
 7004        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7005            cx.propagate();
 7006            return;
 7007        }
 7008
 7009        let text_layout_details = &self.text_layout_details(cx);
 7010
 7011        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7012            let line_mode = s.line_mode;
 7013            s.move_with(|map, selection| {
 7014                if !selection.is_empty() && !line_mode {
 7015                    selection.goal = SelectionGoal::None;
 7016                }
 7017                let (cursor, goal) = movement::up_by_rows(
 7018                    map,
 7019                    selection.start,
 7020                    action.lines,
 7021                    selection.goal,
 7022                    false,
 7023                    text_layout_details,
 7024                );
 7025                selection.collapse_to(cursor, goal);
 7026            });
 7027        })
 7028    }
 7029
 7030    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7031        if self.take_rename(true, cx).is_some() {
 7032            return;
 7033        }
 7034
 7035        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7036            cx.propagate();
 7037            return;
 7038        }
 7039
 7040        let text_layout_details = &self.text_layout_details(cx);
 7041
 7042        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7043            let line_mode = s.line_mode;
 7044            s.move_with(|map, selection| {
 7045                if !selection.is_empty() && !line_mode {
 7046                    selection.goal = SelectionGoal::None;
 7047                }
 7048                let (cursor, goal) = movement::down_by_rows(
 7049                    map,
 7050                    selection.start,
 7051                    action.lines,
 7052                    selection.goal,
 7053                    false,
 7054                    text_layout_details,
 7055                );
 7056                selection.collapse_to(cursor, goal);
 7057            });
 7058        })
 7059    }
 7060
 7061    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7062        let text_layout_details = &self.text_layout_details(cx);
 7063        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7064            s.move_heads_with(|map, head, goal| {
 7065                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7066            })
 7067        })
 7068    }
 7069
 7070    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7071        let text_layout_details = &self.text_layout_details(cx);
 7072        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7073            s.move_heads_with(|map, head, goal| {
 7074                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7075            })
 7076        })
 7077    }
 7078
 7079    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7080        let Some(row_count) = self.visible_row_count() else {
 7081            return;
 7082        };
 7083
 7084        let text_layout_details = &self.text_layout_details(cx);
 7085
 7086        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7087            s.move_heads_with(|map, head, goal| {
 7088                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7089            })
 7090        })
 7091    }
 7092
 7093    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7094        if self.take_rename(true, cx).is_some() {
 7095            return;
 7096        }
 7097
 7098        if self
 7099            .context_menu
 7100            .borrow_mut()
 7101            .as_mut()
 7102            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7103            .unwrap_or(false)
 7104        {
 7105            return;
 7106        }
 7107
 7108        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7109            cx.propagate();
 7110            return;
 7111        }
 7112
 7113        let Some(row_count) = self.visible_row_count() else {
 7114            return;
 7115        };
 7116
 7117        let autoscroll = if action.center_cursor {
 7118            Autoscroll::center()
 7119        } else {
 7120            Autoscroll::fit()
 7121        };
 7122
 7123        let text_layout_details = &self.text_layout_details(cx);
 7124
 7125        self.change_selections(Some(autoscroll), cx, |s| {
 7126            let line_mode = s.line_mode;
 7127            s.move_with(|map, selection| {
 7128                if !selection.is_empty() && !line_mode {
 7129                    selection.goal = SelectionGoal::None;
 7130                }
 7131                let (cursor, goal) = movement::up_by_rows(
 7132                    map,
 7133                    selection.end,
 7134                    row_count,
 7135                    selection.goal,
 7136                    false,
 7137                    text_layout_details,
 7138                );
 7139                selection.collapse_to(cursor, goal);
 7140            });
 7141        });
 7142    }
 7143
 7144    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7145        let text_layout_details = &self.text_layout_details(cx);
 7146        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7147            s.move_heads_with(|map, head, goal| {
 7148                movement::up(map, head, goal, false, text_layout_details)
 7149            })
 7150        })
 7151    }
 7152
 7153    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7154        self.take_rename(true, cx);
 7155
 7156        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7157            cx.propagate();
 7158            return;
 7159        }
 7160
 7161        let text_layout_details = &self.text_layout_details(cx);
 7162        let selection_count = self.selections.count();
 7163        let first_selection = self.selections.first_anchor();
 7164
 7165        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7166            let line_mode = s.line_mode;
 7167            s.move_with(|map, selection| {
 7168                if !selection.is_empty() && !line_mode {
 7169                    selection.goal = SelectionGoal::None;
 7170                }
 7171                let (cursor, goal) = movement::down(
 7172                    map,
 7173                    selection.end,
 7174                    selection.goal,
 7175                    false,
 7176                    text_layout_details,
 7177                );
 7178                selection.collapse_to(cursor, goal);
 7179            });
 7180        });
 7181
 7182        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7183        {
 7184            cx.propagate();
 7185        }
 7186    }
 7187
 7188    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7189        let Some(row_count) = self.visible_row_count() else {
 7190            return;
 7191        };
 7192
 7193        let text_layout_details = &self.text_layout_details(cx);
 7194
 7195        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7196            s.move_heads_with(|map, head, goal| {
 7197                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7198            })
 7199        })
 7200    }
 7201
 7202    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7203        if self.take_rename(true, cx).is_some() {
 7204            return;
 7205        }
 7206
 7207        if self
 7208            .context_menu
 7209            .borrow_mut()
 7210            .as_mut()
 7211            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7212            .unwrap_or(false)
 7213        {
 7214            return;
 7215        }
 7216
 7217        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7218            cx.propagate();
 7219            return;
 7220        }
 7221
 7222        let Some(row_count) = self.visible_row_count() else {
 7223            return;
 7224        };
 7225
 7226        let autoscroll = if action.center_cursor {
 7227            Autoscroll::center()
 7228        } else {
 7229            Autoscroll::fit()
 7230        };
 7231
 7232        let text_layout_details = &self.text_layout_details(cx);
 7233        self.change_selections(Some(autoscroll), cx, |s| {
 7234            let line_mode = s.line_mode;
 7235            s.move_with(|map, selection| {
 7236                if !selection.is_empty() && !line_mode {
 7237                    selection.goal = SelectionGoal::None;
 7238                }
 7239                let (cursor, goal) = movement::down_by_rows(
 7240                    map,
 7241                    selection.end,
 7242                    row_count,
 7243                    selection.goal,
 7244                    false,
 7245                    text_layout_details,
 7246                );
 7247                selection.collapse_to(cursor, goal);
 7248            });
 7249        });
 7250    }
 7251
 7252    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7253        let text_layout_details = &self.text_layout_details(cx);
 7254        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7255            s.move_heads_with(|map, head, goal| {
 7256                movement::down(map, head, goal, false, text_layout_details)
 7257            })
 7258        });
 7259    }
 7260
 7261    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7262        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7263            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7264        }
 7265    }
 7266
 7267    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7268        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7269            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7270        }
 7271    }
 7272
 7273    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7274        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7275            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7276        }
 7277    }
 7278
 7279    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7280        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7281            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7282        }
 7283    }
 7284
 7285    pub fn move_to_previous_word_start(
 7286        &mut self,
 7287        _: &MoveToPreviousWordStart,
 7288        cx: &mut ViewContext<Self>,
 7289    ) {
 7290        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7291            s.move_cursors_with(|map, head, _| {
 7292                (
 7293                    movement::previous_word_start(map, head),
 7294                    SelectionGoal::None,
 7295                )
 7296            });
 7297        })
 7298    }
 7299
 7300    pub fn move_to_previous_subword_start(
 7301        &mut self,
 7302        _: &MoveToPreviousSubwordStart,
 7303        cx: &mut ViewContext<Self>,
 7304    ) {
 7305        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7306            s.move_cursors_with(|map, head, _| {
 7307                (
 7308                    movement::previous_subword_start(map, head),
 7309                    SelectionGoal::None,
 7310                )
 7311            });
 7312        })
 7313    }
 7314
 7315    pub fn select_to_previous_word_start(
 7316        &mut self,
 7317        _: &SelectToPreviousWordStart,
 7318        cx: &mut ViewContext<Self>,
 7319    ) {
 7320        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7321            s.move_heads_with(|map, head, _| {
 7322                (
 7323                    movement::previous_word_start(map, head),
 7324                    SelectionGoal::None,
 7325                )
 7326            });
 7327        })
 7328    }
 7329
 7330    pub fn select_to_previous_subword_start(
 7331        &mut self,
 7332        _: &SelectToPreviousSubwordStart,
 7333        cx: &mut ViewContext<Self>,
 7334    ) {
 7335        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7336            s.move_heads_with(|map, head, _| {
 7337                (
 7338                    movement::previous_subword_start(map, head),
 7339                    SelectionGoal::None,
 7340                )
 7341            });
 7342        })
 7343    }
 7344
 7345    pub fn delete_to_previous_word_start(
 7346        &mut self,
 7347        action: &DeleteToPreviousWordStart,
 7348        cx: &mut ViewContext<Self>,
 7349    ) {
 7350        self.transact(cx, |this, cx| {
 7351            this.select_autoclose_pair(cx);
 7352            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7353                let line_mode = s.line_mode;
 7354                s.move_with(|map, selection| {
 7355                    if selection.is_empty() && !line_mode {
 7356                        let cursor = if action.ignore_newlines {
 7357                            movement::previous_word_start(map, selection.head())
 7358                        } else {
 7359                            movement::previous_word_start_or_newline(map, selection.head())
 7360                        };
 7361                        selection.set_head(cursor, SelectionGoal::None);
 7362                    }
 7363                });
 7364            });
 7365            this.insert("", cx);
 7366        });
 7367    }
 7368
 7369    pub fn delete_to_previous_subword_start(
 7370        &mut self,
 7371        _: &DeleteToPreviousSubwordStart,
 7372        cx: &mut ViewContext<Self>,
 7373    ) {
 7374        self.transact(cx, |this, cx| {
 7375            this.select_autoclose_pair(cx);
 7376            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7377                let line_mode = s.line_mode;
 7378                s.move_with(|map, selection| {
 7379                    if selection.is_empty() && !line_mode {
 7380                        let cursor = movement::previous_subword_start(map, selection.head());
 7381                        selection.set_head(cursor, SelectionGoal::None);
 7382                    }
 7383                });
 7384            });
 7385            this.insert("", cx);
 7386        });
 7387    }
 7388
 7389    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7390        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7391            s.move_cursors_with(|map, head, _| {
 7392                (movement::next_word_end(map, head), SelectionGoal::None)
 7393            });
 7394        })
 7395    }
 7396
 7397    pub fn move_to_next_subword_end(
 7398        &mut self,
 7399        _: &MoveToNextSubwordEnd,
 7400        cx: &mut ViewContext<Self>,
 7401    ) {
 7402        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7403            s.move_cursors_with(|map, head, _| {
 7404                (movement::next_subword_end(map, head), SelectionGoal::None)
 7405            });
 7406        })
 7407    }
 7408
 7409    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7410        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7411            s.move_heads_with(|map, head, _| {
 7412                (movement::next_word_end(map, head), SelectionGoal::None)
 7413            });
 7414        })
 7415    }
 7416
 7417    pub fn select_to_next_subword_end(
 7418        &mut self,
 7419        _: &SelectToNextSubwordEnd,
 7420        cx: &mut ViewContext<Self>,
 7421    ) {
 7422        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7423            s.move_heads_with(|map, head, _| {
 7424                (movement::next_subword_end(map, head), SelectionGoal::None)
 7425            });
 7426        })
 7427    }
 7428
 7429    pub fn delete_to_next_word_end(
 7430        &mut self,
 7431        action: &DeleteToNextWordEnd,
 7432        cx: &mut ViewContext<Self>,
 7433    ) {
 7434        self.transact(cx, |this, cx| {
 7435            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7436                let line_mode = s.line_mode;
 7437                s.move_with(|map, selection| {
 7438                    if selection.is_empty() && !line_mode {
 7439                        let cursor = if action.ignore_newlines {
 7440                            movement::next_word_end(map, selection.head())
 7441                        } else {
 7442                            movement::next_word_end_or_newline(map, selection.head())
 7443                        };
 7444                        selection.set_head(cursor, SelectionGoal::None);
 7445                    }
 7446                });
 7447            });
 7448            this.insert("", cx);
 7449        });
 7450    }
 7451
 7452    pub fn delete_to_next_subword_end(
 7453        &mut self,
 7454        _: &DeleteToNextSubwordEnd,
 7455        cx: &mut ViewContext<Self>,
 7456    ) {
 7457        self.transact(cx, |this, cx| {
 7458            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7459                s.move_with(|map, selection| {
 7460                    if selection.is_empty() {
 7461                        let cursor = movement::next_subword_end(map, selection.head());
 7462                        selection.set_head(cursor, SelectionGoal::None);
 7463                    }
 7464                });
 7465            });
 7466            this.insert("", cx);
 7467        });
 7468    }
 7469
 7470    pub fn move_to_beginning_of_line(
 7471        &mut self,
 7472        action: &MoveToBeginningOfLine,
 7473        cx: &mut ViewContext<Self>,
 7474    ) {
 7475        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7476            s.move_cursors_with(|map, head, _| {
 7477                (
 7478                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7479                    SelectionGoal::None,
 7480                )
 7481            });
 7482        })
 7483    }
 7484
 7485    pub fn select_to_beginning_of_line(
 7486        &mut self,
 7487        action: &SelectToBeginningOfLine,
 7488        cx: &mut ViewContext<Self>,
 7489    ) {
 7490        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7491            s.move_heads_with(|map, head, _| {
 7492                (
 7493                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7494                    SelectionGoal::None,
 7495                )
 7496            });
 7497        });
 7498    }
 7499
 7500    pub fn delete_to_beginning_of_line(
 7501        &mut self,
 7502        _: &DeleteToBeginningOfLine,
 7503        cx: &mut ViewContext<Self>,
 7504    ) {
 7505        self.transact(cx, |this, cx| {
 7506            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7507                s.move_with(|_, selection| {
 7508                    selection.reversed = true;
 7509                });
 7510            });
 7511
 7512            this.select_to_beginning_of_line(
 7513                &SelectToBeginningOfLine {
 7514                    stop_at_soft_wraps: false,
 7515                },
 7516                cx,
 7517            );
 7518            this.backspace(&Backspace, cx);
 7519        });
 7520    }
 7521
 7522    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7523        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7524            s.move_cursors_with(|map, head, _| {
 7525                (
 7526                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7527                    SelectionGoal::None,
 7528                )
 7529            });
 7530        })
 7531    }
 7532
 7533    pub fn select_to_end_of_line(
 7534        &mut self,
 7535        action: &SelectToEndOfLine,
 7536        cx: &mut ViewContext<Self>,
 7537    ) {
 7538        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7539            s.move_heads_with(|map, head, _| {
 7540                (
 7541                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7542                    SelectionGoal::None,
 7543                )
 7544            });
 7545        })
 7546    }
 7547
 7548    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7549        self.transact(cx, |this, cx| {
 7550            this.select_to_end_of_line(
 7551                &SelectToEndOfLine {
 7552                    stop_at_soft_wraps: false,
 7553                },
 7554                cx,
 7555            );
 7556            this.delete(&Delete, cx);
 7557        });
 7558    }
 7559
 7560    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7561        self.transact(cx, |this, cx| {
 7562            this.select_to_end_of_line(
 7563                &SelectToEndOfLine {
 7564                    stop_at_soft_wraps: false,
 7565                },
 7566                cx,
 7567            );
 7568            this.cut(&Cut, cx);
 7569        });
 7570    }
 7571
 7572    pub fn move_to_start_of_paragraph(
 7573        &mut self,
 7574        _: &MoveToStartOfParagraph,
 7575        cx: &mut ViewContext<Self>,
 7576    ) {
 7577        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7578            cx.propagate();
 7579            return;
 7580        }
 7581
 7582        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7583            s.move_with(|map, selection| {
 7584                selection.collapse_to(
 7585                    movement::start_of_paragraph(map, selection.head(), 1),
 7586                    SelectionGoal::None,
 7587                )
 7588            });
 7589        })
 7590    }
 7591
 7592    pub fn move_to_end_of_paragraph(
 7593        &mut self,
 7594        _: &MoveToEndOfParagraph,
 7595        cx: &mut ViewContext<Self>,
 7596    ) {
 7597        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7598            cx.propagate();
 7599            return;
 7600        }
 7601
 7602        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7603            s.move_with(|map, selection| {
 7604                selection.collapse_to(
 7605                    movement::end_of_paragraph(map, selection.head(), 1),
 7606                    SelectionGoal::None,
 7607                )
 7608            });
 7609        })
 7610    }
 7611
 7612    pub fn select_to_start_of_paragraph(
 7613        &mut self,
 7614        _: &SelectToStartOfParagraph,
 7615        cx: &mut ViewContext<Self>,
 7616    ) {
 7617        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7618            cx.propagate();
 7619            return;
 7620        }
 7621
 7622        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7623            s.move_heads_with(|map, head, _| {
 7624                (
 7625                    movement::start_of_paragraph(map, head, 1),
 7626                    SelectionGoal::None,
 7627                )
 7628            });
 7629        })
 7630    }
 7631
 7632    pub fn select_to_end_of_paragraph(
 7633        &mut self,
 7634        _: &SelectToEndOfParagraph,
 7635        cx: &mut ViewContext<Self>,
 7636    ) {
 7637        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7638            cx.propagate();
 7639            return;
 7640        }
 7641
 7642        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7643            s.move_heads_with(|map, head, _| {
 7644                (
 7645                    movement::end_of_paragraph(map, head, 1),
 7646                    SelectionGoal::None,
 7647                )
 7648            });
 7649        })
 7650    }
 7651
 7652    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7653        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7654            cx.propagate();
 7655            return;
 7656        }
 7657
 7658        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7659            s.select_ranges(vec![0..0]);
 7660        });
 7661    }
 7662
 7663    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7664        let mut selection = self.selections.last::<Point>(cx);
 7665        selection.set_head(Point::zero(), SelectionGoal::None);
 7666
 7667        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7668            s.select(vec![selection]);
 7669        });
 7670    }
 7671
 7672    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7673        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7674            cx.propagate();
 7675            return;
 7676        }
 7677
 7678        let cursor = self.buffer.read(cx).read(cx).len();
 7679        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7680            s.select_ranges(vec![cursor..cursor])
 7681        });
 7682    }
 7683
 7684    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7685        self.nav_history = nav_history;
 7686    }
 7687
 7688    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7689        self.nav_history.as_ref()
 7690    }
 7691
 7692    fn push_to_nav_history(
 7693        &mut self,
 7694        cursor_anchor: Anchor,
 7695        new_position: Option<Point>,
 7696        cx: &mut ViewContext<Self>,
 7697    ) {
 7698        if let Some(nav_history) = self.nav_history.as_mut() {
 7699            let buffer = self.buffer.read(cx).read(cx);
 7700            let cursor_position = cursor_anchor.to_point(&buffer);
 7701            let scroll_state = self.scroll_manager.anchor();
 7702            let scroll_top_row = scroll_state.top_row(&buffer);
 7703            drop(buffer);
 7704
 7705            if let Some(new_position) = new_position {
 7706                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7707                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7708                    return;
 7709                }
 7710            }
 7711
 7712            nav_history.push(
 7713                Some(NavigationData {
 7714                    cursor_anchor,
 7715                    cursor_position,
 7716                    scroll_anchor: scroll_state,
 7717                    scroll_top_row,
 7718                }),
 7719                cx,
 7720            );
 7721        }
 7722    }
 7723
 7724    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7725        let buffer = self.buffer.read(cx).snapshot(cx);
 7726        let mut selection = self.selections.first::<usize>(cx);
 7727        selection.set_head(buffer.len(), SelectionGoal::None);
 7728        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7729            s.select(vec![selection]);
 7730        });
 7731    }
 7732
 7733    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7734        let end = self.buffer.read(cx).read(cx).len();
 7735        self.change_selections(None, cx, |s| {
 7736            s.select_ranges(vec![0..end]);
 7737        });
 7738    }
 7739
 7740    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7741        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7742        let mut selections = self.selections.all::<Point>(cx);
 7743        let max_point = display_map.buffer_snapshot.max_point();
 7744        for selection in &mut selections {
 7745            let rows = selection.spanned_rows(true, &display_map);
 7746            selection.start = Point::new(rows.start.0, 0);
 7747            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7748            selection.reversed = false;
 7749        }
 7750        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7751            s.select(selections);
 7752        });
 7753    }
 7754
 7755    pub fn split_selection_into_lines(
 7756        &mut self,
 7757        _: &SplitSelectionIntoLines,
 7758        cx: &mut ViewContext<Self>,
 7759    ) {
 7760        let mut to_unfold = Vec::new();
 7761        let mut new_selection_ranges = Vec::new();
 7762        {
 7763            let selections = self.selections.all::<Point>(cx);
 7764            let buffer = self.buffer.read(cx).read(cx);
 7765            for selection in selections {
 7766                for row in selection.start.row..selection.end.row {
 7767                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7768                    new_selection_ranges.push(cursor..cursor);
 7769                }
 7770                new_selection_ranges.push(selection.end..selection.end);
 7771                to_unfold.push(selection.start..selection.end);
 7772            }
 7773        }
 7774        self.unfold_ranges(&to_unfold, true, true, cx);
 7775        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7776            s.select_ranges(new_selection_ranges);
 7777        });
 7778    }
 7779
 7780    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7781        self.add_selection(true, cx);
 7782    }
 7783
 7784    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7785        self.add_selection(false, cx);
 7786    }
 7787
 7788    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7789        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7790        let mut selections = self.selections.all::<Point>(cx);
 7791        let text_layout_details = self.text_layout_details(cx);
 7792        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7793            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7794            let range = oldest_selection.display_range(&display_map).sorted();
 7795
 7796            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7797            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7798            let positions = start_x.min(end_x)..start_x.max(end_x);
 7799
 7800            selections.clear();
 7801            let mut stack = Vec::new();
 7802            for row in range.start.row().0..=range.end.row().0 {
 7803                if let Some(selection) = self.selections.build_columnar_selection(
 7804                    &display_map,
 7805                    DisplayRow(row),
 7806                    &positions,
 7807                    oldest_selection.reversed,
 7808                    &text_layout_details,
 7809                ) {
 7810                    stack.push(selection.id);
 7811                    selections.push(selection);
 7812                }
 7813            }
 7814
 7815            if above {
 7816                stack.reverse();
 7817            }
 7818
 7819            AddSelectionsState { above, stack }
 7820        });
 7821
 7822        let last_added_selection = *state.stack.last().unwrap();
 7823        let mut new_selections = Vec::new();
 7824        if above == state.above {
 7825            let end_row = if above {
 7826                DisplayRow(0)
 7827            } else {
 7828                display_map.max_point().row()
 7829            };
 7830
 7831            'outer: for selection in selections {
 7832                if selection.id == last_added_selection {
 7833                    let range = selection.display_range(&display_map).sorted();
 7834                    debug_assert_eq!(range.start.row(), range.end.row());
 7835                    let mut row = range.start.row();
 7836                    let positions =
 7837                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7838                            px(start)..px(end)
 7839                        } else {
 7840                            let start_x =
 7841                                display_map.x_for_display_point(range.start, &text_layout_details);
 7842                            let end_x =
 7843                                display_map.x_for_display_point(range.end, &text_layout_details);
 7844                            start_x.min(end_x)..start_x.max(end_x)
 7845                        };
 7846
 7847                    while row != end_row {
 7848                        if above {
 7849                            row.0 -= 1;
 7850                        } else {
 7851                            row.0 += 1;
 7852                        }
 7853
 7854                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7855                            &display_map,
 7856                            row,
 7857                            &positions,
 7858                            selection.reversed,
 7859                            &text_layout_details,
 7860                        ) {
 7861                            state.stack.push(new_selection.id);
 7862                            if above {
 7863                                new_selections.push(new_selection);
 7864                                new_selections.push(selection);
 7865                            } else {
 7866                                new_selections.push(selection);
 7867                                new_selections.push(new_selection);
 7868                            }
 7869
 7870                            continue 'outer;
 7871                        }
 7872                    }
 7873                }
 7874
 7875                new_selections.push(selection);
 7876            }
 7877        } else {
 7878            new_selections = selections;
 7879            new_selections.retain(|s| s.id != last_added_selection);
 7880            state.stack.pop();
 7881        }
 7882
 7883        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7884            s.select(new_selections);
 7885        });
 7886        if state.stack.len() > 1 {
 7887            self.add_selections_state = Some(state);
 7888        }
 7889    }
 7890
 7891    pub fn select_next_match_internal(
 7892        &mut self,
 7893        display_map: &DisplaySnapshot,
 7894        replace_newest: bool,
 7895        autoscroll: Option<Autoscroll>,
 7896        cx: &mut ViewContext<Self>,
 7897    ) -> Result<()> {
 7898        fn select_next_match_ranges(
 7899            this: &mut Editor,
 7900            range: Range<usize>,
 7901            replace_newest: bool,
 7902            auto_scroll: Option<Autoscroll>,
 7903            cx: &mut ViewContext<Editor>,
 7904        ) {
 7905            this.unfold_ranges(&[range.clone()], false, true, cx);
 7906            this.change_selections(auto_scroll, cx, |s| {
 7907                if replace_newest {
 7908                    s.delete(s.newest_anchor().id);
 7909                }
 7910                s.insert_range(range.clone());
 7911            });
 7912        }
 7913
 7914        let buffer = &display_map.buffer_snapshot;
 7915        let mut selections = self.selections.all::<usize>(cx);
 7916        if let Some(mut select_next_state) = self.select_next_state.take() {
 7917            let query = &select_next_state.query;
 7918            if !select_next_state.done {
 7919                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7920                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7921                let mut next_selected_range = None;
 7922
 7923                let bytes_after_last_selection =
 7924                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7925                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7926                let query_matches = query
 7927                    .stream_find_iter(bytes_after_last_selection)
 7928                    .map(|result| (last_selection.end, result))
 7929                    .chain(
 7930                        query
 7931                            .stream_find_iter(bytes_before_first_selection)
 7932                            .map(|result| (0, result)),
 7933                    );
 7934
 7935                for (start_offset, query_match) in query_matches {
 7936                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7937                    let offset_range =
 7938                        start_offset + query_match.start()..start_offset + query_match.end();
 7939                    let display_range = offset_range.start.to_display_point(display_map)
 7940                        ..offset_range.end.to_display_point(display_map);
 7941
 7942                    if !select_next_state.wordwise
 7943                        || (!movement::is_inside_word(display_map, display_range.start)
 7944                            && !movement::is_inside_word(display_map, display_range.end))
 7945                    {
 7946                        // TODO: This is n^2, because we might check all the selections
 7947                        if !selections
 7948                            .iter()
 7949                            .any(|selection| selection.range().overlaps(&offset_range))
 7950                        {
 7951                            next_selected_range = Some(offset_range);
 7952                            break;
 7953                        }
 7954                    }
 7955                }
 7956
 7957                if let Some(next_selected_range) = next_selected_range {
 7958                    select_next_match_ranges(
 7959                        self,
 7960                        next_selected_range,
 7961                        replace_newest,
 7962                        autoscroll,
 7963                        cx,
 7964                    );
 7965                } else {
 7966                    select_next_state.done = true;
 7967                }
 7968            }
 7969
 7970            self.select_next_state = Some(select_next_state);
 7971        } else {
 7972            let mut only_carets = true;
 7973            let mut same_text_selected = true;
 7974            let mut selected_text = None;
 7975
 7976            let mut selections_iter = selections.iter().peekable();
 7977            while let Some(selection) = selections_iter.next() {
 7978                if selection.start != selection.end {
 7979                    only_carets = false;
 7980                }
 7981
 7982                if same_text_selected {
 7983                    if selected_text.is_none() {
 7984                        selected_text =
 7985                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7986                    }
 7987
 7988                    if let Some(next_selection) = selections_iter.peek() {
 7989                        if next_selection.range().len() == selection.range().len() {
 7990                            let next_selected_text = buffer
 7991                                .text_for_range(next_selection.range())
 7992                                .collect::<String>();
 7993                            if Some(next_selected_text) != selected_text {
 7994                                same_text_selected = false;
 7995                                selected_text = None;
 7996                            }
 7997                        } else {
 7998                            same_text_selected = false;
 7999                            selected_text = None;
 8000                        }
 8001                    }
 8002                }
 8003            }
 8004
 8005            if only_carets {
 8006                for selection in &mut selections {
 8007                    let word_range = movement::surrounding_word(
 8008                        display_map,
 8009                        selection.start.to_display_point(display_map),
 8010                    );
 8011                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8012                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8013                    selection.goal = SelectionGoal::None;
 8014                    selection.reversed = false;
 8015                    select_next_match_ranges(
 8016                        self,
 8017                        selection.start..selection.end,
 8018                        replace_newest,
 8019                        autoscroll,
 8020                        cx,
 8021                    );
 8022                }
 8023
 8024                if selections.len() == 1 {
 8025                    let selection = selections
 8026                        .last()
 8027                        .expect("ensured that there's only one selection");
 8028                    let query = buffer
 8029                        .text_for_range(selection.start..selection.end)
 8030                        .collect::<String>();
 8031                    let is_empty = query.is_empty();
 8032                    let select_state = SelectNextState {
 8033                        query: AhoCorasick::new(&[query])?,
 8034                        wordwise: true,
 8035                        done: is_empty,
 8036                    };
 8037                    self.select_next_state = Some(select_state);
 8038                } else {
 8039                    self.select_next_state = None;
 8040                }
 8041            } else if let Some(selected_text) = selected_text {
 8042                self.select_next_state = Some(SelectNextState {
 8043                    query: AhoCorasick::new(&[selected_text])?,
 8044                    wordwise: false,
 8045                    done: false,
 8046                });
 8047                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8048            }
 8049        }
 8050        Ok(())
 8051    }
 8052
 8053    pub fn select_all_matches(
 8054        &mut self,
 8055        _action: &SelectAllMatches,
 8056        cx: &mut ViewContext<Self>,
 8057    ) -> Result<()> {
 8058        self.push_to_selection_history();
 8059        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8060
 8061        self.select_next_match_internal(&display_map, false, None, cx)?;
 8062        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8063            return Ok(());
 8064        };
 8065        if select_next_state.done {
 8066            return Ok(());
 8067        }
 8068
 8069        let mut new_selections = self.selections.all::<usize>(cx);
 8070
 8071        let buffer = &display_map.buffer_snapshot;
 8072        let query_matches = select_next_state
 8073            .query
 8074            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8075
 8076        for query_match in query_matches {
 8077            let query_match = query_match.unwrap(); // can only fail due to I/O
 8078            let offset_range = query_match.start()..query_match.end();
 8079            let display_range = offset_range.start.to_display_point(&display_map)
 8080                ..offset_range.end.to_display_point(&display_map);
 8081
 8082            if !select_next_state.wordwise
 8083                || (!movement::is_inside_word(&display_map, display_range.start)
 8084                    && !movement::is_inside_word(&display_map, display_range.end))
 8085            {
 8086                self.selections.change_with(cx, |selections| {
 8087                    new_selections.push(Selection {
 8088                        id: selections.new_selection_id(),
 8089                        start: offset_range.start,
 8090                        end: offset_range.end,
 8091                        reversed: false,
 8092                        goal: SelectionGoal::None,
 8093                    });
 8094                });
 8095            }
 8096        }
 8097
 8098        new_selections.sort_by_key(|selection| selection.start);
 8099        let mut ix = 0;
 8100        while ix + 1 < new_selections.len() {
 8101            let current_selection = &new_selections[ix];
 8102            let next_selection = &new_selections[ix + 1];
 8103            if current_selection.range().overlaps(&next_selection.range()) {
 8104                if current_selection.id < next_selection.id {
 8105                    new_selections.remove(ix + 1);
 8106                } else {
 8107                    new_selections.remove(ix);
 8108                }
 8109            } else {
 8110                ix += 1;
 8111            }
 8112        }
 8113
 8114        select_next_state.done = true;
 8115        self.unfold_ranges(
 8116            &new_selections
 8117                .iter()
 8118                .map(|selection| selection.range())
 8119                .collect::<Vec<_>>(),
 8120            false,
 8121            false,
 8122            cx,
 8123        );
 8124        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8125            selections.select(new_selections)
 8126        });
 8127
 8128        Ok(())
 8129    }
 8130
 8131    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8132        self.push_to_selection_history();
 8133        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8134        self.select_next_match_internal(
 8135            &display_map,
 8136            action.replace_newest,
 8137            Some(Autoscroll::newest()),
 8138            cx,
 8139        )?;
 8140        Ok(())
 8141    }
 8142
 8143    pub fn select_previous(
 8144        &mut self,
 8145        action: &SelectPrevious,
 8146        cx: &mut ViewContext<Self>,
 8147    ) -> Result<()> {
 8148        self.push_to_selection_history();
 8149        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8150        let buffer = &display_map.buffer_snapshot;
 8151        let mut selections = self.selections.all::<usize>(cx);
 8152        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8153            let query = &select_prev_state.query;
 8154            if !select_prev_state.done {
 8155                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8156                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8157                let mut next_selected_range = None;
 8158                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8159                let bytes_before_last_selection =
 8160                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8161                let bytes_after_first_selection =
 8162                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8163                let query_matches = query
 8164                    .stream_find_iter(bytes_before_last_selection)
 8165                    .map(|result| (last_selection.start, result))
 8166                    .chain(
 8167                        query
 8168                            .stream_find_iter(bytes_after_first_selection)
 8169                            .map(|result| (buffer.len(), result)),
 8170                    );
 8171                for (end_offset, query_match) in query_matches {
 8172                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8173                    let offset_range =
 8174                        end_offset - query_match.end()..end_offset - query_match.start();
 8175                    let display_range = offset_range.start.to_display_point(&display_map)
 8176                        ..offset_range.end.to_display_point(&display_map);
 8177
 8178                    if !select_prev_state.wordwise
 8179                        || (!movement::is_inside_word(&display_map, display_range.start)
 8180                            && !movement::is_inside_word(&display_map, display_range.end))
 8181                    {
 8182                        next_selected_range = Some(offset_range);
 8183                        break;
 8184                    }
 8185                }
 8186
 8187                if let Some(next_selected_range) = next_selected_range {
 8188                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8189                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8190                        if action.replace_newest {
 8191                            s.delete(s.newest_anchor().id);
 8192                        }
 8193                        s.insert_range(next_selected_range);
 8194                    });
 8195                } else {
 8196                    select_prev_state.done = true;
 8197                }
 8198            }
 8199
 8200            self.select_prev_state = Some(select_prev_state);
 8201        } else {
 8202            let mut only_carets = true;
 8203            let mut same_text_selected = true;
 8204            let mut selected_text = None;
 8205
 8206            let mut selections_iter = selections.iter().peekable();
 8207            while let Some(selection) = selections_iter.next() {
 8208                if selection.start != selection.end {
 8209                    only_carets = false;
 8210                }
 8211
 8212                if same_text_selected {
 8213                    if selected_text.is_none() {
 8214                        selected_text =
 8215                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8216                    }
 8217
 8218                    if let Some(next_selection) = selections_iter.peek() {
 8219                        if next_selection.range().len() == selection.range().len() {
 8220                            let next_selected_text = buffer
 8221                                .text_for_range(next_selection.range())
 8222                                .collect::<String>();
 8223                            if Some(next_selected_text) != selected_text {
 8224                                same_text_selected = false;
 8225                                selected_text = None;
 8226                            }
 8227                        } else {
 8228                            same_text_selected = false;
 8229                            selected_text = None;
 8230                        }
 8231                    }
 8232                }
 8233            }
 8234
 8235            if only_carets {
 8236                for selection in &mut selections {
 8237                    let word_range = movement::surrounding_word(
 8238                        &display_map,
 8239                        selection.start.to_display_point(&display_map),
 8240                    );
 8241                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8242                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8243                    selection.goal = SelectionGoal::None;
 8244                    selection.reversed = false;
 8245                }
 8246                if selections.len() == 1 {
 8247                    let selection = selections
 8248                        .last()
 8249                        .expect("ensured that there's only one selection");
 8250                    let query = buffer
 8251                        .text_for_range(selection.start..selection.end)
 8252                        .collect::<String>();
 8253                    let is_empty = query.is_empty();
 8254                    let select_state = SelectNextState {
 8255                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8256                        wordwise: true,
 8257                        done: is_empty,
 8258                    };
 8259                    self.select_prev_state = Some(select_state);
 8260                } else {
 8261                    self.select_prev_state = None;
 8262                }
 8263
 8264                self.unfold_ranges(
 8265                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8266                    false,
 8267                    true,
 8268                    cx,
 8269                );
 8270                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8271                    s.select(selections);
 8272                });
 8273            } else if let Some(selected_text) = selected_text {
 8274                self.select_prev_state = Some(SelectNextState {
 8275                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8276                    wordwise: false,
 8277                    done: false,
 8278                });
 8279                self.select_previous(action, cx)?;
 8280            }
 8281        }
 8282        Ok(())
 8283    }
 8284
 8285    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8286        if self.read_only(cx) {
 8287            return;
 8288        }
 8289        let text_layout_details = &self.text_layout_details(cx);
 8290        self.transact(cx, |this, cx| {
 8291            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8292            let mut edits = Vec::new();
 8293            let mut selection_edit_ranges = Vec::new();
 8294            let mut last_toggled_row = None;
 8295            let snapshot = this.buffer.read(cx).read(cx);
 8296            let empty_str: Arc<str> = Arc::default();
 8297            let mut suffixes_inserted = Vec::new();
 8298            let ignore_indent = action.ignore_indent;
 8299
 8300            fn comment_prefix_range(
 8301                snapshot: &MultiBufferSnapshot,
 8302                row: MultiBufferRow,
 8303                comment_prefix: &str,
 8304                comment_prefix_whitespace: &str,
 8305                ignore_indent: bool,
 8306            ) -> Range<Point> {
 8307                let indent_size = if ignore_indent {
 8308                    0
 8309                } else {
 8310                    snapshot.indent_size_for_line(row).len
 8311                };
 8312
 8313                let start = Point::new(row.0, indent_size);
 8314
 8315                let mut line_bytes = snapshot
 8316                    .bytes_in_range(start..snapshot.max_point())
 8317                    .flatten()
 8318                    .copied();
 8319
 8320                // If this line currently begins with the line comment prefix, then record
 8321                // the range containing the prefix.
 8322                if line_bytes
 8323                    .by_ref()
 8324                    .take(comment_prefix.len())
 8325                    .eq(comment_prefix.bytes())
 8326                {
 8327                    // Include any whitespace that matches the comment prefix.
 8328                    let matching_whitespace_len = line_bytes
 8329                        .zip(comment_prefix_whitespace.bytes())
 8330                        .take_while(|(a, b)| a == b)
 8331                        .count() as u32;
 8332                    let end = Point::new(
 8333                        start.row,
 8334                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8335                    );
 8336                    start..end
 8337                } else {
 8338                    start..start
 8339                }
 8340            }
 8341
 8342            fn comment_suffix_range(
 8343                snapshot: &MultiBufferSnapshot,
 8344                row: MultiBufferRow,
 8345                comment_suffix: &str,
 8346                comment_suffix_has_leading_space: bool,
 8347            ) -> Range<Point> {
 8348                let end = Point::new(row.0, snapshot.line_len(row));
 8349                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8350
 8351                let mut line_end_bytes = snapshot
 8352                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8353                    .flatten()
 8354                    .copied();
 8355
 8356                let leading_space_len = if suffix_start_column > 0
 8357                    && line_end_bytes.next() == Some(b' ')
 8358                    && comment_suffix_has_leading_space
 8359                {
 8360                    1
 8361                } else {
 8362                    0
 8363                };
 8364
 8365                // If this line currently begins with the line comment prefix, then record
 8366                // the range containing the prefix.
 8367                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8368                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8369                    start..end
 8370                } else {
 8371                    end..end
 8372                }
 8373            }
 8374
 8375            // TODO: Handle selections that cross excerpts
 8376            for selection in &mut selections {
 8377                let start_column = snapshot
 8378                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8379                    .len;
 8380                let language = if let Some(language) =
 8381                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8382                {
 8383                    language
 8384                } else {
 8385                    continue;
 8386                };
 8387
 8388                selection_edit_ranges.clear();
 8389
 8390                // If multiple selections contain a given row, avoid processing that
 8391                // row more than once.
 8392                let mut start_row = MultiBufferRow(selection.start.row);
 8393                if last_toggled_row == Some(start_row) {
 8394                    start_row = start_row.next_row();
 8395                }
 8396                let end_row =
 8397                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8398                        MultiBufferRow(selection.end.row - 1)
 8399                    } else {
 8400                        MultiBufferRow(selection.end.row)
 8401                    };
 8402                last_toggled_row = Some(end_row);
 8403
 8404                if start_row > end_row {
 8405                    continue;
 8406                }
 8407
 8408                // If the language has line comments, toggle those.
 8409                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8410
 8411                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8412                if ignore_indent {
 8413                    full_comment_prefixes = full_comment_prefixes
 8414                        .into_iter()
 8415                        .map(|s| Arc::from(s.trim_end()))
 8416                        .collect();
 8417                }
 8418
 8419                if !full_comment_prefixes.is_empty() {
 8420                    let first_prefix = full_comment_prefixes
 8421                        .first()
 8422                        .expect("prefixes is non-empty");
 8423                    let prefix_trimmed_lengths = full_comment_prefixes
 8424                        .iter()
 8425                        .map(|p| p.trim_end_matches(' ').len())
 8426                        .collect::<SmallVec<[usize; 4]>>();
 8427
 8428                    let mut all_selection_lines_are_comments = true;
 8429
 8430                    for row in start_row.0..=end_row.0 {
 8431                        let row = MultiBufferRow(row);
 8432                        if start_row < end_row && snapshot.is_line_blank(row) {
 8433                            continue;
 8434                        }
 8435
 8436                        let prefix_range = full_comment_prefixes
 8437                            .iter()
 8438                            .zip(prefix_trimmed_lengths.iter().copied())
 8439                            .map(|(prefix, trimmed_prefix_len)| {
 8440                                comment_prefix_range(
 8441                                    snapshot.deref(),
 8442                                    row,
 8443                                    &prefix[..trimmed_prefix_len],
 8444                                    &prefix[trimmed_prefix_len..],
 8445                                    ignore_indent,
 8446                                )
 8447                            })
 8448                            .max_by_key(|range| range.end.column - range.start.column)
 8449                            .expect("prefixes is non-empty");
 8450
 8451                        if prefix_range.is_empty() {
 8452                            all_selection_lines_are_comments = false;
 8453                        }
 8454
 8455                        selection_edit_ranges.push(prefix_range);
 8456                    }
 8457
 8458                    if all_selection_lines_are_comments {
 8459                        edits.extend(
 8460                            selection_edit_ranges
 8461                                .iter()
 8462                                .cloned()
 8463                                .map(|range| (range, empty_str.clone())),
 8464                        );
 8465                    } else {
 8466                        let min_column = selection_edit_ranges
 8467                            .iter()
 8468                            .map(|range| range.start.column)
 8469                            .min()
 8470                            .unwrap_or(0);
 8471                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8472                            let position = Point::new(range.start.row, min_column);
 8473                            (position..position, first_prefix.clone())
 8474                        }));
 8475                    }
 8476                } else if let Some((full_comment_prefix, comment_suffix)) =
 8477                    language.block_comment_delimiters()
 8478                {
 8479                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8480                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8481                    let prefix_range = comment_prefix_range(
 8482                        snapshot.deref(),
 8483                        start_row,
 8484                        comment_prefix,
 8485                        comment_prefix_whitespace,
 8486                        ignore_indent,
 8487                    );
 8488                    let suffix_range = comment_suffix_range(
 8489                        snapshot.deref(),
 8490                        end_row,
 8491                        comment_suffix.trim_start_matches(' '),
 8492                        comment_suffix.starts_with(' '),
 8493                    );
 8494
 8495                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8496                        edits.push((
 8497                            prefix_range.start..prefix_range.start,
 8498                            full_comment_prefix.clone(),
 8499                        ));
 8500                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8501                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8502                    } else {
 8503                        edits.push((prefix_range, empty_str.clone()));
 8504                        edits.push((suffix_range, empty_str.clone()));
 8505                    }
 8506                } else {
 8507                    continue;
 8508                }
 8509            }
 8510
 8511            drop(snapshot);
 8512            this.buffer.update(cx, |buffer, cx| {
 8513                buffer.edit(edits, None, cx);
 8514            });
 8515
 8516            // Adjust selections so that they end before any comment suffixes that
 8517            // were inserted.
 8518            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8519            let mut selections = this.selections.all::<Point>(cx);
 8520            let snapshot = this.buffer.read(cx).read(cx);
 8521            for selection in &mut selections {
 8522                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8523                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8524                        Ordering::Less => {
 8525                            suffixes_inserted.next();
 8526                            continue;
 8527                        }
 8528                        Ordering::Greater => break,
 8529                        Ordering::Equal => {
 8530                            if selection.end.column == snapshot.line_len(row) {
 8531                                if selection.is_empty() {
 8532                                    selection.start.column -= suffix_len as u32;
 8533                                }
 8534                                selection.end.column -= suffix_len as u32;
 8535                            }
 8536                            break;
 8537                        }
 8538                    }
 8539                }
 8540            }
 8541
 8542            drop(snapshot);
 8543            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8544
 8545            let selections = this.selections.all::<Point>(cx);
 8546            let selections_on_single_row = selections.windows(2).all(|selections| {
 8547                selections[0].start.row == selections[1].start.row
 8548                    && selections[0].end.row == selections[1].end.row
 8549                    && selections[0].start.row == selections[0].end.row
 8550            });
 8551            let selections_selecting = selections
 8552                .iter()
 8553                .any(|selection| selection.start != selection.end);
 8554            let advance_downwards = action.advance_downwards
 8555                && selections_on_single_row
 8556                && !selections_selecting
 8557                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8558
 8559            if advance_downwards {
 8560                let snapshot = this.buffer.read(cx).snapshot(cx);
 8561
 8562                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8563                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8564                        let mut point = display_point.to_point(display_snapshot);
 8565                        point.row += 1;
 8566                        point = snapshot.clip_point(point, Bias::Left);
 8567                        let display_point = point.to_display_point(display_snapshot);
 8568                        let goal = SelectionGoal::HorizontalPosition(
 8569                            display_snapshot
 8570                                .x_for_display_point(display_point, text_layout_details)
 8571                                .into(),
 8572                        );
 8573                        (display_point, goal)
 8574                    })
 8575                });
 8576            }
 8577        });
 8578    }
 8579
 8580    pub fn select_enclosing_symbol(
 8581        &mut self,
 8582        _: &SelectEnclosingSymbol,
 8583        cx: &mut ViewContext<Self>,
 8584    ) {
 8585        let buffer = self.buffer.read(cx).snapshot(cx);
 8586        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8587
 8588        fn update_selection(
 8589            selection: &Selection<usize>,
 8590            buffer_snap: &MultiBufferSnapshot,
 8591        ) -> Option<Selection<usize>> {
 8592            let cursor = selection.head();
 8593            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8594            for symbol in symbols.iter().rev() {
 8595                let start = symbol.range.start.to_offset(buffer_snap);
 8596                let end = symbol.range.end.to_offset(buffer_snap);
 8597                let new_range = start..end;
 8598                if start < selection.start || end > selection.end {
 8599                    return Some(Selection {
 8600                        id: selection.id,
 8601                        start: new_range.start,
 8602                        end: new_range.end,
 8603                        goal: SelectionGoal::None,
 8604                        reversed: selection.reversed,
 8605                    });
 8606                }
 8607            }
 8608            None
 8609        }
 8610
 8611        let mut selected_larger_symbol = false;
 8612        let new_selections = old_selections
 8613            .iter()
 8614            .map(|selection| match update_selection(selection, &buffer) {
 8615                Some(new_selection) => {
 8616                    if new_selection.range() != selection.range() {
 8617                        selected_larger_symbol = true;
 8618                    }
 8619                    new_selection
 8620                }
 8621                None => selection.clone(),
 8622            })
 8623            .collect::<Vec<_>>();
 8624
 8625        if selected_larger_symbol {
 8626            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8627                s.select(new_selections);
 8628            });
 8629        }
 8630    }
 8631
 8632    pub fn select_larger_syntax_node(
 8633        &mut self,
 8634        _: &SelectLargerSyntaxNode,
 8635        cx: &mut ViewContext<Self>,
 8636    ) {
 8637        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8638        let buffer = self.buffer.read(cx).snapshot(cx);
 8639        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8640
 8641        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8642        let mut selected_larger_node = false;
 8643        let new_selections = old_selections
 8644            .iter()
 8645            .map(|selection| {
 8646                let old_range = selection.start..selection.end;
 8647                let mut new_range = old_range.clone();
 8648                while let Some(containing_range) =
 8649                    buffer.range_for_syntax_ancestor(new_range.clone())
 8650                {
 8651                    new_range = containing_range;
 8652                    if !display_map.intersects_fold(new_range.start)
 8653                        && !display_map.intersects_fold(new_range.end)
 8654                    {
 8655                        break;
 8656                    }
 8657                }
 8658
 8659                selected_larger_node |= new_range != old_range;
 8660                Selection {
 8661                    id: selection.id,
 8662                    start: new_range.start,
 8663                    end: new_range.end,
 8664                    goal: SelectionGoal::None,
 8665                    reversed: selection.reversed,
 8666                }
 8667            })
 8668            .collect::<Vec<_>>();
 8669
 8670        if selected_larger_node {
 8671            stack.push(old_selections);
 8672            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8673                s.select(new_selections);
 8674            });
 8675        }
 8676        self.select_larger_syntax_node_stack = stack;
 8677    }
 8678
 8679    pub fn select_smaller_syntax_node(
 8680        &mut self,
 8681        _: &SelectSmallerSyntaxNode,
 8682        cx: &mut ViewContext<Self>,
 8683    ) {
 8684        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8685        if let Some(selections) = stack.pop() {
 8686            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8687                s.select(selections.to_vec());
 8688            });
 8689        }
 8690        self.select_larger_syntax_node_stack = stack;
 8691    }
 8692
 8693    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8694        if !EditorSettings::get_global(cx).gutter.runnables {
 8695            self.clear_tasks();
 8696            return Task::ready(());
 8697        }
 8698        let project = self.project.as_ref().map(Model::downgrade);
 8699        cx.spawn(|this, mut cx| async move {
 8700            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8701            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8702                return;
 8703            };
 8704            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8705                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8706            }) else {
 8707                return;
 8708            };
 8709
 8710            let hide_runnables = project
 8711                .update(&mut cx, |project, cx| {
 8712                    // Do not display any test indicators in non-dev server remote projects.
 8713                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8714                })
 8715                .unwrap_or(true);
 8716            if hide_runnables {
 8717                return;
 8718            }
 8719            let new_rows =
 8720                cx.background_executor()
 8721                    .spawn({
 8722                        let snapshot = display_snapshot.clone();
 8723                        async move {
 8724                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8725                        }
 8726                    })
 8727                    .await;
 8728            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8729
 8730            this.update(&mut cx, |this, _| {
 8731                this.clear_tasks();
 8732                for (key, value) in rows {
 8733                    this.insert_tasks(key, value);
 8734                }
 8735            })
 8736            .ok();
 8737        })
 8738    }
 8739    fn fetch_runnable_ranges(
 8740        snapshot: &DisplaySnapshot,
 8741        range: Range<Anchor>,
 8742    ) -> Vec<language::RunnableRange> {
 8743        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8744    }
 8745
 8746    fn runnable_rows(
 8747        project: Model<Project>,
 8748        snapshot: DisplaySnapshot,
 8749        runnable_ranges: Vec<RunnableRange>,
 8750        mut cx: AsyncWindowContext,
 8751    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8752        runnable_ranges
 8753            .into_iter()
 8754            .filter_map(|mut runnable| {
 8755                let tasks = cx
 8756                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8757                    .ok()?;
 8758                if tasks.is_empty() {
 8759                    return None;
 8760                }
 8761
 8762                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8763
 8764                let row = snapshot
 8765                    .buffer_snapshot
 8766                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8767                    .1
 8768                    .start
 8769                    .row;
 8770
 8771                let context_range =
 8772                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8773                Some((
 8774                    (runnable.buffer_id, row),
 8775                    RunnableTasks {
 8776                        templates: tasks,
 8777                        offset: MultiBufferOffset(runnable.run_range.start),
 8778                        context_range,
 8779                        column: point.column,
 8780                        extra_variables: runnable.extra_captures,
 8781                    },
 8782                ))
 8783            })
 8784            .collect()
 8785    }
 8786
 8787    fn templates_with_tags(
 8788        project: &Model<Project>,
 8789        runnable: &mut Runnable,
 8790        cx: &WindowContext<'_>,
 8791    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8792        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8793            let (worktree_id, file) = project
 8794                .buffer_for_id(runnable.buffer, cx)
 8795                .and_then(|buffer| buffer.read(cx).file())
 8796                .map(|file| (file.worktree_id(cx), file.clone()))
 8797                .unzip();
 8798
 8799            (
 8800                project.task_store().read(cx).task_inventory().cloned(),
 8801                worktree_id,
 8802                file,
 8803            )
 8804        });
 8805
 8806        let tags = mem::take(&mut runnable.tags);
 8807        let mut tags: Vec<_> = tags
 8808            .into_iter()
 8809            .flat_map(|tag| {
 8810                let tag = tag.0.clone();
 8811                inventory
 8812                    .as_ref()
 8813                    .into_iter()
 8814                    .flat_map(|inventory| {
 8815                        inventory.read(cx).list_tasks(
 8816                            file.clone(),
 8817                            Some(runnable.language.clone()),
 8818                            worktree_id,
 8819                            cx,
 8820                        )
 8821                    })
 8822                    .filter(move |(_, template)| {
 8823                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8824                    })
 8825            })
 8826            .sorted_by_key(|(kind, _)| kind.to_owned())
 8827            .collect();
 8828        if let Some((leading_tag_source, _)) = tags.first() {
 8829            // Strongest source wins; if we have worktree tag binding, prefer that to
 8830            // global and language bindings;
 8831            // if we have a global binding, prefer that to language binding.
 8832            let first_mismatch = tags
 8833                .iter()
 8834                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8835            if let Some(index) = first_mismatch {
 8836                tags.truncate(index);
 8837            }
 8838        }
 8839
 8840        tags
 8841    }
 8842
 8843    pub fn move_to_enclosing_bracket(
 8844        &mut self,
 8845        _: &MoveToEnclosingBracket,
 8846        cx: &mut ViewContext<Self>,
 8847    ) {
 8848        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8849            s.move_offsets_with(|snapshot, selection| {
 8850                let Some(enclosing_bracket_ranges) =
 8851                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8852                else {
 8853                    return;
 8854                };
 8855
 8856                let mut best_length = usize::MAX;
 8857                let mut best_inside = false;
 8858                let mut best_in_bracket_range = false;
 8859                let mut best_destination = None;
 8860                for (open, close) in enclosing_bracket_ranges {
 8861                    let close = close.to_inclusive();
 8862                    let length = close.end() - open.start;
 8863                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8864                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8865                        || close.contains(&selection.head());
 8866
 8867                    // If best is next to a bracket and current isn't, skip
 8868                    if !in_bracket_range && best_in_bracket_range {
 8869                        continue;
 8870                    }
 8871
 8872                    // Prefer smaller lengths unless best is inside and current isn't
 8873                    if length > best_length && (best_inside || !inside) {
 8874                        continue;
 8875                    }
 8876
 8877                    best_length = length;
 8878                    best_inside = inside;
 8879                    best_in_bracket_range = in_bracket_range;
 8880                    best_destination = Some(
 8881                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8882                            if inside {
 8883                                open.end
 8884                            } else {
 8885                                open.start
 8886                            }
 8887                        } else if inside {
 8888                            *close.start()
 8889                        } else {
 8890                            *close.end()
 8891                        },
 8892                    );
 8893                }
 8894
 8895                if let Some(destination) = best_destination {
 8896                    selection.collapse_to(destination, SelectionGoal::None);
 8897                }
 8898            })
 8899        });
 8900    }
 8901
 8902    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8903        self.end_selection(cx);
 8904        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8905        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8906            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8907            self.select_next_state = entry.select_next_state;
 8908            self.select_prev_state = entry.select_prev_state;
 8909            self.add_selections_state = entry.add_selections_state;
 8910            self.request_autoscroll(Autoscroll::newest(), cx);
 8911        }
 8912        self.selection_history.mode = SelectionHistoryMode::Normal;
 8913    }
 8914
 8915    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8916        self.end_selection(cx);
 8917        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8918        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8919            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8920            self.select_next_state = entry.select_next_state;
 8921            self.select_prev_state = entry.select_prev_state;
 8922            self.add_selections_state = entry.add_selections_state;
 8923            self.request_autoscroll(Autoscroll::newest(), cx);
 8924        }
 8925        self.selection_history.mode = SelectionHistoryMode::Normal;
 8926    }
 8927
 8928    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8929        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8930    }
 8931
 8932    pub fn expand_excerpts_down(
 8933        &mut self,
 8934        action: &ExpandExcerptsDown,
 8935        cx: &mut ViewContext<Self>,
 8936    ) {
 8937        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8938    }
 8939
 8940    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8941        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8942    }
 8943
 8944    pub fn expand_excerpts_for_direction(
 8945        &mut self,
 8946        lines: u32,
 8947        direction: ExpandExcerptDirection,
 8948        cx: &mut ViewContext<Self>,
 8949    ) {
 8950        let selections = self.selections.disjoint_anchors();
 8951
 8952        let lines = if lines == 0 {
 8953            EditorSettings::get_global(cx).expand_excerpt_lines
 8954        } else {
 8955            lines
 8956        };
 8957
 8958        self.buffer.update(cx, |buffer, cx| {
 8959            buffer.expand_excerpts(
 8960                selections
 8961                    .iter()
 8962                    .map(|selection| selection.head().excerpt_id)
 8963                    .dedup(),
 8964                lines,
 8965                direction,
 8966                cx,
 8967            )
 8968        })
 8969    }
 8970
 8971    pub fn expand_excerpt(
 8972        &mut self,
 8973        excerpt: ExcerptId,
 8974        direction: ExpandExcerptDirection,
 8975        cx: &mut ViewContext<Self>,
 8976    ) {
 8977        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8978        self.buffer.update(cx, |buffer, cx| {
 8979            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8980        })
 8981    }
 8982
 8983    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8984        self.go_to_diagnostic_impl(Direction::Next, cx)
 8985    }
 8986
 8987    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8988        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8989    }
 8990
 8991    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8992        let buffer = self.buffer.read(cx).snapshot(cx);
 8993        let selection = self.selections.newest::<usize>(cx);
 8994
 8995        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8996        if direction == Direction::Next {
 8997            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8998                let (group_id, jump_to) = popover.activation_info();
 8999                if self.activate_diagnostics(group_id, cx) {
 9000                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9001                        let mut new_selection = s.newest_anchor().clone();
 9002                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9003                        s.select_anchors(vec![new_selection.clone()]);
 9004                    });
 9005                }
 9006                return;
 9007            }
 9008        }
 9009
 9010        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9011            active_diagnostics
 9012                .primary_range
 9013                .to_offset(&buffer)
 9014                .to_inclusive()
 9015        });
 9016        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9017            if active_primary_range.contains(&selection.head()) {
 9018                *active_primary_range.start()
 9019            } else {
 9020                selection.head()
 9021            }
 9022        } else {
 9023            selection.head()
 9024        };
 9025        let snapshot = self.snapshot(cx);
 9026        loop {
 9027            let diagnostics = if direction == Direction::Prev {
 9028                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9029            } else {
 9030                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9031            }
 9032            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9033            let group = diagnostics
 9034                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9035                // be sorted in a stable way
 9036                // skip until we are at current active diagnostic, if it exists
 9037                .skip_while(|entry| {
 9038                    (match direction {
 9039                        Direction::Prev => entry.range.start >= search_start,
 9040                        Direction::Next => entry.range.start <= search_start,
 9041                    }) && self
 9042                        .active_diagnostics
 9043                        .as_ref()
 9044                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9045                })
 9046                .find_map(|entry| {
 9047                    if entry.diagnostic.is_primary
 9048                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9049                        && !entry.range.is_empty()
 9050                        // if we match with the active diagnostic, skip it
 9051                        && Some(entry.diagnostic.group_id)
 9052                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9053                    {
 9054                        Some((entry.range, entry.diagnostic.group_id))
 9055                    } else {
 9056                        None
 9057                    }
 9058                });
 9059
 9060            if let Some((primary_range, group_id)) = group {
 9061                if self.activate_diagnostics(group_id, cx) {
 9062                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9063                        s.select(vec![Selection {
 9064                            id: selection.id,
 9065                            start: primary_range.start,
 9066                            end: primary_range.start,
 9067                            reversed: false,
 9068                            goal: SelectionGoal::None,
 9069                        }]);
 9070                    });
 9071                }
 9072                break;
 9073            } else {
 9074                // Cycle around to the start of the buffer, potentially moving back to the start of
 9075                // the currently active diagnostic.
 9076                active_primary_range.take();
 9077                if direction == Direction::Prev {
 9078                    if search_start == buffer.len() {
 9079                        break;
 9080                    } else {
 9081                        search_start = buffer.len();
 9082                    }
 9083                } else if search_start == 0 {
 9084                    break;
 9085                } else {
 9086                    search_start = 0;
 9087                }
 9088            }
 9089        }
 9090    }
 9091
 9092    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9093        let snapshot = self.snapshot(cx);
 9094        let selection = self.selections.newest::<Point>(cx);
 9095        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9096    }
 9097
 9098    fn go_to_hunk_after_position(
 9099        &mut self,
 9100        snapshot: &EditorSnapshot,
 9101        position: Point,
 9102        cx: &mut ViewContext<'_, Editor>,
 9103    ) -> Option<MultiBufferDiffHunk> {
 9104        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9105            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9106                snapshot,
 9107                position,
 9108                ix > 0,
 9109                snapshot.diff_map.diff_hunks_in_range(
 9110                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9111                    &snapshot.buffer_snapshot,
 9112                ),
 9113                cx,
 9114            ) {
 9115                return Some(hunk);
 9116            }
 9117        }
 9118        None
 9119    }
 9120
 9121    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9122        let snapshot = self.snapshot(cx);
 9123        let selection = self.selections.newest::<Point>(cx);
 9124        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9125    }
 9126
 9127    fn go_to_hunk_before_position(
 9128        &mut self,
 9129        snapshot: &EditorSnapshot,
 9130        position: Point,
 9131        cx: &mut ViewContext<'_, Editor>,
 9132    ) -> Option<MultiBufferDiffHunk> {
 9133        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9134            .into_iter()
 9135            .enumerate()
 9136        {
 9137            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9138                snapshot,
 9139                position,
 9140                ix > 0,
 9141                snapshot
 9142                    .diff_map
 9143                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9144                cx,
 9145            ) {
 9146                return Some(hunk);
 9147            }
 9148        }
 9149        None
 9150    }
 9151
 9152    fn go_to_next_hunk_in_direction(
 9153        &mut self,
 9154        snapshot: &DisplaySnapshot,
 9155        initial_point: Point,
 9156        is_wrapped: bool,
 9157        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9158        cx: &mut ViewContext<Editor>,
 9159    ) -> Option<MultiBufferDiffHunk> {
 9160        let display_point = initial_point.to_display_point(snapshot);
 9161        let mut hunks = hunks
 9162            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9163            .filter(|(display_hunk, _)| {
 9164                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9165            })
 9166            .dedup();
 9167
 9168        if let Some((display_hunk, hunk)) = hunks.next() {
 9169            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9170                let row = display_hunk.start_display_row();
 9171                let point = DisplayPoint::new(row, 0);
 9172                s.select_display_ranges([point..point]);
 9173            });
 9174
 9175            Some(hunk)
 9176        } else {
 9177            None
 9178        }
 9179    }
 9180
 9181    pub fn go_to_definition(
 9182        &mut self,
 9183        _: &GoToDefinition,
 9184        cx: &mut ViewContext<Self>,
 9185    ) -> Task<Result<Navigated>> {
 9186        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9187        cx.spawn(|editor, mut cx| async move {
 9188            if definition.await? == Navigated::Yes {
 9189                return Ok(Navigated::Yes);
 9190            }
 9191            match editor.update(&mut cx, |editor, cx| {
 9192                editor.find_all_references(&FindAllReferences, cx)
 9193            })? {
 9194                Some(references) => references.await,
 9195                None => Ok(Navigated::No),
 9196            }
 9197        })
 9198    }
 9199
 9200    pub fn go_to_declaration(
 9201        &mut self,
 9202        _: &GoToDeclaration,
 9203        cx: &mut ViewContext<Self>,
 9204    ) -> Task<Result<Navigated>> {
 9205        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9206    }
 9207
 9208    pub fn go_to_declaration_split(
 9209        &mut self,
 9210        _: &GoToDeclaration,
 9211        cx: &mut ViewContext<Self>,
 9212    ) -> Task<Result<Navigated>> {
 9213        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9214    }
 9215
 9216    pub fn go_to_implementation(
 9217        &mut self,
 9218        _: &GoToImplementation,
 9219        cx: &mut ViewContext<Self>,
 9220    ) -> Task<Result<Navigated>> {
 9221        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9222    }
 9223
 9224    pub fn go_to_implementation_split(
 9225        &mut self,
 9226        _: &GoToImplementationSplit,
 9227        cx: &mut ViewContext<Self>,
 9228    ) -> Task<Result<Navigated>> {
 9229        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9230    }
 9231
 9232    pub fn go_to_type_definition(
 9233        &mut self,
 9234        _: &GoToTypeDefinition,
 9235        cx: &mut ViewContext<Self>,
 9236    ) -> Task<Result<Navigated>> {
 9237        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9238    }
 9239
 9240    pub fn go_to_definition_split(
 9241        &mut self,
 9242        _: &GoToDefinitionSplit,
 9243        cx: &mut ViewContext<Self>,
 9244    ) -> Task<Result<Navigated>> {
 9245        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9246    }
 9247
 9248    pub fn go_to_type_definition_split(
 9249        &mut self,
 9250        _: &GoToTypeDefinitionSplit,
 9251        cx: &mut ViewContext<Self>,
 9252    ) -> Task<Result<Navigated>> {
 9253        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9254    }
 9255
 9256    fn go_to_definition_of_kind(
 9257        &mut self,
 9258        kind: GotoDefinitionKind,
 9259        split: bool,
 9260        cx: &mut ViewContext<Self>,
 9261    ) -> Task<Result<Navigated>> {
 9262        let Some(provider) = self.semantics_provider.clone() else {
 9263            return Task::ready(Ok(Navigated::No));
 9264        };
 9265        let head = self.selections.newest::<usize>(cx).head();
 9266        let buffer = self.buffer.read(cx);
 9267        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9268            text_anchor
 9269        } else {
 9270            return Task::ready(Ok(Navigated::No));
 9271        };
 9272
 9273        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9274            return Task::ready(Ok(Navigated::No));
 9275        };
 9276
 9277        cx.spawn(|editor, mut cx| async move {
 9278            let definitions = definitions.await?;
 9279            let navigated = editor
 9280                .update(&mut cx, |editor, cx| {
 9281                    editor.navigate_to_hover_links(
 9282                        Some(kind),
 9283                        definitions
 9284                            .into_iter()
 9285                            .filter(|location| {
 9286                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9287                            })
 9288                            .map(HoverLink::Text)
 9289                            .collect::<Vec<_>>(),
 9290                        split,
 9291                        cx,
 9292                    )
 9293                })?
 9294                .await?;
 9295            anyhow::Ok(navigated)
 9296        })
 9297    }
 9298
 9299    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9300        let selection = self.selections.newest_anchor();
 9301        let head = selection.head();
 9302        let tail = selection.tail();
 9303
 9304        let Some((buffer, start_position)) =
 9305            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9306        else {
 9307            return;
 9308        };
 9309
 9310        let end_position = if head != tail {
 9311            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9312                return;
 9313            };
 9314            Some(pos)
 9315        } else {
 9316            None
 9317        };
 9318
 9319        let url_finder = cx.spawn(|editor, mut cx| async move {
 9320            let url = if let Some(end_pos) = end_position {
 9321                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9322            } else {
 9323                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9324            };
 9325
 9326            if let Some(url) = url {
 9327                editor.update(&mut cx, |_, cx| {
 9328                    cx.open_url(&url);
 9329                })
 9330            } else {
 9331                Ok(())
 9332            }
 9333        });
 9334
 9335        url_finder.detach();
 9336    }
 9337
 9338    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9339        let Some(workspace) = self.workspace() else {
 9340            return;
 9341        };
 9342
 9343        let position = self.selections.newest_anchor().head();
 9344
 9345        let Some((buffer, buffer_position)) =
 9346            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9347        else {
 9348            return;
 9349        };
 9350
 9351        let project = self.project.clone();
 9352
 9353        cx.spawn(|_, mut cx| async move {
 9354            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9355
 9356            if let Some((_, path)) = result {
 9357                workspace
 9358                    .update(&mut cx, |workspace, cx| {
 9359                        workspace.open_resolved_path(path, cx)
 9360                    })?
 9361                    .await?;
 9362            }
 9363            anyhow::Ok(())
 9364        })
 9365        .detach();
 9366    }
 9367
 9368    pub(crate) fn navigate_to_hover_links(
 9369        &mut self,
 9370        kind: Option<GotoDefinitionKind>,
 9371        mut definitions: Vec<HoverLink>,
 9372        split: bool,
 9373        cx: &mut ViewContext<Editor>,
 9374    ) -> Task<Result<Navigated>> {
 9375        // If there is one definition, just open it directly
 9376        if definitions.len() == 1 {
 9377            let definition = definitions.pop().unwrap();
 9378
 9379            enum TargetTaskResult {
 9380                Location(Option<Location>),
 9381                AlreadyNavigated,
 9382            }
 9383
 9384            let target_task = match definition {
 9385                HoverLink::Text(link) => {
 9386                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9387                }
 9388                HoverLink::InlayHint(lsp_location, server_id) => {
 9389                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9390                    cx.background_executor().spawn(async move {
 9391                        let location = computation.await?;
 9392                        Ok(TargetTaskResult::Location(location))
 9393                    })
 9394                }
 9395                HoverLink::Url(url) => {
 9396                    cx.open_url(&url);
 9397                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9398                }
 9399                HoverLink::File(path) => {
 9400                    if let Some(workspace) = self.workspace() {
 9401                        cx.spawn(|_, mut cx| async move {
 9402                            workspace
 9403                                .update(&mut cx, |workspace, cx| {
 9404                                    workspace.open_resolved_path(path, cx)
 9405                                })?
 9406                                .await
 9407                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9408                        })
 9409                    } else {
 9410                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9411                    }
 9412                }
 9413            };
 9414            cx.spawn(|editor, mut cx| async move {
 9415                let target = match target_task.await.context("target resolution task")? {
 9416                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9417                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9418                    TargetTaskResult::Location(Some(target)) => target,
 9419                };
 9420
 9421                editor.update(&mut cx, |editor, cx| {
 9422                    let Some(workspace) = editor.workspace() else {
 9423                        return Navigated::No;
 9424                    };
 9425                    let pane = workspace.read(cx).active_pane().clone();
 9426
 9427                    let range = target.range.to_offset(target.buffer.read(cx));
 9428                    let range = editor.range_for_match(&range);
 9429
 9430                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9431                        let buffer = target.buffer.read(cx);
 9432                        let range = check_multiline_range(buffer, range);
 9433                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9434                            s.select_ranges([range]);
 9435                        });
 9436                    } else {
 9437                        cx.window_context().defer(move |cx| {
 9438                            let target_editor: View<Self> =
 9439                                workspace.update(cx, |workspace, cx| {
 9440                                    let pane = if split {
 9441                                        workspace.adjacent_pane(cx)
 9442                                    } else {
 9443                                        workspace.active_pane().clone()
 9444                                    };
 9445
 9446                                    workspace.open_project_item(
 9447                                        pane,
 9448                                        target.buffer.clone(),
 9449                                        true,
 9450                                        true,
 9451                                        cx,
 9452                                    )
 9453                                });
 9454                            target_editor.update(cx, |target_editor, cx| {
 9455                                // When selecting a definition in a different buffer, disable the nav history
 9456                                // to avoid creating a history entry at the previous cursor location.
 9457                                pane.update(cx, |pane, _| pane.disable_history());
 9458                                let buffer = target.buffer.read(cx);
 9459                                let range = check_multiline_range(buffer, range);
 9460                                target_editor.change_selections(
 9461                                    Some(Autoscroll::focused()),
 9462                                    cx,
 9463                                    |s| {
 9464                                        s.select_ranges([range]);
 9465                                    },
 9466                                );
 9467                                pane.update(cx, |pane, _| pane.enable_history());
 9468                            });
 9469                        });
 9470                    }
 9471                    Navigated::Yes
 9472                })
 9473            })
 9474        } else if !definitions.is_empty() {
 9475            cx.spawn(|editor, mut cx| async move {
 9476                let (title, location_tasks, workspace) = editor
 9477                    .update(&mut cx, |editor, cx| {
 9478                        let tab_kind = match kind {
 9479                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9480                            _ => "Definitions",
 9481                        };
 9482                        let title = definitions
 9483                            .iter()
 9484                            .find_map(|definition| match definition {
 9485                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9486                                    let buffer = origin.buffer.read(cx);
 9487                                    format!(
 9488                                        "{} for {}",
 9489                                        tab_kind,
 9490                                        buffer
 9491                                            .text_for_range(origin.range.clone())
 9492                                            .collect::<String>()
 9493                                    )
 9494                                }),
 9495                                HoverLink::InlayHint(_, _) => None,
 9496                                HoverLink::Url(_) => None,
 9497                                HoverLink::File(_) => None,
 9498                            })
 9499                            .unwrap_or(tab_kind.to_string());
 9500                        let location_tasks = definitions
 9501                            .into_iter()
 9502                            .map(|definition| match definition {
 9503                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9504                                HoverLink::InlayHint(lsp_location, server_id) => {
 9505                                    editor.compute_target_location(lsp_location, server_id, cx)
 9506                                }
 9507                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9508                                HoverLink::File(_) => Task::ready(Ok(None)),
 9509                            })
 9510                            .collect::<Vec<_>>();
 9511                        (title, location_tasks, editor.workspace().clone())
 9512                    })
 9513                    .context("location tasks preparation")?;
 9514
 9515                let locations = future::join_all(location_tasks)
 9516                    .await
 9517                    .into_iter()
 9518                    .filter_map(|location| location.transpose())
 9519                    .collect::<Result<_>>()
 9520                    .context("location tasks")?;
 9521
 9522                let Some(workspace) = workspace else {
 9523                    return Ok(Navigated::No);
 9524                };
 9525                let opened = workspace
 9526                    .update(&mut cx, |workspace, cx| {
 9527                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9528                    })
 9529                    .ok();
 9530
 9531                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9532            })
 9533        } else {
 9534            Task::ready(Ok(Navigated::No))
 9535        }
 9536    }
 9537
 9538    fn compute_target_location(
 9539        &self,
 9540        lsp_location: lsp::Location,
 9541        server_id: LanguageServerId,
 9542        cx: &mut ViewContext<Self>,
 9543    ) -> Task<anyhow::Result<Option<Location>>> {
 9544        let Some(project) = self.project.clone() else {
 9545            return Task::ready(Ok(None));
 9546        };
 9547
 9548        cx.spawn(move |editor, mut cx| async move {
 9549            let location_task = editor.update(&mut cx, |_, cx| {
 9550                project.update(cx, |project, cx| {
 9551                    let language_server_name = project
 9552                        .language_server_statuses(cx)
 9553                        .find(|(id, _)| server_id == *id)
 9554                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9555                    language_server_name.map(|language_server_name| {
 9556                        project.open_local_buffer_via_lsp(
 9557                            lsp_location.uri.clone(),
 9558                            server_id,
 9559                            language_server_name,
 9560                            cx,
 9561                        )
 9562                    })
 9563                })
 9564            })?;
 9565            let location = match location_task {
 9566                Some(task) => Some({
 9567                    let target_buffer_handle = task.await.context("open local buffer")?;
 9568                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9569                        let target_start = target_buffer
 9570                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9571                        let target_end = target_buffer
 9572                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9573                        target_buffer.anchor_after(target_start)
 9574                            ..target_buffer.anchor_before(target_end)
 9575                    })?;
 9576                    Location {
 9577                        buffer: target_buffer_handle,
 9578                        range,
 9579                    }
 9580                }),
 9581                None => None,
 9582            };
 9583            Ok(location)
 9584        })
 9585    }
 9586
 9587    pub fn find_all_references(
 9588        &mut self,
 9589        _: &FindAllReferences,
 9590        cx: &mut ViewContext<Self>,
 9591    ) -> Option<Task<Result<Navigated>>> {
 9592        let selection = self.selections.newest::<usize>(cx);
 9593        let multi_buffer = self.buffer.read(cx);
 9594        let head = selection.head();
 9595
 9596        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9597        let head_anchor = multi_buffer_snapshot.anchor_at(
 9598            head,
 9599            if head < selection.tail() {
 9600                Bias::Right
 9601            } else {
 9602                Bias::Left
 9603            },
 9604        );
 9605
 9606        match self
 9607            .find_all_references_task_sources
 9608            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9609        {
 9610            Ok(_) => {
 9611                log::info!(
 9612                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9613                );
 9614                return None;
 9615            }
 9616            Err(i) => {
 9617                self.find_all_references_task_sources.insert(i, head_anchor);
 9618            }
 9619        }
 9620
 9621        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9622        let workspace = self.workspace()?;
 9623        let project = workspace.read(cx).project().clone();
 9624        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9625        Some(cx.spawn(|editor, mut cx| async move {
 9626            let _cleanup = defer({
 9627                let mut cx = cx.clone();
 9628                move || {
 9629                    let _ = editor.update(&mut cx, |editor, _| {
 9630                        if let Ok(i) =
 9631                            editor
 9632                                .find_all_references_task_sources
 9633                                .binary_search_by(|anchor| {
 9634                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9635                                })
 9636                        {
 9637                            editor.find_all_references_task_sources.remove(i);
 9638                        }
 9639                    });
 9640                }
 9641            });
 9642
 9643            let locations = references.await?;
 9644            if locations.is_empty() {
 9645                return anyhow::Ok(Navigated::No);
 9646            }
 9647
 9648            workspace.update(&mut cx, |workspace, cx| {
 9649                let title = locations
 9650                    .first()
 9651                    .as_ref()
 9652                    .map(|location| {
 9653                        let buffer = location.buffer.read(cx);
 9654                        format!(
 9655                            "References to `{}`",
 9656                            buffer
 9657                                .text_for_range(location.range.clone())
 9658                                .collect::<String>()
 9659                        )
 9660                    })
 9661                    .unwrap();
 9662                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9663                Navigated::Yes
 9664            })
 9665        }))
 9666    }
 9667
 9668    /// Opens a multibuffer with the given project locations in it
 9669    pub fn open_locations_in_multibuffer(
 9670        workspace: &mut Workspace,
 9671        mut locations: Vec<Location>,
 9672        title: String,
 9673        split: bool,
 9674        cx: &mut ViewContext<Workspace>,
 9675    ) {
 9676        // If there are multiple definitions, open them in a multibuffer
 9677        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9678        let mut locations = locations.into_iter().peekable();
 9679        let mut ranges_to_highlight = Vec::new();
 9680        let capability = workspace.project().read(cx).capability();
 9681
 9682        let excerpt_buffer = cx.new_model(|cx| {
 9683            let mut multibuffer = MultiBuffer::new(capability);
 9684            while let Some(location) = locations.next() {
 9685                let buffer = location.buffer.read(cx);
 9686                let mut ranges_for_buffer = Vec::new();
 9687                let range = location.range.to_offset(buffer);
 9688                ranges_for_buffer.push(range.clone());
 9689
 9690                while let Some(next_location) = locations.peek() {
 9691                    if next_location.buffer == location.buffer {
 9692                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9693                        locations.next();
 9694                    } else {
 9695                        break;
 9696                    }
 9697                }
 9698
 9699                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9700                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9701                    location.buffer.clone(),
 9702                    ranges_for_buffer,
 9703                    DEFAULT_MULTIBUFFER_CONTEXT,
 9704                    cx,
 9705                ))
 9706            }
 9707
 9708            multibuffer.with_title(title)
 9709        });
 9710
 9711        let editor = cx.new_view(|cx| {
 9712            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9713        });
 9714        editor.update(cx, |editor, cx| {
 9715            if let Some(first_range) = ranges_to_highlight.first() {
 9716                editor.change_selections(None, cx, |selections| {
 9717                    selections.clear_disjoint();
 9718                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9719                });
 9720            }
 9721            editor.highlight_background::<Self>(
 9722                &ranges_to_highlight,
 9723                |theme| theme.editor_highlighted_line_background,
 9724                cx,
 9725            );
 9726            editor.register_buffers_with_language_servers(cx);
 9727        });
 9728
 9729        let item = Box::new(editor);
 9730        let item_id = item.item_id();
 9731
 9732        if split {
 9733            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9734        } else {
 9735            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9736                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9737                    pane.close_current_preview_item(cx)
 9738                } else {
 9739                    None
 9740                }
 9741            });
 9742            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9743        }
 9744        workspace.active_pane().update(cx, |pane, cx| {
 9745            pane.set_preview_item_id(Some(item_id), cx);
 9746        });
 9747    }
 9748
 9749    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9750        use language::ToOffset as _;
 9751
 9752        let provider = self.semantics_provider.clone()?;
 9753        let selection = self.selections.newest_anchor().clone();
 9754        let (cursor_buffer, cursor_buffer_position) = self
 9755            .buffer
 9756            .read(cx)
 9757            .text_anchor_for_position(selection.head(), cx)?;
 9758        let (tail_buffer, cursor_buffer_position_end) = self
 9759            .buffer
 9760            .read(cx)
 9761            .text_anchor_for_position(selection.tail(), cx)?;
 9762        if tail_buffer != cursor_buffer {
 9763            return None;
 9764        }
 9765
 9766        let snapshot = cursor_buffer.read(cx).snapshot();
 9767        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9768        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9769        let prepare_rename = provider
 9770            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9771            .unwrap_or_else(|| Task::ready(Ok(None)));
 9772        drop(snapshot);
 9773
 9774        Some(cx.spawn(|this, mut cx| async move {
 9775            let rename_range = if let Some(range) = prepare_rename.await? {
 9776                Some(range)
 9777            } else {
 9778                this.update(&mut cx, |this, cx| {
 9779                    let buffer = this.buffer.read(cx).snapshot(cx);
 9780                    let mut buffer_highlights = this
 9781                        .document_highlights_for_position(selection.head(), &buffer)
 9782                        .filter(|highlight| {
 9783                            highlight.start.excerpt_id == selection.head().excerpt_id
 9784                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9785                        });
 9786                    buffer_highlights
 9787                        .next()
 9788                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9789                })?
 9790            };
 9791            if let Some(rename_range) = rename_range {
 9792                this.update(&mut cx, |this, cx| {
 9793                    let snapshot = cursor_buffer.read(cx).snapshot();
 9794                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9795                    let cursor_offset_in_rename_range =
 9796                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9797                    let cursor_offset_in_rename_range_end =
 9798                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9799
 9800                    this.take_rename(false, cx);
 9801                    let buffer = this.buffer.read(cx).read(cx);
 9802                    let cursor_offset = selection.head().to_offset(&buffer);
 9803                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9804                    let rename_end = rename_start + rename_buffer_range.len();
 9805                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9806                    let mut old_highlight_id = None;
 9807                    let old_name: Arc<str> = buffer
 9808                        .chunks(rename_start..rename_end, true)
 9809                        .map(|chunk| {
 9810                            if old_highlight_id.is_none() {
 9811                                old_highlight_id = chunk.syntax_highlight_id;
 9812                            }
 9813                            chunk.text
 9814                        })
 9815                        .collect::<String>()
 9816                        .into();
 9817
 9818                    drop(buffer);
 9819
 9820                    // Position the selection in the rename editor so that it matches the current selection.
 9821                    this.show_local_selections = false;
 9822                    let rename_editor = cx.new_view(|cx| {
 9823                        let mut editor = Editor::single_line(cx);
 9824                        editor.buffer.update(cx, |buffer, cx| {
 9825                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9826                        });
 9827                        let rename_selection_range = match cursor_offset_in_rename_range
 9828                            .cmp(&cursor_offset_in_rename_range_end)
 9829                        {
 9830                            Ordering::Equal => {
 9831                                editor.select_all(&SelectAll, cx);
 9832                                return editor;
 9833                            }
 9834                            Ordering::Less => {
 9835                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9836                            }
 9837                            Ordering::Greater => {
 9838                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9839                            }
 9840                        };
 9841                        if rename_selection_range.end > old_name.len() {
 9842                            editor.select_all(&SelectAll, cx);
 9843                        } else {
 9844                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9845                                s.select_ranges([rename_selection_range]);
 9846                            });
 9847                        }
 9848                        editor
 9849                    });
 9850                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9851                        if e == &EditorEvent::Focused {
 9852                            cx.emit(EditorEvent::FocusedIn)
 9853                        }
 9854                    })
 9855                    .detach();
 9856
 9857                    let write_highlights =
 9858                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9859                    let read_highlights =
 9860                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9861                    let ranges = write_highlights
 9862                        .iter()
 9863                        .flat_map(|(_, ranges)| ranges.iter())
 9864                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9865                        .cloned()
 9866                        .collect();
 9867
 9868                    this.highlight_text::<Rename>(
 9869                        ranges,
 9870                        HighlightStyle {
 9871                            fade_out: Some(0.6),
 9872                            ..Default::default()
 9873                        },
 9874                        cx,
 9875                    );
 9876                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9877                    cx.focus(&rename_focus_handle);
 9878                    let block_id = this.insert_blocks(
 9879                        [BlockProperties {
 9880                            style: BlockStyle::Flex,
 9881                            placement: BlockPlacement::Below(range.start),
 9882                            height: 1,
 9883                            render: Arc::new({
 9884                                let rename_editor = rename_editor.clone();
 9885                                move |cx: &mut BlockContext| {
 9886                                    let mut text_style = cx.editor_style.text.clone();
 9887                                    if let Some(highlight_style) = old_highlight_id
 9888                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9889                                    {
 9890                                        text_style = text_style.highlight(highlight_style);
 9891                                    }
 9892                                    div()
 9893                                        .block_mouse_down()
 9894                                        .pl(cx.anchor_x)
 9895                                        .child(EditorElement::new(
 9896                                            &rename_editor,
 9897                                            EditorStyle {
 9898                                                background: cx.theme().system().transparent,
 9899                                                local_player: cx.editor_style.local_player,
 9900                                                text: text_style,
 9901                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9902                                                syntax: cx.editor_style.syntax.clone(),
 9903                                                status: cx.editor_style.status.clone(),
 9904                                                inlay_hints_style: HighlightStyle {
 9905                                                    font_weight: Some(FontWeight::BOLD),
 9906                                                    ..make_inlay_hints_style(cx)
 9907                                                },
 9908                                                inline_completion_styles: make_suggestion_styles(
 9909                                                    cx,
 9910                                                ),
 9911                                                ..EditorStyle::default()
 9912                                            },
 9913                                        ))
 9914                                        .into_any_element()
 9915                                }
 9916                            }),
 9917                            priority: 0,
 9918                        }],
 9919                        Some(Autoscroll::fit()),
 9920                        cx,
 9921                    )[0];
 9922                    this.pending_rename = Some(RenameState {
 9923                        range,
 9924                        old_name,
 9925                        editor: rename_editor,
 9926                        block_id,
 9927                    });
 9928                })?;
 9929            }
 9930
 9931            Ok(())
 9932        }))
 9933    }
 9934
 9935    pub fn confirm_rename(
 9936        &mut self,
 9937        _: &ConfirmRename,
 9938        cx: &mut ViewContext<Self>,
 9939    ) -> Option<Task<Result<()>>> {
 9940        let rename = self.take_rename(false, cx)?;
 9941        let workspace = self.workspace()?.downgrade();
 9942        let (buffer, start) = self
 9943            .buffer
 9944            .read(cx)
 9945            .text_anchor_for_position(rename.range.start, cx)?;
 9946        let (end_buffer, _) = self
 9947            .buffer
 9948            .read(cx)
 9949            .text_anchor_for_position(rename.range.end, cx)?;
 9950        if buffer != end_buffer {
 9951            return None;
 9952        }
 9953
 9954        let old_name = rename.old_name;
 9955        let new_name = rename.editor.read(cx).text(cx);
 9956
 9957        let rename = self.semantics_provider.as_ref()?.perform_rename(
 9958            &buffer,
 9959            start,
 9960            new_name.clone(),
 9961            cx,
 9962        )?;
 9963
 9964        Some(cx.spawn(|editor, mut cx| async move {
 9965            let project_transaction = rename.await?;
 9966            Self::open_project_transaction(
 9967                &editor,
 9968                workspace,
 9969                project_transaction,
 9970                format!("Rename: {}{}", old_name, new_name),
 9971                cx.clone(),
 9972            )
 9973            .await?;
 9974
 9975            editor.update(&mut cx, |editor, cx| {
 9976                editor.refresh_document_highlights(cx);
 9977            })?;
 9978            Ok(())
 9979        }))
 9980    }
 9981
 9982    fn take_rename(
 9983        &mut self,
 9984        moving_cursor: bool,
 9985        cx: &mut ViewContext<Self>,
 9986    ) -> Option<RenameState> {
 9987        let rename = self.pending_rename.take()?;
 9988        if rename.editor.focus_handle(cx).is_focused(cx) {
 9989            cx.focus(&self.focus_handle);
 9990        }
 9991
 9992        self.remove_blocks(
 9993            [rename.block_id].into_iter().collect(),
 9994            Some(Autoscroll::fit()),
 9995            cx,
 9996        );
 9997        self.clear_highlights::<Rename>(cx);
 9998        self.show_local_selections = true;
 9999
10000        if moving_cursor {
10001            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10002                editor.selections.newest::<usize>(cx).head()
10003            });
10004
10005            // Update the selection to match the position of the selection inside
10006            // the rename editor.
10007            let snapshot = self.buffer.read(cx).read(cx);
10008            let rename_range = rename.range.to_offset(&snapshot);
10009            let cursor_in_editor = snapshot
10010                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10011                .min(rename_range.end);
10012            drop(snapshot);
10013
10014            self.change_selections(None, cx, |s| {
10015                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10016            });
10017        } else {
10018            self.refresh_document_highlights(cx);
10019        }
10020
10021        Some(rename)
10022    }
10023
10024    pub fn pending_rename(&self) -> Option<&RenameState> {
10025        self.pending_rename.as_ref()
10026    }
10027
10028    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10029        let project = match &self.project {
10030            Some(project) => project.clone(),
10031            None => return None,
10032        };
10033
10034        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10035    }
10036
10037    fn format_selections(
10038        &mut self,
10039        _: &FormatSelections,
10040        cx: &mut ViewContext<Self>,
10041    ) -> Option<Task<Result<()>>> {
10042        let project = match &self.project {
10043            Some(project) => project.clone(),
10044            None => return None,
10045        };
10046
10047        let selections = self
10048            .selections
10049            .all_adjusted(cx)
10050            .into_iter()
10051            .filter(|s| !s.is_empty())
10052            .collect_vec();
10053
10054        Some(self.perform_format(
10055            project,
10056            FormatTrigger::Manual,
10057            FormatTarget::Ranges(selections),
10058            cx,
10059        ))
10060    }
10061
10062    fn perform_format(
10063        &mut self,
10064        project: Model<Project>,
10065        trigger: FormatTrigger,
10066        target: FormatTarget,
10067        cx: &mut ViewContext<Self>,
10068    ) -> Task<Result<()>> {
10069        let buffer = self.buffer().clone();
10070        let mut buffers = buffer.read(cx).all_buffers();
10071        if trigger == FormatTrigger::Save {
10072            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10073        }
10074
10075        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10076        let format = project.update(cx, |project, cx| {
10077            project.format(buffers, true, trigger, target, cx)
10078        });
10079
10080        cx.spawn(|_, mut cx| async move {
10081            let transaction = futures::select_biased! {
10082                () = timeout => {
10083                    log::warn!("timed out waiting for formatting");
10084                    None
10085                }
10086                transaction = format.log_err().fuse() => transaction,
10087            };
10088
10089            buffer
10090                .update(&mut cx, |buffer, cx| {
10091                    if let Some(transaction) = transaction {
10092                        if !buffer.is_singleton() {
10093                            buffer.push_transaction(&transaction.0, cx);
10094                        }
10095                    }
10096
10097                    cx.notify();
10098                })
10099                .ok();
10100
10101            Ok(())
10102        })
10103    }
10104
10105    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10106        if let Some(project) = self.project.clone() {
10107            self.buffer.update(cx, |multi_buffer, cx| {
10108                project.update(cx, |project, cx| {
10109                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10110                });
10111            })
10112        }
10113    }
10114
10115    fn cancel_language_server_work(
10116        &mut self,
10117        _: &actions::CancelLanguageServerWork,
10118        cx: &mut ViewContext<Self>,
10119    ) {
10120        if let Some(project) = self.project.clone() {
10121            self.buffer.update(cx, |multi_buffer, cx| {
10122                project.update(cx, |project, cx| {
10123                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10124                });
10125            })
10126        }
10127    }
10128
10129    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10130        cx.show_character_palette();
10131    }
10132
10133    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10134        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10135            let buffer = self.buffer.read(cx).snapshot(cx);
10136            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10137            let is_valid = buffer
10138                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10139                .any(|entry| {
10140                    entry.diagnostic.is_primary
10141                        && !entry.range.is_empty()
10142                        && entry.range.start == primary_range_start
10143                        && entry.diagnostic.message == active_diagnostics.primary_message
10144                });
10145
10146            if is_valid != active_diagnostics.is_valid {
10147                active_diagnostics.is_valid = is_valid;
10148                let mut new_styles = HashMap::default();
10149                for (block_id, diagnostic) in &active_diagnostics.blocks {
10150                    new_styles.insert(
10151                        *block_id,
10152                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10153                    );
10154                }
10155                self.display_map.update(cx, |display_map, _cx| {
10156                    display_map.replace_blocks(new_styles)
10157                });
10158            }
10159        }
10160    }
10161
10162    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10163        self.dismiss_diagnostics(cx);
10164        let snapshot = self.snapshot(cx);
10165        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10166            let buffer = self.buffer.read(cx).snapshot(cx);
10167
10168            let mut primary_range = None;
10169            let mut primary_message = None;
10170            let mut group_end = Point::zero();
10171            let diagnostic_group = buffer
10172                .diagnostic_group::<MultiBufferPoint>(group_id)
10173                .filter_map(|entry| {
10174                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10175                        && (entry.range.start.row == entry.range.end.row
10176                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10177                    {
10178                        return None;
10179                    }
10180                    if entry.range.end > group_end {
10181                        group_end = entry.range.end;
10182                    }
10183                    if entry.diagnostic.is_primary {
10184                        primary_range = Some(entry.range.clone());
10185                        primary_message = Some(entry.diagnostic.message.clone());
10186                    }
10187                    Some(entry)
10188                })
10189                .collect::<Vec<_>>();
10190            let primary_range = primary_range?;
10191            let primary_message = primary_message?;
10192            let primary_range =
10193                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10194
10195            let blocks = display_map
10196                .insert_blocks(
10197                    diagnostic_group.iter().map(|entry| {
10198                        let diagnostic = entry.diagnostic.clone();
10199                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10200                        BlockProperties {
10201                            style: BlockStyle::Fixed,
10202                            placement: BlockPlacement::Below(
10203                                buffer.anchor_after(entry.range.start),
10204                            ),
10205                            height: message_height,
10206                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10207                            priority: 0,
10208                        }
10209                    }),
10210                    cx,
10211                )
10212                .into_iter()
10213                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10214                .collect();
10215
10216            Some(ActiveDiagnosticGroup {
10217                primary_range,
10218                primary_message,
10219                group_id,
10220                blocks,
10221                is_valid: true,
10222            })
10223        });
10224        self.active_diagnostics.is_some()
10225    }
10226
10227    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10228        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10229            self.display_map.update(cx, |display_map, cx| {
10230                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10231            });
10232            cx.notify();
10233        }
10234    }
10235
10236    pub fn set_selections_from_remote(
10237        &mut self,
10238        selections: Vec<Selection<Anchor>>,
10239        pending_selection: Option<Selection<Anchor>>,
10240        cx: &mut ViewContext<Self>,
10241    ) {
10242        let old_cursor_position = self.selections.newest_anchor().head();
10243        self.selections.change_with(cx, |s| {
10244            s.select_anchors(selections);
10245            if let Some(pending_selection) = pending_selection {
10246                s.set_pending(pending_selection, SelectMode::Character);
10247            } else {
10248                s.clear_pending();
10249            }
10250        });
10251        self.selections_did_change(false, &old_cursor_position, true, cx);
10252    }
10253
10254    fn push_to_selection_history(&mut self) {
10255        self.selection_history.push(SelectionHistoryEntry {
10256            selections: self.selections.disjoint_anchors(),
10257            select_next_state: self.select_next_state.clone(),
10258            select_prev_state: self.select_prev_state.clone(),
10259            add_selections_state: self.add_selections_state.clone(),
10260        });
10261    }
10262
10263    pub fn transact(
10264        &mut self,
10265        cx: &mut ViewContext<Self>,
10266        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10267    ) -> Option<TransactionId> {
10268        self.start_transaction_at(Instant::now(), cx);
10269        update(self, cx);
10270        self.end_transaction_at(Instant::now(), cx)
10271    }
10272
10273    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10274        self.end_selection(cx);
10275        if let Some(tx_id) = self
10276            .buffer
10277            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10278        {
10279            self.selection_history
10280                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10281            cx.emit(EditorEvent::TransactionBegun {
10282                transaction_id: tx_id,
10283            })
10284        }
10285    }
10286
10287    fn end_transaction_at(
10288        &mut self,
10289        now: Instant,
10290        cx: &mut ViewContext<Self>,
10291    ) -> Option<TransactionId> {
10292        if let Some(transaction_id) = self
10293            .buffer
10294            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10295        {
10296            if let Some((_, end_selections)) =
10297                self.selection_history.transaction_mut(transaction_id)
10298            {
10299                *end_selections = Some(self.selections.disjoint_anchors());
10300            } else {
10301                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10302            }
10303
10304            cx.emit(EditorEvent::Edited { transaction_id });
10305            Some(transaction_id)
10306        } else {
10307            None
10308        }
10309    }
10310
10311    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10312        if self.is_singleton(cx) {
10313            let selection = self.selections.newest::<Point>(cx);
10314
10315            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10316            let range = if selection.is_empty() {
10317                let point = selection.head().to_display_point(&display_map);
10318                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10319                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10320                    .to_point(&display_map);
10321                start..end
10322            } else {
10323                selection.range()
10324            };
10325            if display_map.folds_in_range(range).next().is_some() {
10326                self.unfold_lines(&Default::default(), cx)
10327            } else {
10328                self.fold(&Default::default(), cx)
10329            }
10330        } else {
10331            let (display_snapshot, selections) = self.selections.all_adjusted_display(cx);
10332            let mut toggled_buffers = HashSet::default();
10333            for selection in selections {
10334                if let Some(buffer_id) = display_snapshot
10335                    .display_point_to_anchor(selection.head(), Bias::Right)
10336                    .buffer_id
10337                {
10338                    if toggled_buffers.insert(buffer_id) {
10339                        if self.buffer_folded(buffer_id, cx) {
10340                            self.unfold_buffer(buffer_id, cx);
10341                        } else {
10342                            self.fold_buffer(buffer_id, cx);
10343                        }
10344                    }
10345                }
10346                if let Some(buffer_id) = display_snapshot
10347                    .display_point_to_anchor(selection.tail(), Bias::Left)
10348                    .buffer_id
10349                {
10350                    if toggled_buffers.insert(buffer_id) {
10351                        if self.buffer_folded(buffer_id, cx) {
10352                            self.unfold_buffer(buffer_id, cx);
10353                        } else {
10354                            self.fold_buffer(buffer_id, cx);
10355                        }
10356                    }
10357                }
10358            }
10359        }
10360    }
10361
10362    pub fn toggle_fold_recursive(
10363        &mut self,
10364        _: &actions::ToggleFoldRecursive,
10365        cx: &mut ViewContext<Self>,
10366    ) {
10367        let selection = self.selections.newest::<Point>(cx);
10368
10369        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10370        let range = if selection.is_empty() {
10371            let point = selection.head().to_display_point(&display_map);
10372            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10373            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10374                .to_point(&display_map);
10375            start..end
10376        } else {
10377            selection.range()
10378        };
10379        if display_map.folds_in_range(range).next().is_some() {
10380            self.unfold_recursive(&Default::default(), cx)
10381        } else {
10382            self.fold_recursive(&Default::default(), cx)
10383        }
10384    }
10385
10386    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10387        if self.is_singleton(cx) {
10388            let mut to_fold = Vec::new();
10389            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10390            let selections = self.selections.all_adjusted(cx);
10391
10392            for selection in selections {
10393                let range = selection.range().sorted();
10394                let buffer_start_row = range.start.row;
10395
10396                if range.start.row != range.end.row {
10397                    let mut found = false;
10398                    let mut row = range.start.row;
10399                    while row <= range.end.row {
10400                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10401                        {
10402                            found = true;
10403                            row = crease.range().end.row + 1;
10404                            to_fold.push(crease);
10405                        } else {
10406                            row += 1
10407                        }
10408                    }
10409                    if found {
10410                        continue;
10411                    }
10412                }
10413
10414                for row in (0..=range.start.row).rev() {
10415                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10416                        if crease.range().end.row >= buffer_start_row {
10417                            to_fold.push(crease);
10418                            if row <= range.start.row {
10419                                break;
10420                            }
10421                        }
10422                    }
10423                }
10424            }
10425
10426            self.fold_creases(to_fold, true, cx);
10427        } else {
10428            let (display_snapshot, selections) = self.selections.all_adjusted_display(cx);
10429            let mut folded_buffers = HashSet::default();
10430            for selection in selections {
10431                if let Some(buffer_id) = display_snapshot
10432                    .display_point_to_anchor(selection.head(), Bias::Right)
10433                    .buffer_id
10434                {
10435                    if folded_buffers.insert(buffer_id) {
10436                        self.fold_buffer(buffer_id, cx);
10437                    }
10438                }
10439                if let Some(buffer_id) = display_snapshot
10440                    .display_point_to_anchor(selection.tail(), Bias::Left)
10441                    .buffer_id
10442                {
10443                    if folded_buffers.insert(buffer_id) {
10444                        self.fold_buffer(buffer_id, cx);
10445                    }
10446                }
10447            }
10448        }
10449    }
10450
10451    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10452        if !self.buffer.read(cx).is_singleton() {
10453            return;
10454        }
10455
10456        let fold_at_level = fold_at.level;
10457        let snapshot = self.buffer.read(cx).snapshot(cx);
10458        let mut to_fold = Vec::new();
10459        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10460
10461        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10462            while start_row < end_row {
10463                match self
10464                    .snapshot(cx)
10465                    .crease_for_buffer_row(MultiBufferRow(start_row))
10466                {
10467                    Some(crease) => {
10468                        let nested_start_row = crease.range().start.row + 1;
10469                        let nested_end_row = crease.range().end.row;
10470
10471                        if current_level < fold_at_level {
10472                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10473                        } else if current_level == fold_at_level {
10474                            to_fold.push(crease);
10475                        }
10476
10477                        start_row = nested_end_row + 1;
10478                    }
10479                    None => start_row += 1,
10480                }
10481            }
10482        }
10483
10484        self.fold_creases(to_fold, true, cx);
10485    }
10486
10487    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10488        if self.buffer.read(cx).is_singleton() {
10489            let mut fold_ranges = Vec::new();
10490            let snapshot = self.buffer.read(cx).snapshot(cx);
10491
10492            for row in 0..snapshot.max_row().0 {
10493                if let Some(foldable_range) =
10494                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10495                {
10496                    fold_ranges.push(foldable_range);
10497                }
10498            }
10499
10500            self.fold_creases(fold_ranges, true, cx);
10501        } else {
10502            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10503                editor
10504                    .update(&mut cx, |editor, cx| {
10505                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10506                            editor.fold_buffer(buffer_id, cx);
10507                        }
10508                    })
10509                    .ok();
10510            });
10511        }
10512    }
10513
10514    pub fn fold_function_bodies(
10515        &mut self,
10516        _: &actions::FoldFunctionBodies,
10517        cx: &mut ViewContext<Self>,
10518    ) {
10519        let snapshot = self.buffer.read(cx).snapshot(cx);
10520        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10521            return;
10522        };
10523        let creases = buffer
10524            .function_body_fold_ranges(0..buffer.len())
10525            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10526            .collect();
10527
10528        self.fold_creases(creases, true, cx);
10529    }
10530
10531    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10532        let mut to_fold = Vec::new();
10533        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10534        let selections = self.selections.all_adjusted(cx);
10535
10536        for selection in selections {
10537            let range = selection.range().sorted();
10538            let buffer_start_row = range.start.row;
10539
10540            if range.start.row != range.end.row {
10541                let mut found = false;
10542                for row in range.start.row..=range.end.row {
10543                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10544                        found = true;
10545                        to_fold.push(crease);
10546                    }
10547                }
10548                if found {
10549                    continue;
10550                }
10551            }
10552
10553            for row in (0..=range.start.row).rev() {
10554                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10555                    if crease.range().end.row >= buffer_start_row {
10556                        to_fold.push(crease);
10557                    } else {
10558                        break;
10559                    }
10560                }
10561            }
10562        }
10563
10564        self.fold_creases(to_fold, true, cx);
10565    }
10566
10567    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10568        let buffer_row = fold_at.buffer_row;
10569        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10570
10571        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10572            let autoscroll = self
10573                .selections
10574                .all::<Point>(cx)
10575                .iter()
10576                .any(|selection| crease.range().overlaps(&selection.range()));
10577
10578            self.fold_creases(vec![crease], autoscroll, cx);
10579        }
10580    }
10581
10582    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10583        if self.is_singleton(cx) {
10584            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10585            let buffer = &display_map.buffer_snapshot;
10586            let selections = self.selections.all::<Point>(cx);
10587            let ranges = selections
10588                .iter()
10589                .map(|s| {
10590                    let range = s.display_range(&display_map).sorted();
10591                    let mut start = range.start.to_point(&display_map);
10592                    let mut end = range.end.to_point(&display_map);
10593                    start.column = 0;
10594                    end.column = buffer.line_len(MultiBufferRow(end.row));
10595                    start..end
10596                })
10597                .collect::<Vec<_>>();
10598
10599            self.unfold_ranges(&ranges, true, true, cx);
10600        } else {
10601            let (display_snapshot, selections) = self.selections.all_adjusted_display(cx);
10602            let mut unfolded_buffers = HashSet::default();
10603            for selection in selections {
10604                if let Some(buffer_id) = display_snapshot
10605                    .display_point_to_anchor(selection.head(), Bias::Right)
10606                    .buffer_id
10607                {
10608                    if unfolded_buffers.insert(buffer_id) {
10609                        self.unfold_buffer(buffer_id, cx);
10610                    }
10611                }
10612                if let Some(buffer_id) = display_snapshot
10613                    .display_point_to_anchor(selection.tail(), Bias::Left)
10614                    .buffer_id
10615                {
10616                    if unfolded_buffers.insert(buffer_id) {
10617                        self.unfold_buffer(buffer_id, cx);
10618                    }
10619                }
10620            }
10621        }
10622    }
10623
10624    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10625        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10626        let selections = self.selections.all::<Point>(cx);
10627        let ranges = selections
10628            .iter()
10629            .map(|s| {
10630                let mut range = s.display_range(&display_map).sorted();
10631                *range.start.column_mut() = 0;
10632                *range.end.column_mut() = display_map.line_len(range.end.row());
10633                let start = range.start.to_point(&display_map);
10634                let end = range.end.to_point(&display_map);
10635                start..end
10636            })
10637            .collect::<Vec<_>>();
10638
10639        self.unfold_ranges(&ranges, true, true, cx);
10640    }
10641
10642    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10643        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10644
10645        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10646            ..Point::new(
10647                unfold_at.buffer_row.0,
10648                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10649            );
10650
10651        let autoscroll = self
10652            .selections
10653            .all::<Point>(cx)
10654            .iter()
10655            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10656
10657        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10658    }
10659
10660    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10661        if self.buffer.read(cx).is_singleton() {
10662            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10663            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10664        } else {
10665            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10666                editor
10667                    .update(&mut cx, |editor, cx| {
10668                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10669                            editor.unfold_buffer(buffer_id, cx);
10670                        }
10671                    })
10672                    .ok();
10673            });
10674        }
10675    }
10676
10677    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10678        let selections = self.selections.all::<Point>(cx);
10679        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10680        let line_mode = self.selections.line_mode;
10681        let ranges = selections
10682            .into_iter()
10683            .map(|s| {
10684                if line_mode {
10685                    let start = Point::new(s.start.row, 0);
10686                    let end = Point::new(
10687                        s.end.row,
10688                        display_map
10689                            .buffer_snapshot
10690                            .line_len(MultiBufferRow(s.end.row)),
10691                    );
10692                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10693                } else {
10694                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10695                }
10696            })
10697            .collect::<Vec<_>>();
10698        self.fold_creases(ranges, true, cx);
10699    }
10700
10701    pub fn fold_creases<T: ToOffset + Clone>(
10702        &mut self,
10703        creases: Vec<Crease<T>>,
10704        auto_scroll: bool,
10705        cx: &mut ViewContext<Self>,
10706    ) {
10707        if creases.is_empty() {
10708            return;
10709        }
10710
10711        let mut buffers_affected = HashSet::default();
10712        let multi_buffer = self.buffer().read(cx);
10713        for crease in &creases {
10714            if let Some((_, buffer, _)) =
10715                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10716            {
10717                buffers_affected.insert(buffer.read(cx).remote_id());
10718            };
10719        }
10720
10721        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10722
10723        if auto_scroll {
10724            self.request_autoscroll(Autoscroll::fit(), cx);
10725        }
10726
10727        for buffer_id in buffers_affected {
10728            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10729        }
10730
10731        cx.notify();
10732
10733        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10734            // Clear diagnostics block when folding a range that contains it.
10735            let snapshot = self.snapshot(cx);
10736            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10737                drop(snapshot);
10738                self.active_diagnostics = Some(active_diagnostics);
10739                self.dismiss_diagnostics(cx);
10740            } else {
10741                self.active_diagnostics = Some(active_diagnostics);
10742            }
10743        }
10744
10745        self.scrollbar_marker_state.dirty = true;
10746    }
10747
10748    /// Removes any folds whose ranges intersect any of the given ranges.
10749    pub fn unfold_ranges<T: ToOffset + Clone>(
10750        &mut self,
10751        ranges: &[Range<T>],
10752        inclusive: bool,
10753        auto_scroll: bool,
10754        cx: &mut ViewContext<Self>,
10755    ) {
10756        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10757            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10758        });
10759    }
10760
10761    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10762        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10763            return;
10764        }
10765        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10766            return;
10767        };
10768        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10769        self.display_map
10770            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10771        cx.emit(EditorEvent::BufferFoldToggled {
10772            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10773            folded: true,
10774        });
10775        cx.notify();
10776    }
10777
10778    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10779        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10780            return;
10781        }
10782        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10783            return;
10784        };
10785        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10786        self.display_map.update(cx, |display_map, cx| {
10787            display_map.unfold_buffer(buffer_id, cx);
10788        });
10789        cx.emit(EditorEvent::BufferFoldToggled {
10790            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10791            folded: false,
10792        });
10793        cx.notify();
10794    }
10795
10796    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10797        self.display_map.read(cx).buffer_folded(buffer)
10798    }
10799
10800    /// Removes any folds with the given ranges.
10801    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10802        &mut self,
10803        ranges: &[Range<T>],
10804        type_id: TypeId,
10805        auto_scroll: bool,
10806        cx: &mut ViewContext<Self>,
10807    ) {
10808        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10809            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10810        });
10811    }
10812
10813    fn remove_folds_with<T: ToOffset + Clone>(
10814        &mut self,
10815        ranges: &[Range<T>],
10816        auto_scroll: bool,
10817        cx: &mut ViewContext<Self>,
10818        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10819    ) {
10820        if ranges.is_empty() {
10821            return;
10822        }
10823
10824        let mut buffers_affected = HashSet::default();
10825        let multi_buffer = self.buffer().read(cx);
10826        for range in ranges {
10827            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10828                buffers_affected.insert(buffer.read(cx).remote_id());
10829            };
10830        }
10831
10832        self.display_map.update(cx, update);
10833
10834        if auto_scroll {
10835            self.request_autoscroll(Autoscroll::fit(), cx);
10836        }
10837
10838        for buffer_id in buffers_affected {
10839            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10840        }
10841
10842        cx.notify();
10843        self.scrollbar_marker_state.dirty = true;
10844        self.active_indent_guides_state.dirty = true;
10845    }
10846
10847    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10848        self.display_map.read(cx).fold_placeholder.clone()
10849    }
10850
10851    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10852        if hovered != self.gutter_hovered {
10853            self.gutter_hovered = hovered;
10854            cx.notify();
10855        }
10856    }
10857
10858    pub fn insert_blocks(
10859        &mut self,
10860        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10861        autoscroll: Option<Autoscroll>,
10862        cx: &mut ViewContext<Self>,
10863    ) -> Vec<CustomBlockId> {
10864        let blocks = self
10865            .display_map
10866            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10867        if let Some(autoscroll) = autoscroll {
10868            self.request_autoscroll(autoscroll, cx);
10869        }
10870        cx.notify();
10871        blocks
10872    }
10873
10874    pub fn resize_blocks(
10875        &mut self,
10876        heights: HashMap<CustomBlockId, u32>,
10877        autoscroll: Option<Autoscroll>,
10878        cx: &mut ViewContext<Self>,
10879    ) {
10880        self.display_map
10881            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10882        if let Some(autoscroll) = autoscroll {
10883            self.request_autoscroll(autoscroll, cx);
10884        }
10885        cx.notify();
10886    }
10887
10888    pub fn replace_blocks(
10889        &mut self,
10890        renderers: HashMap<CustomBlockId, RenderBlock>,
10891        autoscroll: Option<Autoscroll>,
10892        cx: &mut ViewContext<Self>,
10893    ) {
10894        self.display_map
10895            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10896        if let Some(autoscroll) = autoscroll {
10897            self.request_autoscroll(autoscroll, cx);
10898        }
10899        cx.notify();
10900    }
10901
10902    pub fn remove_blocks(
10903        &mut self,
10904        block_ids: HashSet<CustomBlockId>,
10905        autoscroll: Option<Autoscroll>,
10906        cx: &mut ViewContext<Self>,
10907    ) {
10908        self.display_map.update(cx, |display_map, cx| {
10909            display_map.remove_blocks(block_ids, cx)
10910        });
10911        if let Some(autoscroll) = autoscroll {
10912            self.request_autoscroll(autoscroll, cx);
10913        }
10914        cx.notify();
10915    }
10916
10917    pub fn row_for_block(
10918        &self,
10919        block_id: CustomBlockId,
10920        cx: &mut ViewContext<Self>,
10921    ) -> Option<DisplayRow> {
10922        self.display_map
10923            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10924    }
10925
10926    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10927        self.focused_block = Some(focused_block);
10928    }
10929
10930    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10931        self.focused_block.take()
10932    }
10933
10934    pub fn insert_creases(
10935        &mut self,
10936        creases: impl IntoIterator<Item = Crease<Anchor>>,
10937        cx: &mut ViewContext<Self>,
10938    ) -> Vec<CreaseId> {
10939        self.display_map
10940            .update(cx, |map, cx| map.insert_creases(creases, cx))
10941    }
10942
10943    pub fn remove_creases(
10944        &mut self,
10945        ids: impl IntoIterator<Item = CreaseId>,
10946        cx: &mut ViewContext<Self>,
10947    ) {
10948        self.display_map
10949            .update(cx, |map, cx| map.remove_creases(ids, cx));
10950    }
10951
10952    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10953        self.display_map
10954            .update(cx, |map, cx| map.snapshot(cx))
10955            .longest_row()
10956    }
10957
10958    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10959        self.display_map
10960            .update(cx, |map, cx| map.snapshot(cx))
10961            .max_point()
10962    }
10963
10964    pub fn text(&self, cx: &AppContext) -> String {
10965        self.buffer.read(cx).read(cx).text()
10966    }
10967
10968    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10969        let text = self.text(cx);
10970        let text = text.trim();
10971
10972        if text.is_empty() {
10973            return None;
10974        }
10975
10976        Some(text.to_string())
10977    }
10978
10979    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10980        self.transact(cx, |this, cx| {
10981            this.buffer
10982                .read(cx)
10983                .as_singleton()
10984                .expect("you can only call set_text on editors for singleton buffers")
10985                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10986        });
10987    }
10988
10989    pub fn display_text(&self, cx: &mut AppContext) -> String {
10990        self.display_map
10991            .update(cx, |map, cx| map.snapshot(cx))
10992            .text()
10993    }
10994
10995    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10996        let mut wrap_guides = smallvec::smallvec![];
10997
10998        if self.show_wrap_guides == Some(false) {
10999            return wrap_guides;
11000        }
11001
11002        let settings = self.buffer.read(cx).settings_at(0, cx);
11003        if settings.show_wrap_guides {
11004            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11005                wrap_guides.push((soft_wrap as usize, true));
11006            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11007                wrap_guides.push((soft_wrap as usize, true));
11008            }
11009            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11010        }
11011
11012        wrap_guides
11013    }
11014
11015    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11016        let settings = self.buffer.read(cx).settings_at(0, cx);
11017        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11018        match mode {
11019            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11020                SoftWrap::None
11021            }
11022            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11023            language_settings::SoftWrap::PreferredLineLength => {
11024                SoftWrap::Column(settings.preferred_line_length)
11025            }
11026            language_settings::SoftWrap::Bounded => {
11027                SoftWrap::Bounded(settings.preferred_line_length)
11028            }
11029        }
11030    }
11031
11032    pub fn set_soft_wrap_mode(
11033        &mut self,
11034        mode: language_settings::SoftWrap,
11035        cx: &mut ViewContext<Self>,
11036    ) {
11037        self.soft_wrap_mode_override = Some(mode);
11038        cx.notify();
11039    }
11040
11041    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11042        self.text_style_refinement = Some(style);
11043    }
11044
11045    /// called by the Element so we know what style we were most recently rendered with.
11046    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11047        let rem_size = cx.rem_size();
11048        self.display_map.update(cx, |map, cx| {
11049            map.set_font(
11050                style.text.font(),
11051                style.text.font_size.to_pixels(rem_size),
11052                cx,
11053            )
11054        });
11055        self.style = Some(style);
11056    }
11057
11058    pub fn style(&self) -> Option<&EditorStyle> {
11059        self.style.as_ref()
11060    }
11061
11062    // Called by the element. This method is not designed to be called outside of the editor
11063    // element's layout code because it does not notify when rewrapping is computed synchronously.
11064    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11065        self.display_map
11066            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11067    }
11068
11069    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11070        if self.soft_wrap_mode_override.is_some() {
11071            self.soft_wrap_mode_override.take();
11072        } else {
11073            let soft_wrap = match self.soft_wrap_mode(cx) {
11074                SoftWrap::GitDiff => return,
11075                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11076                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11077                    language_settings::SoftWrap::None
11078                }
11079            };
11080            self.soft_wrap_mode_override = Some(soft_wrap);
11081        }
11082        cx.notify();
11083    }
11084
11085    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11086        let Some(workspace) = self.workspace() else {
11087            return;
11088        };
11089        let fs = workspace.read(cx).app_state().fs.clone();
11090        let current_show = TabBarSettings::get_global(cx).show;
11091        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11092            setting.show = Some(!current_show);
11093        });
11094    }
11095
11096    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11097        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11098            self.buffer
11099                .read(cx)
11100                .settings_at(0, cx)
11101                .indent_guides
11102                .enabled
11103        });
11104        self.show_indent_guides = Some(!currently_enabled);
11105        cx.notify();
11106    }
11107
11108    fn should_show_indent_guides(&self) -> Option<bool> {
11109        self.show_indent_guides
11110    }
11111
11112    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11113        let mut editor_settings = EditorSettings::get_global(cx).clone();
11114        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11115        EditorSettings::override_global(editor_settings, cx);
11116    }
11117
11118    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11119        self.use_relative_line_numbers
11120            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11121    }
11122
11123    pub fn toggle_relative_line_numbers(
11124        &mut self,
11125        _: &ToggleRelativeLineNumbers,
11126        cx: &mut ViewContext<Self>,
11127    ) {
11128        let is_relative = self.should_use_relative_line_numbers(cx);
11129        self.set_relative_line_number(Some(!is_relative), cx)
11130    }
11131
11132    pub fn set_relative_line_number(
11133        &mut self,
11134        is_relative: Option<bool>,
11135        cx: &mut ViewContext<Self>,
11136    ) {
11137        self.use_relative_line_numbers = is_relative;
11138        cx.notify();
11139    }
11140
11141    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11142        self.show_gutter = show_gutter;
11143        cx.notify();
11144    }
11145
11146    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11147        self.show_line_numbers = Some(show_line_numbers);
11148        cx.notify();
11149    }
11150
11151    pub fn set_show_git_diff_gutter(
11152        &mut self,
11153        show_git_diff_gutter: bool,
11154        cx: &mut ViewContext<Self>,
11155    ) {
11156        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11157        cx.notify();
11158    }
11159
11160    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11161        self.show_code_actions = Some(show_code_actions);
11162        cx.notify();
11163    }
11164
11165    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11166        self.show_runnables = Some(show_runnables);
11167        cx.notify();
11168    }
11169
11170    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11171        if self.display_map.read(cx).masked != masked {
11172            self.display_map.update(cx, |map, _| map.masked = masked);
11173        }
11174        cx.notify()
11175    }
11176
11177    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11178        self.show_wrap_guides = Some(show_wrap_guides);
11179        cx.notify();
11180    }
11181
11182    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11183        self.show_indent_guides = Some(show_indent_guides);
11184        cx.notify();
11185    }
11186
11187    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11188        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11189            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11190                if let Some(dir) = file.abs_path(cx).parent() {
11191                    return Some(dir.to_owned());
11192                }
11193            }
11194
11195            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11196                return Some(project_path.path.to_path_buf());
11197            }
11198        }
11199
11200        None
11201    }
11202
11203    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11204        self.active_excerpt(cx)?
11205            .1
11206            .read(cx)
11207            .file()
11208            .and_then(|f| f.as_local())
11209    }
11210
11211    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11212        if let Some(target) = self.target_file(cx) {
11213            cx.reveal_path(&target.abs_path(cx));
11214        }
11215    }
11216
11217    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11218        if let Some(file) = self.target_file(cx) {
11219            if let Some(path) = file.abs_path(cx).to_str() {
11220                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11221            }
11222        }
11223    }
11224
11225    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11226        if let Some(file) = self.target_file(cx) {
11227            if let Some(path) = file.path().to_str() {
11228                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11229            }
11230        }
11231    }
11232
11233    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11234        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11235
11236        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11237            self.start_git_blame(true, cx);
11238        }
11239
11240        cx.notify();
11241    }
11242
11243    pub fn toggle_git_blame_inline(
11244        &mut self,
11245        _: &ToggleGitBlameInline,
11246        cx: &mut ViewContext<Self>,
11247    ) {
11248        self.toggle_git_blame_inline_internal(true, cx);
11249        cx.notify();
11250    }
11251
11252    pub fn git_blame_inline_enabled(&self) -> bool {
11253        self.git_blame_inline_enabled
11254    }
11255
11256    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11257        self.show_selection_menu = self
11258            .show_selection_menu
11259            .map(|show_selections_menu| !show_selections_menu)
11260            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11261
11262        cx.notify();
11263    }
11264
11265    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11266        self.show_selection_menu
11267            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11268    }
11269
11270    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11271        if let Some(project) = self.project.as_ref() {
11272            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11273                return;
11274            };
11275
11276            if buffer.read(cx).file().is_none() {
11277                return;
11278            }
11279
11280            let focused = self.focus_handle(cx).contains_focused(cx);
11281
11282            let project = project.clone();
11283            let blame =
11284                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11285            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11286            self.blame = Some(blame);
11287        }
11288    }
11289
11290    fn toggle_git_blame_inline_internal(
11291        &mut self,
11292        user_triggered: bool,
11293        cx: &mut ViewContext<Self>,
11294    ) {
11295        if self.git_blame_inline_enabled {
11296            self.git_blame_inline_enabled = false;
11297            self.show_git_blame_inline = false;
11298            self.show_git_blame_inline_delay_task.take();
11299        } else {
11300            self.git_blame_inline_enabled = true;
11301            self.start_git_blame_inline(user_triggered, cx);
11302        }
11303
11304        cx.notify();
11305    }
11306
11307    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11308        self.start_git_blame(user_triggered, cx);
11309
11310        if ProjectSettings::get_global(cx)
11311            .git
11312            .inline_blame_delay()
11313            .is_some()
11314        {
11315            self.start_inline_blame_timer(cx);
11316        } else {
11317            self.show_git_blame_inline = true
11318        }
11319    }
11320
11321    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11322        self.blame.as_ref()
11323    }
11324
11325    pub fn show_git_blame_gutter(&self) -> bool {
11326        self.show_git_blame_gutter
11327    }
11328
11329    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11330        self.show_git_blame_gutter && self.has_blame_entries(cx)
11331    }
11332
11333    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11334        self.show_git_blame_inline
11335            && self.focus_handle.is_focused(cx)
11336            && !self.newest_selection_head_on_empty_line(cx)
11337            && self.has_blame_entries(cx)
11338    }
11339
11340    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11341        self.blame()
11342            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11343    }
11344
11345    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11346        let cursor_anchor = self.selections.newest_anchor().head();
11347
11348        let snapshot = self.buffer.read(cx).snapshot(cx);
11349        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11350
11351        snapshot.line_len(buffer_row) == 0
11352    }
11353
11354    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11355        let buffer_and_selection = maybe!({
11356            let selection = self.selections.newest::<Point>(cx);
11357            let selection_range = selection.range();
11358
11359            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11360                (buffer, selection_range.start.row..selection_range.end.row)
11361            } else {
11362                let buffer_ranges = self
11363                    .buffer()
11364                    .read(cx)
11365                    .range_to_buffer_ranges(selection_range, cx);
11366
11367                let (buffer, range, _) = if selection.reversed {
11368                    buffer_ranges.first()
11369                } else {
11370                    buffer_ranges.last()
11371                }?;
11372
11373                let snapshot = buffer.read(cx).snapshot();
11374                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11375                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11376                (buffer.clone(), selection)
11377            };
11378
11379            Some((buffer, selection))
11380        });
11381
11382        let Some((buffer, selection)) = buffer_and_selection else {
11383            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11384        };
11385
11386        let Some(project) = self.project.as_ref() else {
11387            return Task::ready(Err(anyhow!("editor does not have project")));
11388        };
11389
11390        project.update(cx, |project, cx| {
11391            project.get_permalink_to_line(&buffer, selection, cx)
11392        })
11393    }
11394
11395    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11396        let permalink_task = self.get_permalink_to_line(cx);
11397        let workspace = self.workspace();
11398
11399        cx.spawn(|_, mut cx| async move {
11400            match permalink_task.await {
11401                Ok(permalink) => {
11402                    cx.update(|cx| {
11403                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11404                    })
11405                    .ok();
11406                }
11407                Err(err) => {
11408                    let message = format!("Failed to copy permalink: {err}");
11409
11410                    Err::<(), anyhow::Error>(err).log_err();
11411
11412                    if let Some(workspace) = workspace {
11413                        workspace
11414                            .update(&mut cx, |workspace, cx| {
11415                                struct CopyPermalinkToLine;
11416
11417                                workspace.show_toast(
11418                                    Toast::new(
11419                                        NotificationId::unique::<CopyPermalinkToLine>(),
11420                                        message,
11421                                    ),
11422                                    cx,
11423                                )
11424                            })
11425                            .ok();
11426                    }
11427                }
11428            }
11429        })
11430        .detach();
11431    }
11432
11433    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11434        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11435        if let Some(file) = self.target_file(cx) {
11436            if let Some(path) = file.path().to_str() {
11437                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11438            }
11439        }
11440    }
11441
11442    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11443        let permalink_task = self.get_permalink_to_line(cx);
11444        let workspace = self.workspace();
11445
11446        cx.spawn(|_, mut cx| async move {
11447            match permalink_task.await {
11448                Ok(permalink) => {
11449                    cx.update(|cx| {
11450                        cx.open_url(permalink.as_ref());
11451                    })
11452                    .ok();
11453                }
11454                Err(err) => {
11455                    let message = format!("Failed to open permalink: {err}");
11456
11457                    Err::<(), anyhow::Error>(err).log_err();
11458
11459                    if let Some(workspace) = workspace {
11460                        workspace
11461                            .update(&mut cx, |workspace, cx| {
11462                                struct OpenPermalinkToLine;
11463
11464                                workspace.show_toast(
11465                                    Toast::new(
11466                                        NotificationId::unique::<OpenPermalinkToLine>(),
11467                                        message,
11468                                    ),
11469                                    cx,
11470                                )
11471                            })
11472                            .ok();
11473                    }
11474                }
11475            }
11476        })
11477        .detach();
11478    }
11479
11480    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11481        self.insert_uuid(UuidVersion::V4, cx);
11482    }
11483
11484    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11485        self.insert_uuid(UuidVersion::V7, cx);
11486    }
11487
11488    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11489        self.transact(cx, |this, cx| {
11490            let edits = this
11491                .selections
11492                .all::<Point>(cx)
11493                .into_iter()
11494                .map(|selection| {
11495                    let uuid = match version {
11496                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11497                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11498                    };
11499
11500                    (selection.range(), uuid.to_string())
11501                });
11502            this.edit(edits, cx);
11503            this.refresh_inline_completion(true, false, cx);
11504        });
11505    }
11506
11507    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11508    /// last highlight added will be used.
11509    ///
11510    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11511    pub fn highlight_rows<T: 'static>(
11512        &mut self,
11513        range: Range<Anchor>,
11514        color: Hsla,
11515        should_autoscroll: bool,
11516        cx: &mut ViewContext<Self>,
11517    ) {
11518        let snapshot = self.buffer().read(cx).snapshot(cx);
11519        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11520        let ix = row_highlights.binary_search_by(|highlight| {
11521            Ordering::Equal
11522                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11523                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11524        });
11525
11526        if let Err(mut ix) = ix {
11527            let index = post_inc(&mut self.highlight_order);
11528
11529            // If this range intersects with the preceding highlight, then merge it with
11530            // the preceding highlight. Otherwise insert a new highlight.
11531            let mut merged = false;
11532            if ix > 0 {
11533                let prev_highlight = &mut row_highlights[ix - 1];
11534                if prev_highlight
11535                    .range
11536                    .end
11537                    .cmp(&range.start, &snapshot)
11538                    .is_ge()
11539                {
11540                    ix -= 1;
11541                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11542                        prev_highlight.range.end = range.end;
11543                    }
11544                    merged = true;
11545                    prev_highlight.index = index;
11546                    prev_highlight.color = color;
11547                    prev_highlight.should_autoscroll = should_autoscroll;
11548                }
11549            }
11550
11551            if !merged {
11552                row_highlights.insert(
11553                    ix,
11554                    RowHighlight {
11555                        range: range.clone(),
11556                        index,
11557                        color,
11558                        should_autoscroll,
11559                    },
11560                );
11561            }
11562
11563            // If any of the following highlights intersect with this one, merge them.
11564            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11565                let highlight = &row_highlights[ix];
11566                if next_highlight
11567                    .range
11568                    .start
11569                    .cmp(&highlight.range.end, &snapshot)
11570                    .is_le()
11571                {
11572                    if next_highlight
11573                        .range
11574                        .end
11575                        .cmp(&highlight.range.end, &snapshot)
11576                        .is_gt()
11577                    {
11578                        row_highlights[ix].range.end = next_highlight.range.end;
11579                    }
11580                    row_highlights.remove(ix + 1);
11581                } else {
11582                    break;
11583                }
11584            }
11585        }
11586    }
11587
11588    /// Remove any highlighted row ranges of the given type that intersect the
11589    /// given ranges.
11590    pub fn remove_highlighted_rows<T: 'static>(
11591        &mut self,
11592        ranges_to_remove: Vec<Range<Anchor>>,
11593        cx: &mut ViewContext<Self>,
11594    ) {
11595        let snapshot = self.buffer().read(cx).snapshot(cx);
11596        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11597        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11598        row_highlights.retain(|highlight| {
11599            while let Some(range_to_remove) = ranges_to_remove.peek() {
11600                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11601                    Ordering::Less | Ordering::Equal => {
11602                        ranges_to_remove.next();
11603                    }
11604                    Ordering::Greater => {
11605                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11606                            Ordering::Less | Ordering::Equal => {
11607                                return false;
11608                            }
11609                            Ordering::Greater => break,
11610                        }
11611                    }
11612                }
11613            }
11614
11615            true
11616        })
11617    }
11618
11619    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11620    pub fn clear_row_highlights<T: 'static>(&mut self) {
11621        self.highlighted_rows.remove(&TypeId::of::<T>());
11622    }
11623
11624    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11625    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11626        self.highlighted_rows
11627            .get(&TypeId::of::<T>())
11628            .map_or(&[] as &[_], |vec| vec.as_slice())
11629            .iter()
11630            .map(|highlight| (highlight.range.clone(), highlight.color))
11631    }
11632
11633    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11634    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11635    /// Allows to ignore certain kinds of highlights.
11636    pub fn highlighted_display_rows(
11637        &mut self,
11638        cx: &mut WindowContext,
11639    ) -> BTreeMap<DisplayRow, Hsla> {
11640        let snapshot = self.snapshot(cx);
11641        let mut used_highlight_orders = HashMap::default();
11642        self.highlighted_rows
11643            .iter()
11644            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11645            .fold(
11646                BTreeMap::<DisplayRow, Hsla>::new(),
11647                |mut unique_rows, highlight| {
11648                    let start = highlight.range.start.to_display_point(&snapshot);
11649                    let end = highlight.range.end.to_display_point(&snapshot);
11650                    let start_row = start.row().0;
11651                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11652                        && end.column() == 0
11653                    {
11654                        end.row().0.saturating_sub(1)
11655                    } else {
11656                        end.row().0
11657                    };
11658                    for row in start_row..=end_row {
11659                        let used_index =
11660                            used_highlight_orders.entry(row).or_insert(highlight.index);
11661                        if highlight.index >= *used_index {
11662                            *used_index = highlight.index;
11663                            unique_rows.insert(DisplayRow(row), highlight.color);
11664                        }
11665                    }
11666                    unique_rows
11667                },
11668            )
11669    }
11670
11671    pub fn highlighted_display_row_for_autoscroll(
11672        &self,
11673        snapshot: &DisplaySnapshot,
11674    ) -> Option<DisplayRow> {
11675        self.highlighted_rows
11676            .values()
11677            .flat_map(|highlighted_rows| highlighted_rows.iter())
11678            .filter_map(|highlight| {
11679                if highlight.should_autoscroll {
11680                    Some(highlight.range.start.to_display_point(snapshot).row())
11681                } else {
11682                    None
11683                }
11684            })
11685            .min()
11686    }
11687
11688    pub fn set_search_within_ranges(
11689        &mut self,
11690        ranges: &[Range<Anchor>],
11691        cx: &mut ViewContext<Self>,
11692    ) {
11693        self.highlight_background::<SearchWithinRange>(
11694            ranges,
11695            |colors| colors.editor_document_highlight_read_background,
11696            cx,
11697        )
11698    }
11699
11700    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11701        self.breadcrumb_header = Some(new_header);
11702    }
11703
11704    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11705        self.clear_background_highlights::<SearchWithinRange>(cx);
11706    }
11707
11708    pub fn highlight_background<T: 'static>(
11709        &mut self,
11710        ranges: &[Range<Anchor>],
11711        color_fetcher: fn(&ThemeColors) -> Hsla,
11712        cx: &mut ViewContext<Self>,
11713    ) {
11714        self.background_highlights
11715            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11716        self.scrollbar_marker_state.dirty = true;
11717        cx.notify();
11718    }
11719
11720    pub fn clear_background_highlights<T: 'static>(
11721        &mut self,
11722        cx: &mut ViewContext<Self>,
11723    ) -> Option<BackgroundHighlight> {
11724        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11725        if !text_highlights.1.is_empty() {
11726            self.scrollbar_marker_state.dirty = true;
11727            cx.notify();
11728        }
11729        Some(text_highlights)
11730    }
11731
11732    pub fn highlight_gutter<T: 'static>(
11733        &mut self,
11734        ranges: &[Range<Anchor>],
11735        color_fetcher: fn(&AppContext) -> Hsla,
11736        cx: &mut ViewContext<Self>,
11737    ) {
11738        self.gutter_highlights
11739            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11740        cx.notify();
11741    }
11742
11743    pub fn clear_gutter_highlights<T: 'static>(
11744        &mut self,
11745        cx: &mut ViewContext<Self>,
11746    ) -> Option<GutterHighlight> {
11747        cx.notify();
11748        self.gutter_highlights.remove(&TypeId::of::<T>())
11749    }
11750
11751    #[cfg(feature = "test-support")]
11752    pub fn all_text_background_highlights(
11753        &mut self,
11754        cx: &mut ViewContext<Self>,
11755    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11756        let snapshot = self.snapshot(cx);
11757        let buffer = &snapshot.buffer_snapshot;
11758        let start = buffer.anchor_before(0);
11759        let end = buffer.anchor_after(buffer.len());
11760        let theme = cx.theme().colors();
11761        self.background_highlights_in_range(start..end, &snapshot, theme)
11762    }
11763
11764    #[cfg(feature = "test-support")]
11765    pub fn search_background_highlights(
11766        &mut self,
11767        cx: &mut ViewContext<Self>,
11768    ) -> Vec<Range<Point>> {
11769        let snapshot = self.buffer().read(cx).snapshot(cx);
11770
11771        let highlights = self
11772            .background_highlights
11773            .get(&TypeId::of::<items::BufferSearchHighlights>());
11774
11775        if let Some((_color, ranges)) = highlights {
11776            ranges
11777                .iter()
11778                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11779                .collect_vec()
11780        } else {
11781            vec![]
11782        }
11783    }
11784
11785    fn document_highlights_for_position<'a>(
11786        &'a self,
11787        position: Anchor,
11788        buffer: &'a MultiBufferSnapshot,
11789    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11790        let read_highlights = self
11791            .background_highlights
11792            .get(&TypeId::of::<DocumentHighlightRead>())
11793            .map(|h| &h.1);
11794        let write_highlights = self
11795            .background_highlights
11796            .get(&TypeId::of::<DocumentHighlightWrite>())
11797            .map(|h| &h.1);
11798        let left_position = position.bias_left(buffer);
11799        let right_position = position.bias_right(buffer);
11800        read_highlights
11801            .into_iter()
11802            .chain(write_highlights)
11803            .flat_map(move |ranges| {
11804                let start_ix = match ranges.binary_search_by(|probe| {
11805                    let cmp = probe.end.cmp(&left_position, buffer);
11806                    if cmp.is_ge() {
11807                        Ordering::Greater
11808                    } else {
11809                        Ordering::Less
11810                    }
11811                }) {
11812                    Ok(i) | Err(i) => i,
11813                };
11814
11815                ranges[start_ix..]
11816                    .iter()
11817                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11818            })
11819    }
11820
11821    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11822        self.background_highlights
11823            .get(&TypeId::of::<T>())
11824            .map_or(false, |(_, highlights)| !highlights.is_empty())
11825    }
11826
11827    pub fn background_highlights_in_range(
11828        &self,
11829        search_range: Range<Anchor>,
11830        display_snapshot: &DisplaySnapshot,
11831        theme: &ThemeColors,
11832    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11833        let mut results = Vec::new();
11834        for (color_fetcher, ranges) in self.background_highlights.values() {
11835            let color = color_fetcher(theme);
11836            let start_ix = match ranges.binary_search_by(|probe| {
11837                let cmp = probe
11838                    .end
11839                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11840                if cmp.is_gt() {
11841                    Ordering::Greater
11842                } else {
11843                    Ordering::Less
11844                }
11845            }) {
11846                Ok(i) | Err(i) => i,
11847            };
11848            for range in &ranges[start_ix..] {
11849                if range
11850                    .start
11851                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11852                    .is_ge()
11853                {
11854                    break;
11855                }
11856
11857                let start = range.start.to_display_point(display_snapshot);
11858                let end = range.end.to_display_point(display_snapshot);
11859                results.push((start..end, color))
11860            }
11861        }
11862        results
11863    }
11864
11865    pub fn background_highlight_row_ranges<T: 'static>(
11866        &self,
11867        search_range: Range<Anchor>,
11868        display_snapshot: &DisplaySnapshot,
11869        count: usize,
11870    ) -> Vec<RangeInclusive<DisplayPoint>> {
11871        let mut results = Vec::new();
11872        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11873            return vec![];
11874        };
11875
11876        let start_ix = match ranges.binary_search_by(|probe| {
11877            let cmp = probe
11878                .end
11879                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11880            if cmp.is_gt() {
11881                Ordering::Greater
11882            } else {
11883                Ordering::Less
11884            }
11885        }) {
11886            Ok(i) | Err(i) => i,
11887        };
11888        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11889            if let (Some(start_display), Some(end_display)) = (start, end) {
11890                results.push(
11891                    start_display.to_display_point(display_snapshot)
11892                        ..=end_display.to_display_point(display_snapshot),
11893                );
11894            }
11895        };
11896        let mut start_row: Option<Point> = None;
11897        let mut end_row: Option<Point> = None;
11898        if ranges.len() > count {
11899            return Vec::new();
11900        }
11901        for range in &ranges[start_ix..] {
11902            if range
11903                .start
11904                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11905                .is_ge()
11906            {
11907                break;
11908            }
11909            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11910            if let Some(current_row) = &end_row {
11911                if end.row == current_row.row {
11912                    continue;
11913                }
11914            }
11915            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11916            if start_row.is_none() {
11917                assert_eq!(end_row, None);
11918                start_row = Some(start);
11919                end_row = Some(end);
11920                continue;
11921            }
11922            if let Some(current_end) = end_row.as_mut() {
11923                if start.row > current_end.row + 1 {
11924                    push_region(start_row, end_row);
11925                    start_row = Some(start);
11926                    end_row = Some(end);
11927                } else {
11928                    // Merge two hunks.
11929                    *current_end = end;
11930                }
11931            } else {
11932                unreachable!();
11933            }
11934        }
11935        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11936        push_region(start_row, end_row);
11937        results
11938    }
11939
11940    pub fn gutter_highlights_in_range(
11941        &self,
11942        search_range: Range<Anchor>,
11943        display_snapshot: &DisplaySnapshot,
11944        cx: &AppContext,
11945    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11946        let mut results = Vec::new();
11947        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11948            let color = color_fetcher(cx);
11949            let start_ix = match ranges.binary_search_by(|probe| {
11950                let cmp = probe
11951                    .end
11952                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11953                if cmp.is_gt() {
11954                    Ordering::Greater
11955                } else {
11956                    Ordering::Less
11957                }
11958            }) {
11959                Ok(i) | Err(i) => i,
11960            };
11961            for range in &ranges[start_ix..] {
11962                if range
11963                    .start
11964                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11965                    .is_ge()
11966                {
11967                    break;
11968                }
11969
11970                let start = range.start.to_display_point(display_snapshot);
11971                let end = range.end.to_display_point(display_snapshot);
11972                results.push((start..end, color))
11973            }
11974        }
11975        results
11976    }
11977
11978    /// Get the text ranges corresponding to the redaction query
11979    pub fn redacted_ranges(
11980        &self,
11981        search_range: Range<Anchor>,
11982        display_snapshot: &DisplaySnapshot,
11983        cx: &WindowContext,
11984    ) -> Vec<Range<DisplayPoint>> {
11985        display_snapshot
11986            .buffer_snapshot
11987            .redacted_ranges(search_range, |file| {
11988                if let Some(file) = file {
11989                    file.is_private()
11990                        && EditorSettings::get(
11991                            Some(SettingsLocation {
11992                                worktree_id: file.worktree_id(cx),
11993                                path: file.path().as_ref(),
11994                            }),
11995                            cx,
11996                        )
11997                        .redact_private_values
11998                } else {
11999                    false
12000                }
12001            })
12002            .map(|range| {
12003                range.start.to_display_point(display_snapshot)
12004                    ..range.end.to_display_point(display_snapshot)
12005            })
12006            .collect()
12007    }
12008
12009    pub fn highlight_text<T: 'static>(
12010        &mut self,
12011        ranges: Vec<Range<Anchor>>,
12012        style: HighlightStyle,
12013        cx: &mut ViewContext<Self>,
12014    ) {
12015        self.display_map.update(cx, |map, _| {
12016            map.highlight_text(TypeId::of::<T>(), ranges, style)
12017        });
12018        cx.notify();
12019    }
12020
12021    pub(crate) fn highlight_inlays<T: 'static>(
12022        &mut self,
12023        highlights: Vec<InlayHighlight>,
12024        style: HighlightStyle,
12025        cx: &mut ViewContext<Self>,
12026    ) {
12027        self.display_map.update(cx, |map, _| {
12028            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12029        });
12030        cx.notify();
12031    }
12032
12033    pub fn text_highlights<'a, T: 'static>(
12034        &'a self,
12035        cx: &'a AppContext,
12036    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12037        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12038    }
12039
12040    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12041        let cleared = self
12042            .display_map
12043            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12044        if cleared {
12045            cx.notify();
12046        }
12047    }
12048
12049    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12050        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12051            && self.focus_handle.is_focused(cx)
12052    }
12053
12054    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12055        self.show_cursor_when_unfocused = is_enabled;
12056        cx.notify();
12057    }
12058
12059    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12060        self.project
12061            .as_ref()
12062            .map(|project| project.read(cx).lsp_store())
12063    }
12064
12065    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12066        cx.notify();
12067    }
12068
12069    fn on_buffer_event(
12070        &mut self,
12071        multibuffer: Model<MultiBuffer>,
12072        event: &multi_buffer::Event,
12073        cx: &mut ViewContext<Self>,
12074    ) {
12075        match event {
12076            multi_buffer::Event::Edited {
12077                singleton_buffer_edited,
12078                edited_buffer: buffer_edited,
12079            } => {
12080                self.scrollbar_marker_state.dirty = true;
12081                self.active_indent_guides_state.dirty = true;
12082                self.refresh_active_diagnostics(cx);
12083                self.refresh_code_actions(cx);
12084                if self.has_active_inline_completion() {
12085                    self.update_visible_inline_completion(cx);
12086                }
12087                if let Some(buffer) = buffer_edited {
12088                    let buffer_id = buffer.read(cx).remote_id();
12089                    if !self.registered_buffers.contains_key(&buffer_id) {
12090                        if let Some(lsp_store) = self.lsp_store(cx) {
12091                            lsp_store.update(cx, |lsp_store, cx| {
12092                                self.registered_buffers.insert(
12093                                    buffer_id,
12094                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12095                                );
12096                            })
12097                        }
12098                    }
12099                }
12100                cx.emit(EditorEvent::BufferEdited);
12101                cx.emit(SearchEvent::MatchesInvalidated);
12102                if *singleton_buffer_edited {
12103                    if let Some(project) = &self.project {
12104                        let project = project.read(cx);
12105                        #[allow(clippy::mutable_key_type)]
12106                        let languages_affected = multibuffer
12107                            .read(cx)
12108                            .all_buffers()
12109                            .into_iter()
12110                            .filter_map(|buffer| {
12111                                let buffer = buffer.read(cx);
12112                                let language = buffer.language()?;
12113                                if project.is_local()
12114                                    && project
12115                                        .language_servers_for_local_buffer(buffer, cx)
12116                                        .count()
12117                                        == 0
12118                                {
12119                                    None
12120                                } else {
12121                                    Some(language)
12122                                }
12123                            })
12124                            .cloned()
12125                            .collect::<HashSet<_>>();
12126                        if !languages_affected.is_empty() {
12127                            self.refresh_inlay_hints(
12128                                InlayHintRefreshReason::BufferEdited(languages_affected),
12129                                cx,
12130                            );
12131                        }
12132                    }
12133                }
12134
12135                let Some(project) = &self.project else { return };
12136                let (telemetry, is_via_ssh) = {
12137                    let project = project.read(cx);
12138                    let telemetry = project.client().telemetry().clone();
12139                    let is_via_ssh = project.is_via_ssh();
12140                    (telemetry, is_via_ssh)
12141                };
12142                refresh_linked_ranges(self, cx);
12143                telemetry.log_edit_event("editor", is_via_ssh);
12144            }
12145            multi_buffer::Event::ExcerptsAdded {
12146                buffer,
12147                predecessor,
12148                excerpts,
12149            } => {
12150                self.tasks_update_task = Some(self.refresh_runnables(cx));
12151                let buffer_id = buffer.read(cx).remote_id();
12152                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12153                    if let Some(project) = &self.project {
12154                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12155                    }
12156                }
12157                cx.emit(EditorEvent::ExcerptsAdded {
12158                    buffer: buffer.clone(),
12159                    predecessor: *predecessor,
12160                    excerpts: excerpts.clone(),
12161                });
12162                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12163            }
12164            multi_buffer::Event::ExcerptsRemoved { ids } => {
12165                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12166                let buffer = self.buffer.read(cx);
12167                self.registered_buffers
12168                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12169                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12170            }
12171            multi_buffer::Event::ExcerptsEdited { ids } => {
12172                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12173            }
12174            multi_buffer::Event::ExcerptsExpanded { ids } => {
12175                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12176            }
12177            multi_buffer::Event::Reparsed(buffer_id) => {
12178                self.tasks_update_task = Some(self.refresh_runnables(cx));
12179
12180                cx.emit(EditorEvent::Reparsed(*buffer_id));
12181            }
12182            multi_buffer::Event::LanguageChanged(buffer_id) => {
12183                linked_editing_ranges::refresh_linked_ranges(self, cx);
12184                cx.emit(EditorEvent::Reparsed(*buffer_id));
12185                cx.notify();
12186            }
12187            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12188            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12189            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12190                cx.emit(EditorEvent::TitleChanged)
12191            }
12192            // multi_buffer::Event::DiffBaseChanged => {
12193            //     self.scrollbar_marker_state.dirty = true;
12194            //     cx.emit(EditorEvent::DiffBaseChanged);
12195            //     cx.notify();
12196            // }
12197            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12198            multi_buffer::Event::DiagnosticsUpdated => {
12199                self.refresh_active_diagnostics(cx);
12200                self.scrollbar_marker_state.dirty = true;
12201                cx.notify();
12202            }
12203            _ => {}
12204        };
12205    }
12206
12207    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12208        cx.notify();
12209    }
12210
12211    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12212        self.tasks_update_task = Some(self.refresh_runnables(cx));
12213        self.refresh_inline_completion(true, false, cx);
12214        self.refresh_inlay_hints(
12215            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12216                self.selections.newest_anchor().head(),
12217                &self.buffer.read(cx).snapshot(cx),
12218                cx,
12219            )),
12220            cx,
12221        );
12222
12223        let old_cursor_shape = self.cursor_shape;
12224
12225        {
12226            let editor_settings = EditorSettings::get_global(cx);
12227            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12228            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12229            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12230        }
12231
12232        if old_cursor_shape != self.cursor_shape {
12233            cx.emit(EditorEvent::CursorShapeChanged);
12234        }
12235
12236        let project_settings = ProjectSettings::get_global(cx);
12237        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12238
12239        if self.mode == EditorMode::Full {
12240            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12241            if self.git_blame_inline_enabled != inline_blame_enabled {
12242                self.toggle_git_blame_inline_internal(false, cx);
12243            }
12244        }
12245
12246        cx.notify();
12247    }
12248
12249    pub fn set_searchable(&mut self, searchable: bool) {
12250        self.searchable = searchable;
12251    }
12252
12253    pub fn searchable(&self) -> bool {
12254        self.searchable
12255    }
12256
12257    fn open_proposed_changes_editor(
12258        &mut self,
12259        _: &OpenProposedChangesEditor,
12260        cx: &mut ViewContext<Self>,
12261    ) {
12262        let Some(workspace) = self.workspace() else {
12263            cx.propagate();
12264            return;
12265        };
12266
12267        let selections = self.selections.all::<usize>(cx);
12268        let buffer = self.buffer.read(cx);
12269        let mut new_selections_by_buffer = HashMap::default();
12270        for selection in selections {
12271            for (buffer, range, _) in
12272                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12273            {
12274                let mut range = range.to_point(buffer.read(cx));
12275                range.start.column = 0;
12276                range.end.column = buffer.read(cx).line_len(range.end.row);
12277                new_selections_by_buffer
12278                    .entry(buffer)
12279                    .or_insert(Vec::new())
12280                    .push(range)
12281            }
12282        }
12283
12284        let proposed_changes_buffers = new_selections_by_buffer
12285            .into_iter()
12286            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12287            .collect::<Vec<_>>();
12288        let proposed_changes_editor = cx.new_view(|cx| {
12289            ProposedChangesEditor::new(
12290                "Proposed changes",
12291                proposed_changes_buffers,
12292                self.project.clone(),
12293                cx,
12294            )
12295        });
12296
12297        cx.window_context().defer(move |cx| {
12298            workspace.update(cx, |workspace, cx| {
12299                workspace.active_pane().update(cx, |pane, cx| {
12300                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12301                });
12302            });
12303        });
12304    }
12305
12306    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12307        self.open_excerpts_common(None, true, cx)
12308    }
12309
12310    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12311        self.open_excerpts_common(None, false, cx)
12312    }
12313
12314    fn open_excerpts_common(
12315        &mut self,
12316        jump_data: Option<JumpData>,
12317        split: bool,
12318        cx: &mut ViewContext<Self>,
12319    ) {
12320        let Some(workspace) = self.workspace() else {
12321            cx.propagate();
12322            return;
12323        };
12324
12325        if self.buffer.read(cx).is_singleton() {
12326            cx.propagate();
12327            return;
12328        }
12329
12330        let mut new_selections_by_buffer = HashMap::default();
12331        match &jump_data {
12332            Some(jump_data) => {
12333                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12334                if let Some(buffer) = multi_buffer_snapshot
12335                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12336                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12337                {
12338                    let buffer_snapshot = buffer.read(cx).snapshot();
12339                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12340                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12341                    } else {
12342                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12343                    };
12344                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12345                    new_selections_by_buffer.insert(
12346                        buffer,
12347                        (
12348                            vec![jump_to_offset..jump_to_offset],
12349                            Some(jump_data.line_offset_from_top),
12350                        ),
12351                    );
12352                }
12353            }
12354            None => {
12355                let selections = self.selections.all::<usize>(cx);
12356                let buffer = self.buffer.read(cx);
12357                for selection in selections {
12358                    for (mut buffer_handle, mut range, _) in
12359                        buffer.range_to_buffer_ranges(selection.range(), cx)
12360                    {
12361                        // When editing branch buffers, jump to the corresponding location
12362                        // in their base buffer.
12363                        let buffer = buffer_handle.read(cx);
12364                        if let Some(base_buffer) = buffer.base_buffer() {
12365                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12366                            buffer_handle = base_buffer;
12367                        }
12368
12369                        if selection.reversed {
12370                            mem::swap(&mut range.start, &mut range.end);
12371                        }
12372                        new_selections_by_buffer
12373                            .entry(buffer_handle)
12374                            .or_insert((Vec::new(), None))
12375                            .0
12376                            .push(range)
12377                    }
12378                }
12379            }
12380        }
12381
12382        if new_selections_by_buffer.is_empty() {
12383            return;
12384        }
12385
12386        // We defer the pane interaction because we ourselves are a workspace item
12387        // and activating a new item causes the pane to call a method on us reentrantly,
12388        // which panics if we're on the stack.
12389        cx.window_context().defer(move |cx| {
12390            workspace.update(cx, |workspace, cx| {
12391                let pane = if split {
12392                    workspace.adjacent_pane(cx)
12393                } else {
12394                    workspace.active_pane().clone()
12395                };
12396
12397                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12398                    let editor = buffer
12399                        .read(cx)
12400                        .file()
12401                        .is_none()
12402                        .then(|| {
12403                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12404                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12405                            // Instead, we try to activate the existing editor in the pane first.
12406                            let (editor, pane_item_index) =
12407                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12408                                    let editor = item.downcast::<Editor>()?;
12409                                    let singleton_buffer =
12410                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12411                                    if singleton_buffer == buffer {
12412                                        Some((editor, i))
12413                                    } else {
12414                                        None
12415                                    }
12416                                })?;
12417                            pane.update(cx, |pane, cx| {
12418                                pane.activate_item(pane_item_index, true, true, cx)
12419                            });
12420                            Some(editor)
12421                        })
12422                        .flatten()
12423                        .unwrap_or_else(|| {
12424                            workspace.open_project_item::<Self>(
12425                                pane.clone(),
12426                                buffer,
12427                                true,
12428                                true,
12429                                cx,
12430                            )
12431                        });
12432
12433                    editor.update(cx, |editor, cx| {
12434                        let autoscroll = match scroll_offset {
12435                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12436                            None => Autoscroll::newest(),
12437                        };
12438                        let nav_history = editor.nav_history.take();
12439                        editor.change_selections(Some(autoscroll), cx, |s| {
12440                            s.select_ranges(ranges);
12441                        });
12442                        editor.nav_history = nav_history;
12443                    });
12444                }
12445            })
12446        });
12447    }
12448
12449    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12450        let snapshot = self.buffer.read(cx).read(cx);
12451        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12452        Some(
12453            ranges
12454                .iter()
12455                .map(move |range| {
12456                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12457                })
12458                .collect(),
12459        )
12460    }
12461
12462    fn selection_replacement_ranges(
12463        &self,
12464        range: Range<OffsetUtf16>,
12465        cx: &mut AppContext,
12466    ) -> Vec<Range<OffsetUtf16>> {
12467        let selections = self.selections.all::<OffsetUtf16>(cx);
12468        let newest_selection = selections
12469            .iter()
12470            .max_by_key(|selection| selection.id)
12471            .unwrap();
12472        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12473        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12474        let snapshot = self.buffer.read(cx).read(cx);
12475        selections
12476            .into_iter()
12477            .map(|mut selection| {
12478                selection.start.0 =
12479                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12480                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12481                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12482                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12483            })
12484            .collect()
12485    }
12486
12487    fn report_editor_event(
12488        &self,
12489        operation: &'static str,
12490        file_extension: Option<String>,
12491        cx: &AppContext,
12492    ) {
12493        if cfg!(any(test, feature = "test-support")) {
12494            return;
12495        }
12496
12497        let Some(project) = &self.project else { return };
12498
12499        // If None, we are in a file without an extension
12500        let file = self
12501            .buffer
12502            .read(cx)
12503            .as_singleton()
12504            .and_then(|b| b.read(cx).file());
12505        let file_extension = file_extension.or(file
12506            .as_ref()
12507            .and_then(|file| Path::new(file.file_name(cx)).extension())
12508            .and_then(|e| e.to_str())
12509            .map(|a| a.to_string()));
12510
12511        let vim_mode = cx
12512            .global::<SettingsStore>()
12513            .raw_user_settings()
12514            .get("vim_mode")
12515            == Some(&serde_json::Value::Bool(true));
12516
12517        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12518            == language::language_settings::InlineCompletionProvider::Copilot;
12519        let copilot_enabled_for_language = self
12520            .buffer
12521            .read(cx)
12522            .settings_at(0, cx)
12523            .show_inline_completions;
12524
12525        let project = project.read(cx);
12526        let telemetry = project.client().telemetry().clone();
12527        telemetry.report_editor_event(
12528            file_extension,
12529            vim_mode,
12530            operation,
12531            copilot_enabled,
12532            copilot_enabled_for_language,
12533            project.is_via_ssh(),
12534        )
12535    }
12536
12537    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12538    /// with each line being an array of {text, highlight} objects.
12539    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12540        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12541            return;
12542        };
12543
12544        #[derive(Serialize)]
12545        struct Chunk<'a> {
12546            text: String,
12547            highlight: Option<&'a str>,
12548        }
12549
12550        let snapshot = buffer.read(cx).snapshot();
12551        let range = self
12552            .selected_text_range(false, cx)
12553            .and_then(|selection| {
12554                if selection.range.is_empty() {
12555                    None
12556                } else {
12557                    Some(selection.range)
12558                }
12559            })
12560            .unwrap_or_else(|| 0..snapshot.len());
12561
12562        let chunks = snapshot.chunks(range, true);
12563        let mut lines = Vec::new();
12564        let mut line: VecDeque<Chunk> = VecDeque::new();
12565
12566        let Some(style) = self.style.as_ref() else {
12567            return;
12568        };
12569
12570        for chunk in chunks {
12571            let highlight = chunk
12572                .syntax_highlight_id
12573                .and_then(|id| id.name(&style.syntax));
12574            let mut chunk_lines = chunk.text.split('\n').peekable();
12575            while let Some(text) = chunk_lines.next() {
12576                let mut merged_with_last_token = false;
12577                if let Some(last_token) = line.back_mut() {
12578                    if last_token.highlight == highlight {
12579                        last_token.text.push_str(text);
12580                        merged_with_last_token = true;
12581                    }
12582                }
12583
12584                if !merged_with_last_token {
12585                    line.push_back(Chunk {
12586                        text: text.into(),
12587                        highlight,
12588                    });
12589                }
12590
12591                if chunk_lines.peek().is_some() {
12592                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12593                        line.pop_front();
12594                    }
12595                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12596                        line.pop_back();
12597                    }
12598
12599                    lines.push(mem::take(&mut line));
12600                }
12601            }
12602        }
12603
12604        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12605            return;
12606        };
12607        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12608    }
12609
12610    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12611        self.request_autoscroll(Autoscroll::newest(), cx);
12612        let position = self.selections.newest_display(cx).start;
12613        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12614    }
12615
12616    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12617        &self.inlay_hint_cache
12618    }
12619
12620    pub fn replay_insert_event(
12621        &mut self,
12622        text: &str,
12623        relative_utf16_range: Option<Range<isize>>,
12624        cx: &mut ViewContext<Self>,
12625    ) {
12626        if !self.input_enabled {
12627            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12628            return;
12629        }
12630        if let Some(relative_utf16_range) = relative_utf16_range {
12631            let selections = self.selections.all::<OffsetUtf16>(cx);
12632            self.change_selections(None, cx, |s| {
12633                let new_ranges = selections.into_iter().map(|range| {
12634                    let start = OffsetUtf16(
12635                        range
12636                            .head()
12637                            .0
12638                            .saturating_add_signed(relative_utf16_range.start),
12639                    );
12640                    let end = OffsetUtf16(
12641                        range
12642                            .head()
12643                            .0
12644                            .saturating_add_signed(relative_utf16_range.end),
12645                    );
12646                    start..end
12647                });
12648                s.select_ranges(new_ranges);
12649            });
12650        }
12651
12652        self.handle_input(text, cx);
12653    }
12654
12655    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12656        let Some(provider) = self.semantics_provider.as_ref() else {
12657            return false;
12658        };
12659
12660        let mut supports = false;
12661        self.buffer().read(cx).for_each_buffer(|buffer| {
12662            supports |= provider.supports_inlay_hints(buffer, cx);
12663        });
12664        supports
12665    }
12666
12667    pub fn focus(&self, cx: &mut WindowContext) {
12668        cx.focus(&self.focus_handle)
12669    }
12670
12671    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12672        self.focus_handle.is_focused(cx)
12673    }
12674
12675    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12676        cx.emit(EditorEvent::Focused);
12677
12678        if let Some(descendant) = self
12679            .last_focused_descendant
12680            .take()
12681            .and_then(|descendant| descendant.upgrade())
12682        {
12683            cx.focus(&descendant);
12684        } else {
12685            if let Some(blame) = self.blame.as_ref() {
12686                blame.update(cx, GitBlame::focus)
12687            }
12688
12689            self.blink_manager.update(cx, BlinkManager::enable);
12690            self.show_cursor_names(cx);
12691            self.buffer.update(cx, |buffer, cx| {
12692                buffer.finalize_last_transaction(cx);
12693                if self.leader_peer_id.is_none() {
12694                    buffer.set_active_selections(
12695                        &self.selections.disjoint_anchors(),
12696                        self.selections.line_mode,
12697                        self.cursor_shape,
12698                        cx,
12699                    );
12700                }
12701            });
12702        }
12703    }
12704
12705    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12706        cx.emit(EditorEvent::FocusedIn)
12707    }
12708
12709    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12710        if event.blurred != self.focus_handle {
12711            self.last_focused_descendant = Some(event.blurred);
12712        }
12713    }
12714
12715    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12716        self.blink_manager.update(cx, BlinkManager::disable);
12717        self.buffer
12718            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12719
12720        if let Some(blame) = self.blame.as_ref() {
12721            blame.update(cx, GitBlame::blur)
12722        }
12723        if !self.hover_state.focused(cx) {
12724            hide_hover(self, cx);
12725        }
12726
12727        self.hide_context_menu(cx);
12728        cx.emit(EditorEvent::Blurred);
12729        cx.notify();
12730    }
12731
12732    pub fn register_action<A: Action>(
12733        &mut self,
12734        listener: impl Fn(&A, &mut WindowContext) + 'static,
12735    ) -> Subscription {
12736        let id = self.next_editor_action_id.post_inc();
12737        let listener = Arc::new(listener);
12738        self.editor_actions.borrow_mut().insert(
12739            id,
12740            Box::new(move |cx| {
12741                let cx = cx.window_context();
12742                let listener = listener.clone();
12743                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12744                    let action = action.downcast_ref().unwrap();
12745                    if phase == DispatchPhase::Bubble {
12746                        listener(action, cx)
12747                    }
12748                })
12749            }),
12750        );
12751
12752        let editor_actions = self.editor_actions.clone();
12753        Subscription::new(move || {
12754            editor_actions.borrow_mut().remove(&id);
12755        })
12756    }
12757
12758    pub fn file_header_size(&self) -> u32 {
12759        FILE_HEADER_HEIGHT
12760    }
12761
12762    pub fn revert(
12763        &mut self,
12764        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12765        cx: &mut ViewContext<Self>,
12766    ) {
12767        self.buffer().update(cx, |multi_buffer, cx| {
12768            for (buffer_id, changes) in revert_changes {
12769                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12770                    buffer.update(cx, |buffer, cx| {
12771                        buffer.edit(
12772                            changes.into_iter().map(|(range, text)| {
12773                                (range, text.to_string().map(Arc::<str>::from))
12774                            }),
12775                            None,
12776                            cx,
12777                        );
12778                    });
12779                }
12780            }
12781        });
12782        self.change_selections(None, cx, |selections| selections.refresh());
12783    }
12784
12785    pub fn to_pixel_point(
12786        &mut self,
12787        source: multi_buffer::Anchor,
12788        editor_snapshot: &EditorSnapshot,
12789        cx: &mut ViewContext<Self>,
12790    ) -> Option<gpui::Point<Pixels>> {
12791        let source_point = source.to_display_point(editor_snapshot);
12792        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12793    }
12794
12795    pub fn display_to_pixel_point(
12796        &self,
12797        source: DisplayPoint,
12798        editor_snapshot: &EditorSnapshot,
12799        cx: &WindowContext,
12800    ) -> Option<gpui::Point<Pixels>> {
12801        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12802        let text_layout_details = self.text_layout_details(cx);
12803        let scroll_top = text_layout_details
12804            .scroll_anchor
12805            .scroll_position(editor_snapshot)
12806            .y;
12807
12808        if source.row().as_f32() < scroll_top.floor() {
12809            return None;
12810        }
12811        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12812        let source_y = line_height * (source.row().as_f32() - scroll_top);
12813        Some(gpui::Point::new(source_x, source_y))
12814    }
12815
12816    pub fn has_active_completions_menu(&self) -> bool {
12817        self.context_menu.borrow().as_ref().map_or(false, |menu| {
12818            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12819        })
12820    }
12821
12822    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12823        self.addons
12824            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12825    }
12826
12827    pub fn unregister_addon<T: Addon>(&mut self) {
12828        self.addons.remove(&std::any::TypeId::of::<T>());
12829    }
12830
12831    pub fn addon<T: Addon>(&self) -> Option<&T> {
12832        let type_id = std::any::TypeId::of::<T>();
12833        self.addons
12834            .get(&type_id)
12835            .and_then(|item| item.to_any().downcast_ref::<T>())
12836    }
12837
12838    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12839        let text_layout_details = self.text_layout_details(cx);
12840        let style = &text_layout_details.editor_style;
12841        let font_id = cx.text_system().resolve_font(&style.text.font());
12842        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12843        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12844
12845        let em_width = cx
12846            .text_system()
12847            .typographic_bounds(font_id, font_size, 'm')
12848            .unwrap()
12849            .size
12850            .width;
12851
12852        gpui::Point::new(em_width, line_height)
12853    }
12854}
12855
12856fn get_unstaged_changes_for_buffers(
12857    project: &Model<Project>,
12858    buffers: impl IntoIterator<Item = Model<Buffer>>,
12859    cx: &mut ViewContext<Editor>,
12860) {
12861    let mut tasks = Vec::new();
12862    project.update(cx, |project, cx| {
12863        for buffer in buffers {
12864            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12865        }
12866    });
12867    cx.spawn(|this, mut cx| async move {
12868        let change_sets = futures::future::join_all(tasks).await;
12869        this.update(&mut cx, |this, cx| {
12870            for change_set in change_sets {
12871                if let Some(change_set) = change_set.log_err() {
12872                    this.diff_map.add_change_set(change_set, cx);
12873                }
12874            }
12875        })
12876        .ok();
12877    })
12878    .detach();
12879}
12880
12881fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12882    let tab_size = tab_size.get() as usize;
12883    let mut width = offset;
12884
12885    for ch in text.chars() {
12886        width += if ch == '\t' {
12887            tab_size - (width % tab_size)
12888        } else {
12889            1
12890        };
12891    }
12892
12893    width - offset
12894}
12895
12896#[cfg(test)]
12897mod tests {
12898    use super::*;
12899
12900    #[test]
12901    fn test_string_size_with_expanded_tabs() {
12902        let nz = |val| NonZeroU32::new(val).unwrap();
12903        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12904        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12905        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12906        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12907        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12908        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12909        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12910        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12911    }
12912}
12913
12914/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12915struct WordBreakingTokenizer<'a> {
12916    input: &'a str,
12917}
12918
12919impl<'a> WordBreakingTokenizer<'a> {
12920    fn new(input: &'a str) -> Self {
12921        Self { input }
12922    }
12923}
12924
12925fn is_char_ideographic(ch: char) -> bool {
12926    use unicode_script::Script::*;
12927    use unicode_script::UnicodeScript;
12928    matches!(ch.script(), Han | Tangut | Yi)
12929}
12930
12931fn is_grapheme_ideographic(text: &str) -> bool {
12932    text.chars().any(is_char_ideographic)
12933}
12934
12935fn is_grapheme_whitespace(text: &str) -> bool {
12936    text.chars().any(|x| x.is_whitespace())
12937}
12938
12939fn should_stay_with_preceding_ideograph(text: &str) -> bool {
12940    text.chars().next().map_or(false, |ch| {
12941        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
12942    })
12943}
12944
12945#[derive(PartialEq, Eq, Debug, Clone, Copy)]
12946struct WordBreakToken<'a> {
12947    token: &'a str,
12948    grapheme_len: usize,
12949    is_whitespace: bool,
12950}
12951
12952impl<'a> Iterator for WordBreakingTokenizer<'a> {
12953    /// Yields a span, the count of graphemes in the token, and whether it was
12954    /// whitespace. Note that it also breaks at word boundaries.
12955    type Item = WordBreakToken<'a>;
12956
12957    fn next(&mut self) -> Option<Self::Item> {
12958        use unicode_segmentation::UnicodeSegmentation;
12959        if self.input.is_empty() {
12960            return None;
12961        }
12962
12963        let mut iter = self.input.graphemes(true).peekable();
12964        let mut offset = 0;
12965        let mut graphemes = 0;
12966        if let Some(first_grapheme) = iter.next() {
12967            let is_whitespace = is_grapheme_whitespace(first_grapheme);
12968            offset += first_grapheme.len();
12969            graphemes += 1;
12970            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
12971                if let Some(grapheme) = iter.peek().copied() {
12972                    if should_stay_with_preceding_ideograph(grapheme) {
12973                        offset += grapheme.len();
12974                        graphemes += 1;
12975                    }
12976                }
12977            } else {
12978                let mut words = self.input[offset..].split_word_bound_indices().peekable();
12979                let mut next_word_bound = words.peek().copied();
12980                if next_word_bound.map_or(false, |(i, _)| i == 0) {
12981                    next_word_bound = words.next();
12982                }
12983                while let Some(grapheme) = iter.peek().copied() {
12984                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
12985                        break;
12986                    };
12987                    if is_grapheme_whitespace(grapheme) != is_whitespace {
12988                        break;
12989                    };
12990                    offset += grapheme.len();
12991                    graphemes += 1;
12992                    iter.next();
12993                }
12994            }
12995            let token = &self.input[..offset];
12996            self.input = &self.input[offset..];
12997            if is_whitespace {
12998                Some(WordBreakToken {
12999                    token: " ",
13000                    grapheme_len: 1,
13001                    is_whitespace: true,
13002                })
13003            } else {
13004                Some(WordBreakToken {
13005                    token,
13006                    grapheme_len: graphemes,
13007                    is_whitespace: false,
13008                })
13009            }
13010        } else {
13011            None
13012        }
13013    }
13014}
13015
13016#[test]
13017fn test_word_breaking_tokenizer() {
13018    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13019        ("", &[]),
13020        ("  ", &[(" ", 1, true)]),
13021        ("Ʒ", &[("Ʒ", 1, false)]),
13022        ("Ǽ", &[("Ǽ", 1, false)]),
13023        ("", &[("", 1, false)]),
13024        ("⋑⋑", &[("⋑⋑", 2, false)]),
13025        (
13026            "原理,进而",
13027            &[
13028                ("", 1, false),
13029                ("理,", 2, false),
13030                ("", 1, false),
13031                ("", 1, false),
13032            ],
13033        ),
13034        (
13035            "hello world",
13036            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13037        ),
13038        (
13039            "hello, world",
13040            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13041        ),
13042        (
13043            "  hello world",
13044            &[
13045                (" ", 1, true),
13046                ("hello", 5, false),
13047                (" ", 1, true),
13048                ("world", 5, false),
13049            ],
13050        ),
13051        (
13052            "这是什么 \n 钢笔",
13053            &[
13054                ("", 1, false),
13055                ("", 1, false),
13056                ("", 1, false),
13057                ("", 1, false),
13058                (" ", 1, true),
13059                ("", 1, false),
13060                ("", 1, false),
13061            ],
13062        ),
13063        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13064    ];
13065
13066    for (input, result) in tests {
13067        assert_eq!(
13068            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13069            result
13070                .iter()
13071                .copied()
13072                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13073                    token,
13074                    grapheme_len,
13075                    is_whitespace,
13076                })
13077                .collect::<Vec<_>>()
13078        );
13079    }
13080}
13081
13082fn wrap_with_prefix(
13083    line_prefix: String,
13084    unwrapped_text: String,
13085    wrap_column: usize,
13086    tab_size: NonZeroU32,
13087) -> String {
13088    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13089    let mut wrapped_text = String::new();
13090    let mut current_line = line_prefix.clone();
13091
13092    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13093    let mut current_line_len = line_prefix_len;
13094    for WordBreakToken {
13095        token,
13096        grapheme_len,
13097        is_whitespace,
13098    } in tokenizer
13099    {
13100        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13101            wrapped_text.push_str(current_line.trim_end());
13102            wrapped_text.push('\n');
13103            current_line.truncate(line_prefix.len());
13104            current_line_len = line_prefix_len;
13105            if !is_whitespace {
13106                current_line.push_str(token);
13107                current_line_len += grapheme_len;
13108            }
13109        } else if !is_whitespace {
13110            current_line.push_str(token);
13111            current_line_len += grapheme_len;
13112        } else if current_line_len != line_prefix_len {
13113            current_line.push(' ');
13114            current_line_len += 1;
13115        }
13116    }
13117
13118    if !current_line.is_empty() {
13119        wrapped_text.push_str(&current_line);
13120    }
13121    wrapped_text
13122}
13123
13124#[test]
13125fn test_wrap_with_prefix() {
13126    assert_eq!(
13127        wrap_with_prefix(
13128            "# ".to_string(),
13129            "abcdefg".to_string(),
13130            4,
13131            NonZeroU32::new(4).unwrap()
13132        ),
13133        "# abcdefg"
13134    );
13135    assert_eq!(
13136        wrap_with_prefix(
13137            "".to_string(),
13138            "\thello world".to_string(),
13139            8,
13140            NonZeroU32::new(4).unwrap()
13141        ),
13142        "hello\nworld"
13143    );
13144    assert_eq!(
13145        wrap_with_prefix(
13146            "// ".to_string(),
13147            "xx \nyy zz aa bb cc".to_string(),
13148            12,
13149            NonZeroU32::new(4).unwrap()
13150        ),
13151        "// xx yy zz\n// aa bb cc"
13152    );
13153    assert_eq!(
13154        wrap_with_prefix(
13155            String::new(),
13156            "这是什么 \n 钢笔".to_string(),
13157            3,
13158            NonZeroU32::new(4).unwrap()
13159        ),
13160        "这是什\n么 钢\n"
13161    );
13162}
13163
13164fn hunks_for_selections(
13165    snapshot: &EditorSnapshot,
13166    selections: &[Selection<Point>],
13167) -> Vec<MultiBufferDiffHunk> {
13168    hunks_for_ranges(
13169        selections.iter().map(|selection| selection.range()),
13170        snapshot,
13171    )
13172}
13173
13174pub fn hunks_for_ranges(
13175    ranges: impl Iterator<Item = Range<Point>>,
13176    snapshot: &EditorSnapshot,
13177) -> Vec<MultiBufferDiffHunk> {
13178    let mut hunks = Vec::new();
13179    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13180        HashMap::default();
13181    for query_range in ranges {
13182        let query_rows =
13183            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13184        for hunk in snapshot.diff_map.diff_hunks_in_range(
13185            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13186            &snapshot.buffer_snapshot,
13187        ) {
13188            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13189            // when the caret is just above or just below the deleted hunk.
13190            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13191            let related_to_selection = if allow_adjacent {
13192                hunk.row_range.overlaps(&query_rows)
13193                    || hunk.row_range.start == query_rows.end
13194                    || hunk.row_range.end == query_rows.start
13195            } else {
13196                hunk.row_range.overlaps(&query_rows)
13197            };
13198            if related_to_selection {
13199                if !processed_buffer_rows
13200                    .entry(hunk.buffer_id)
13201                    .or_default()
13202                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13203                {
13204                    continue;
13205                }
13206                hunks.push(hunk);
13207            }
13208        }
13209    }
13210
13211    hunks
13212}
13213
13214pub trait CollaborationHub {
13215    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13216    fn user_participant_indices<'a>(
13217        &self,
13218        cx: &'a AppContext,
13219    ) -> &'a HashMap<u64, ParticipantIndex>;
13220    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13221}
13222
13223impl CollaborationHub for Model<Project> {
13224    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13225        self.read(cx).collaborators()
13226    }
13227
13228    fn user_participant_indices<'a>(
13229        &self,
13230        cx: &'a AppContext,
13231    ) -> &'a HashMap<u64, ParticipantIndex> {
13232        self.read(cx).user_store().read(cx).participant_indices()
13233    }
13234
13235    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13236        let this = self.read(cx);
13237        let user_ids = this.collaborators().values().map(|c| c.user_id);
13238        this.user_store().read_with(cx, |user_store, cx| {
13239            user_store.participant_names(user_ids, cx)
13240        })
13241    }
13242}
13243
13244pub trait SemanticsProvider {
13245    fn hover(
13246        &self,
13247        buffer: &Model<Buffer>,
13248        position: text::Anchor,
13249        cx: &mut AppContext,
13250    ) -> Option<Task<Vec<project::Hover>>>;
13251
13252    fn inlay_hints(
13253        &self,
13254        buffer_handle: Model<Buffer>,
13255        range: Range<text::Anchor>,
13256        cx: &mut AppContext,
13257    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13258
13259    fn resolve_inlay_hint(
13260        &self,
13261        hint: InlayHint,
13262        buffer_handle: Model<Buffer>,
13263        server_id: LanguageServerId,
13264        cx: &mut AppContext,
13265    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13266
13267    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13268
13269    fn document_highlights(
13270        &self,
13271        buffer: &Model<Buffer>,
13272        position: text::Anchor,
13273        cx: &mut AppContext,
13274    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13275
13276    fn definitions(
13277        &self,
13278        buffer: &Model<Buffer>,
13279        position: text::Anchor,
13280        kind: GotoDefinitionKind,
13281        cx: &mut AppContext,
13282    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13283
13284    fn range_for_rename(
13285        &self,
13286        buffer: &Model<Buffer>,
13287        position: text::Anchor,
13288        cx: &mut AppContext,
13289    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13290
13291    fn perform_rename(
13292        &self,
13293        buffer: &Model<Buffer>,
13294        position: text::Anchor,
13295        new_name: String,
13296        cx: &mut AppContext,
13297    ) -> Option<Task<Result<ProjectTransaction>>>;
13298}
13299
13300pub trait CompletionProvider {
13301    fn completions(
13302        &self,
13303        buffer: &Model<Buffer>,
13304        buffer_position: text::Anchor,
13305        trigger: CompletionContext,
13306        cx: &mut ViewContext<Editor>,
13307    ) -> Task<Result<Vec<Completion>>>;
13308
13309    fn resolve_completions(
13310        &self,
13311        buffer: Model<Buffer>,
13312        completion_indices: Vec<usize>,
13313        completions: Rc<RefCell<Box<[Completion]>>>,
13314        cx: &mut ViewContext<Editor>,
13315    ) -> Task<Result<bool>>;
13316
13317    fn apply_additional_edits_for_completion(
13318        &self,
13319        buffer: Model<Buffer>,
13320        completion: Completion,
13321        push_to_history: bool,
13322        cx: &mut ViewContext<Editor>,
13323    ) -> Task<Result<Option<language::Transaction>>>;
13324
13325    fn is_completion_trigger(
13326        &self,
13327        buffer: &Model<Buffer>,
13328        position: language::Anchor,
13329        text: &str,
13330        trigger_in_words: bool,
13331        cx: &mut ViewContext<Editor>,
13332    ) -> bool;
13333
13334    fn sort_completions(&self) -> bool {
13335        true
13336    }
13337}
13338
13339pub trait CodeActionProvider {
13340    fn code_actions(
13341        &self,
13342        buffer: &Model<Buffer>,
13343        range: Range<text::Anchor>,
13344        cx: &mut WindowContext,
13345    ) -> Task<Result<Vec<CodeAction>>>;
13346
13347    fn apply_code_action(
13348        &self,
13349        buffer_handle: Model<Buffer>,
13350        action: CodeAction,
13351        excerpt_id: ExcerptId,
13352        push_to_history: bool,
13353        cx: &mut WindowContext,
13354    ) -> Task<Result<ProjectTransaction>>;
13355}
13356
13357impl CodeActionProvider for Model<Project> {
13358    fn code_actions(
13359        &self,
13360        buffer: &Model<Buffer>,
13361        range: Range<text::Anchor>,
13362        cx: &mut WindowContext,
13363    ) -> Task<Result<Vec<CodeAction>>> {
13364        self.update(cx, |project, cx| {
13365            project.code_actions(buffer, range, None, cx)
13366        })
13367    }
13368
13369    fn apply_code_action(
13370        &self,
13371        buffer_handle: Model<Buffer>,
13372        action: CodeAction,
13373        _excerpt_id: ExcerptId,
13374        push_to_history: bool,
13375        cx: &mut WindowContext,
13376    ) -> Task<Result<ProjectTransaction>> {
13377        self.update(cx, |project, cx| {
13378            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13379        })
13380    }
13381}
13382
13383fn snippet_completions(
13384    project: &Project,
13385    buffer: &Model<Buffer>,
13386    buffer_position: text::Anchor,
13387    cx: &mut AppContext,
13388) -> Task<Result<Vec<Completion>>> {
13389    let language = buffer.read(cx).language_at(buffer_position);
13390    let language_name = language.as_ref().map(|language| language.lsp_id());
13391    let snippet_store = project.snippets().read(cx);
13392    let snippets = snippet_store.snippets_for(language_name, cx);
13393
13394    if snippets.is_empty() {
13395        return Task::ready(Ok(vec![]));
13396    }
13397    let snapshot = buffer.read(cx).text_snapshot();
13398    let chars: String = snapshot
13399        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13400        .collect();
13401
13402    let scope = language.map(|language| language.default_scope());
13403    let executor = cx.background_executor().clone();
13404
13405    cx.background_executor().spawn(async move {
13406        let classifier = CharClassifier::new(scope).for_completion(true);
13407        let mut last_word = chars
13408            .chars()
13409            .take_while(|c| classifier.is_word(*c))
13410            .collect::<String>();
13411        last_word = last_word.chars().rev().collect();
13412
13413        if last_word.is_empty() {
13414            return Ok(vec![]);
13415        }
13416
13417        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13418        let to_lsp = |point: &text::Anchor| {
13419            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13420            point_to_lsp(end)
13421        };
13422        let lsp_end = to_lsp(&buffer_position);
13423
13424        let candidates = snippets
13425            .iter()
13426            .enumerate()
13427            .flat_map(|(ix, snippet)| {
13428                snippet
13429                    .prefix
13430                    .iter()
13431                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13432            })
13433            .collect::<Vec<StringMatchCandidate>>();
13434
13435        let mut matches = fuzzy::match_strings(
13436            &candidates,
13437            &last_word,
13438            last_word.chars().any(|c| c.is_uppercase()),
13439            100,
13440            &Default::default(),
13441            executor,
13442        )
13443        .await;
13444
13445        // Remove all candidates where the query's start does not match the start of any word in the candidate
13446        if let Some(query_start) = last_word.chars().next() {
13447            matches.retain(|string_match| {
13448                split_words(&string_match.string).any(|word| {
13449                    // Check that the first codepoint of the word as lowercase matches the first
13450                    // codepoint of the query as lowercase
13451                    word.chars()
13452                        .flat_map(|codepoint| codepoint.to_lowercase())
13453                        .zip(query_start.to_lowercase())
13454                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13455                })
13456            });
13457        }
13458
13459        let matched_strings = matches
13460            .into_iter()
13461            .map(|m| m.string)
13462            .collect::<HashSet<_>>();
13463
13464        let result: Vec<Completion> = snippets
13465            .into_iter()
13466            .filter_map(|snippet| {
13467                let matching_prefix = snippet
13468                    .prefix
13469                    .iter()
13470                    .find(|prefix| matched_strings.contains(*prefix))?;
13471                let start = as_offset - last_word.len();
13472                let start = snapshot.anchor_before(start);
13473                let range = start..buffer_position;
13474                let lsp_start = to_lsp(&start);
13475                let lsp_range = lsp::Range {
13476                    start: lsp_start,
13477                    end: lsp_end,
13478                };
13479                Some(Completion {
13480                    old_range: range,
13481                    new_text: snippet.body.clone(),
13482                    label: CodeLabel {
13483                        text: matching_prefix.clone(),
13484                        runs: vec![],
13485                        filter_range: 0..matching_prefix.len(),
13486                    },
13487                    server_id: LanguageServerId(usize::MAX),
13488                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13489                    lsp_completion: lsp::CompletionItem {
13490                        label: snippet.prefix.first().unwrap().clone(),
13491                        kind: Some(CompletionItemKind::SNIPPET),
13492                        label_details: snippet.description.as_ref().map(|description| {
13493                            lsp::CompletionItemLabelDetails {
13494                                detail: Some(description.clone()),
13495                                description: None,
13496                            }
13497                        }),
13498                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13499                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13500                            lsp::InsertReplaceEdit {
13501                                new_text: snippet.body.clone(),
13502                                insert: lsp_range,
13503                                replace: lsp_range,
13504                            },
13505                        )),
13506                        filter_text: Some(snippet.body.clone()),
13507                        sort_text: Some(char::MAX.to_string()),
13508                        ..Default::default()
13509                    },
13510                    confirm: None,
13511                })
13512            })
13513            .collect();
13514
13515        Ok(result)
13516    })
13517}
13518
13519impl CompletionProvider for Model<Project> {
13520    fn completions(
13521        &self,
13522        buffer: &Model<Buffer>,
13523        buffer_position: text::Anchor,
13524        options: CompletionContext,
13525        cx: &mut ViewContext<Editor>,
13526    ) -> Task<Result<Vec<Completion>>> {
13527        self.update(cx, |project, cx| {
13528            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13529            let project_completions = project.completions(buffer, buffer_position, options, cx);
13530            cx.background_executor().spawn(async move {
13531                let mut completions = project_completions.await?;
13532                let snippets_completions = snippets.await?;
13533                completions.extend(snippets_completions);
13534                Ok(completions)
13535            })
13536        })
13537    }
13538
13539    fn resolve_completions(
13540        &self,
13541        buffer: Model<Buffer>,
13542        completion_indices: Vec<usize>,
13543        completions: Rc<RefCell<Box<[Completion]>>>,
13544        cx: &mut ViewContext<Editor>,
13545    ) -> Task<Result<bool>> {
13546        self.update(cx, |project, cx| {
13547            project.resolve_completions(buffer, completion_indices, completions, cx)
13548        })
13549    }
13550
13551    fn apply_additional_edits_for_completion(
13552        &self,
13553        buffer: Model<Buffer>,
13554        completion: Completion,
13555        push_to_history: bool,
13556        cx: &mut ViewContext<Editor>,
13557    ) -> Task<Result<Option<language::Transaction>>> {
13558        self.update(cx, |project, cx| {
13559            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13560        })
13561    }
13562
13563    fn is_completion_trigger(
13564        &self,
13565        buffer: &Model<Buffer>,
13566        position: language::Anchor,
13567        text: &str,
13568        trigger_in_words: bool,
13569        cx: &mut ViewContext<Editor>,
13570    ) -> bool {
13571        let mut chars = text.chars();
13572        let char = if let Some(char) = chars.next() {
13573            char
13574        } else {
13575            return false;
13576        };
13577        if chars.next().is_some() {
13578            return false;
13579        }
13580
13581        let buffer = buffer.read(cx);
13582        let snapshot = buffer.snapshot();
13583        if !snapshot.settings_at(position, cx).show_completions_on_input {
13584            return false;
13585        }
13586        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13587        if trigger_in_words && classifier.is_word(char) {
13588            return true;
13589        }
13590
13591        buffer.completion_triggers().contains(text)
13592    }
13593}
13594
13595impl SemanticsProvider for Model<Project> {
13596    fn hover(
13597        &self,
13598        buffer: &Model<Buffer>,
13599        position: text::Anchor,
13600        cx: &mut AppContext,
13601    ) -> Option<Task<Vec<project::Hover>>> {
13602        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13603    }
13604
13605    fn document_highlights(
13606        &self,
13607        buffer: &Model<Buffer>,
13608        position: text::Anchor,
13609        cx: &mut AppContext,
13610    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13611        Some(self.update(cx, |project, cx| {
13612            project.document_highlights(buffer, position, cx)
13613        }))
13614    }
13615
13616    fn definitions(
13617        &self,
13618        buffer: &Model<Buffer>,
13619        position: text::Anchor,
13620        kind: GotoDefinitionKind,
13621        cx: &mut AppContext,
13622    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13623        Some(self.update(cx, |project, cx| match kind {
13624            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13625            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13626            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13627            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13628        }))
13629    }
13630
13631    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13632        // TODO: make this work for remote projects
13633        self.read(cx)
13634            .language_servers_for_local_buffer(buffer.read(cx), cx)
13635            .any(
13636                |(_, server)| match server.capabilities().inlay_hint_provider {
13637                    Some(lsp::OneOf::Left(enabled)) => enabled,
13638                    Some(lsp::OneOf::Right(_)) => true,
13639                    None => false,
13640                },
13641            )
13642    }
13643
13644    fn inlay_hints(
13645        &self,
13646        buffer_handle: Model<Buffer>,
13647        range: Range<text::Anchor>,
13648        cx: &mut AppContext,
13649    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13650        Some(self.update(cx, |project, cx| {
13651            project.inlay_hints(buffer_handle, range, cx)
13652        }))
13653    }
13654
13655    fn resolve_inlay_hint(
13656        &self,
13657        hint: InlayHint,
13658        buffer_handle: Model<Buffer>,
13659        server_id: LanguageServerId,
13660        cx: &mut AppContext,
13661    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13662        Some(self.update(cx, |project, cx| {
13663            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13664        }))
13665    }
13666
13667    fn range_for_rename(
13668        &self,
13669        buffer: &Model<Buffer>,
13670        position: text::Anchor,
13671        cx: &mut AppContext,
13672    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13673        Some(self.update(cx, |project, cx| {
13674            project.prepare_rename(buffer.clone(), position, cx)
13675        }))
13676    }
13677
13678    fn perform_rename(
13679        &self,
13680        buffer: &Model<Buffer>,
13681        position: text::Anchor,
13682        new_name: String,
13683        cx: &mut AppContext,
13684    ) -> Option<Task<Result<ProjectTransaction>>> {
13685        Some(self.update(cx, |project, cx| {
13686            project.perform_rename(buffer.clone(), position, new_name, cx)
13687        }))
13688    }
13689}
13690
13691fn inlay_hint_settings(
13692    location: Anchor,
13693    snapshot: &MultiBufferSnapshot,
13694    cx: &mut ViewContext<'_, Editor>,
13695) -> InlayHintSettings {
13696    let file = snapshot.file_at(location);
13697    let language = snapshot.language_at(location).map(|l| l.name());
13698    language_settings(language, file, cx).inlay_hints
13699}
13700
13701fn consume_contiguous_rows(
13702    contiguous_row_selections: &mut Vec<Selection<Point>>,
13703    selection: &Selection<Point>,
13704    display_map: &DisplaySnapshot,
13705    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13706) -> (MultiBufferRow, MultiBufferRow) {
13707    contiguous_row_selections.push(selection.clone());
13708    let start_row = MultiBufferRow(selection.start.row);
13709    let mut end_row = ending_row(selection, display_map);
13710
13711    while let Some(next_selection) = selections.peek() {
13712        if next_selection.start.row <= end_row.0 {
13713            end_row = ending_row(next_selection, display_map);
13714            contiguous_row_selections.push(selections.next().unwrap().clone());
13715        } else {
13716            break;
13717        }
13718    }
13719    (start_row, end_row)
13720}
13721
13722fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13723    if next_selection.end.column > 0 || next_selection.is_empty() {
13724        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13725    } else {
13726        MultiBufferRow(next_selection.end.row)
13727    }
13728}
13729
13730impl EditorSnapshot {
13731    pub fn remote_selections_in_range<'a>(
13732        &'a self,
13733        range: &'a Range<Anchor>,
13734        collaboration_hub: &dyn CollaborationHub,
13735        cx: &'a AppContext,
13736    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13737        let participant_names = collaboration_hub.user_names(cx);
13738        let participant_indices = collaboration_hub.user_participant_indices(cx);
13739        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13740        let collaborators_by_replica_id = collaborators_by_peer_id
13741            .iter()
13742            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13743            .collect::<HashMap<_, _>>();
13744        self.buffer_snapshot
13745            .selections_in_range(range, false)
13746            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13747                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13748                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13749                let user_name = participant_names.get(&collaborator.user_id).cloned();
13750                Some(RemoteSelection {
13751                    replica_id,
13752                    selection,
13753                    cursor_shape,
13754                    line_mode,
13755                    participant_index,
13756                    peer_id: collaborator.peer_id,
13757                    user_name,
13758                })
13759            })
13760    }
13761
13762    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13763        self.display_snapshot.buffer_snapshot.language_at(position)
13764    }
13765
13766    pub fn is_focused(&self) -> bool {
13767        self.is_focused
13768    }
13769
13770    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13771        self.placeholder_text.as_ref()
13772    }
13773
13774    pub fn scroll_position(&self) -> gpui::Point<f32> {
13775        self.scroll_anchor.scroll_position(&self.display_snapshot)
13776    }
13777
13778    fn gutter_dimensions(
13779        &self,
13780        font_id: FontId,
13781        font_size: Pixels,
13782        em_width: Pixels,
13783        em_advance: Pixels,
13784        max_line_number_width: Pixels,
13785        cx: &AppContext,
13786    ) -> GutterDimensions {
13787        if !self.show_gutter {
13788            return GutterDimensions::default();
13789        }
13790        let descent = cx.text_system().descent(font_id, font_size);
13791
13792        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13793            matches!(
13794                ProjectSettings::get_global(cx).git.git_gutter,
13795                Some(GitGutterSetting::TrackedFiles)
13796            )
13797        });
13798        let gutter_settings = EditorSettings::get_global(cx).gutter;
13799        let show_line_numbers = self
13800            .show_line_numbers
13801            .unwrap_or(gutter_settings.line_numbers);
13802        let line_gutter_width = if show_line_numbers {
13803            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13804            let min_width_for_number_on_gutter = em_advance * 4.0;
13805            max_line_number_width.max(min_width_for_number_on_gutter)
13806        } else {
13807            0.0.into()
13808        };
13809
13810        let show_code_actions = self
13811            .show_code_actions
13812            .unwrap_or(gutter_settings.code_actions);
13813
13814        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13815
13816        let git_blame_entries_width =
13817            self.git_blame_gutter_max_author_length
13818                .map(|max_author_length| {
13819                    // Length of the author name, but also space for the commit hash,
13820                    // the spacing and the timestamp.
13821                    let max_char_count = max_author_length
13822                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13823                        + 7 // length of commit sha
13824                        + 14 // length of max relative timestamp ("60 minutes ago")
13825                        + 4; // gaps and margins
13826
13827                    em_advance * max_char_count
13828                });
13829
13830        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13831        left_padding += if show_code_actions || show_runnables {
13832            em_width * 3.0
13833        } else if show_git_gutter && show_line_numbers {
13834            em_width * 2.0
13835        } else if show_git_gutter || show_line_numbers {
13836            em_width
13837        } else {
13838            px(0.)
13839        };
13840
13841        let right_padding = if gutter_settings.folds && show_line_numbers {
13842            em_width * 4.0
13843        } else if gutter_settings.folds {
13844            em_width * 3.0
13845        } else if show_line_numbers {
13846            em_width
13847        } else {
13848            px(0.)
13849        };
13850
13851        GutterDimensions {
13852            left_padding,
13853            right_padding,
13854            width: line_gutter_width + left_padding + right_padding,
13855            margin: -descent,
13856            git_blame_entries_width,
13857        }
13858    }
13859
13860    pub fn render_crease_toggle(
13861        &self,
13862        buffer_row: MultiBufferRow,
13863        row_contains_cursor: bool,
13864        editor: View<Editor>,
13865        cx: &mut WindowContext,
13866    ) -> Option<AnyElement> {
13867        let folded = self.is_line_folded(buffer_row);
13868        let mut is_foldable = false;
13869
13870        if let Some(crease) = self
13871            .crease_snapshot
13872            .query_row(buffer_row, &self.buffer_snapshot)
13873        {
13874            is_foldable = true;
13875            match crease {
13876                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13877                    if let Some(render_toggle) = render_toggle {
13878                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13879                            if folded {
13880                                editor.update(cx, |editor, cx| {
13881                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13882                                });
13883                            } else {
13884                                editor.update(cx, |editor, cx| {
13885                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13886                                });
13887                            }
13888                        });
13889                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13890                    }
13891                }
13892            }
13893        }
13894
13895        is_foldable |= self.starts_indent(buffer_row);
13896
13897        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13898            Some(
13899                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13900                    .toggle_state(folded)
13901                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13902                        if folded {
13903                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13904                        } else {
13905                            this.fold_at(&FoldAt { buffer_row }, cx);
13906                        }
13907                    }))
13908                    .into_any_element(),
13909            )
13910        } else {
13911            None
13912        }
13913    }
13914
13915    pub fn render_crease_trailer(
13916        &self,
13917        buffer_row: MultiBufferRow,
13918        cx: &mut WindowContext,
13919    ) -> Option<AnyElement> {
13920        let folded = self.is_line_folded(buffer_row);
13921        if let Crease::Inline { render_trailer, .. } = self
13922            .crease_snapshot
13923            .query_row(buffer_row, &self.buffer_snapshot)?
13924        {
13925            let render_trailer = render_trailer.as_ref()?;
13926            Some(render_trailer(buffer_row, folded, cx))
13927        } else {
13928            None
13929        }
13930    }
13931}
13932
13933impl Deref for EditorSnapshot {
13934    type Target = DisplaySnapshot;
13935
13936    fn deref(&self) -> &Self::Target {
13937        &self.display_snapshot
13938    }
13939}
13940
13941#[derive(Clone, Debug, PartialEq, Eq)]
13942pub enum EditorEvent {
13943    InputIgnored {
13944        text: Arc<str>,
13945    },
13946    InputHandled {
13947        utf16_range_to_replace: Option<Range<isize>>,
13948        text: Arc<str>,
13949    },
13950    ExcerptsAdded {
13951        buffer: Model<Buffer>,
13952        predecessor: ExcerptId,
13953        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13954    },
13955    ExcerptsRemoved {
13956        ids: Vec<ExcerptId>,
13957    },
13958    BufferFoldToggled {
13959        ids: Vec<ExcerptId>,
13960        folded: bool,
13961    },
13962    ExcerptsEdited {
13963        ids: Vec<ExcerptId>,
13964    },
13965    ExcerptsExpanded {
13966        ids: Vec<ExcerptId>,
13967    },
13968    BufferEdited,
13969    Edited {
13970        transaction_id: clock::Lamport,
13971    },
13972    Reparsed(BufferId),
13973    Focused,
13974    FocusedIn,
13975    Blurred,
13976    DirtyChanged,
13977    Saved,
13978    TitleChanged,
13979    DiffBaseChanged,
13980    SelectionsChanged {
13981        local: bool,
13982    },
13983    ScrollPositionChanged {
13984        local: bool,
13985        autoscroll: bool,
13986    },
13987    Closed,
13988    TransactionUndone {
13989        transaction_id: clock::Lamport,
13990    },
13991    TransactionBegun {
13992        transaction_id: clock::Lamport,
13993    },
13994    Reloaded,
13995    CursorShapeChanged,
13996}
13997
13998impl EventEmitter<EditorEvent> for Editor {}
13999
14000impl FocusableView for Editor {
14001    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14002        self.focus_handle.clone()
14003    }
14004}
14005
14006impl Render for Editor {
14007    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14008        let settings = ThemeSettings::get_global(cx);
14009
14010        let mut text_style = match self.mode {
14011            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14012                color: cx.theme().colors().editor_foreground,
14013                font_family: settings.ui_font.family.clone(),
14014                font_features: settings.ui_font.features.clone(),
14015                font_fallbacks: settings.ui_font.fallbacks.clone(),
14016                font_size: rems(0.875).into(),
14017                font_weight: settings.ui_font.weight,
14018                line_height: relative(settings.buffer_line_height.value()),
14019                ..Default::default()
14020            },
14021            EditorMode::Full => TextStyle {
14022                color: cx.theme().colors().editor_foreground,
14023                font_family: settings.buffer_font.family.clone(),
14024                font_features: settings.buffer_font.features.clone(),
14025                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14026                font_size: settings.buffer_font_size(cx).into(),
14027                font_weight: settings.buffer_font.weight,
14028                line_height: relative(settings.buffer_line_height.value()),
14029                ..Default::default()
14030            },
14031        };
14032        if let Some(text_style_refinement) = &self.text_style_refinement {
14033            text_style.refine(text_style_refinement)
14034        }
14035
14036        let background = match self.mode {
14037            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14038            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14039            EditorMode::Full => cx.theme().colors().editor_background,
14040        };
14041
14042        EditorElement::new(
14043            cx.view(),
14044            EditorStyle {
14045                background,
14046                local_player: cx.theme().players().local(),
14047                text: text_style,
14048                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14049                syntax: cx.theme().syntax().clone(),
14050                status: cx.theme().status().clone(),
14051                inlay_hints_style: make_inlay_hints_style(cx),
14052                inline_completion_styles: make_suggestion_styles(cx),
14053                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14054            },
14055        )
14056    }
14057}
14058
14059impl ViewInputHandler for Editor {
14060    fn text_for_range(
14061        &mut self,
14062        range_utf16: Range<usize>,
14063        adjusted_range: &mut Option<Range<usize>>,
14064        cx: &mut ViewContext<Self>,
14065    ) -> Option<String> {
14066        let snapshot = self.buffer.read(cx).read(cx);
14067        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14068        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14069        if (start.0..end.0) != range_utf16 {
14070            adjusted_range.replace(start.0..end.0);
14071        }
14072        Some(snapshot.text_for_range(start..end).collect())
14073    }
14074
14075    fn selected_text_range(
14076        &mut self,
14077        ignore_disabled_input: bool,
14078        cx: &mut ViewContext<Self>,
14079    ) -> Option<UTF16Selection> {
14080        // Prevent the IME menu from appearing when holding down an alphabetic key
14081        // while input is disabled.
14082        if !ignore_disabled_input && !self.input_enabled {
14083            return None;
14084        }
14085
14086        let selection = self.selections.newest::<OffsetUtf16>(cx);
14087        let range = selection.range();
14088
14089        Some(UTF16Selection {
14090            range: range.start.0..range.end.0,
14091            reversed: selection.reversed,
14092        })
14093    }
14094
14095    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14096        let snapshot = self.buffer.read(cx).read(cx);
14097        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14098        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14099    }
14100
14101    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14102        self.clear_highlights::<InputComposition>(cx);
14103        self.ime_transaction.take();
14104    }
14105
14106    fn replace_text_in_range(
14107        &mut self,
14108        range_utf16: Option<Range<usize>>,
14109        text: &str,
14110        cx: &mut ViewContext<Self>,
14111    ) {
14112        if !self.input_enabled {
14113            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14114            return;
14115        }
14116
14117        self.transact(cx, |this, cx| {
14118            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14119                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14120                Some(this.selection_replacement_ranges(range_utf16, cx))
14121            } else {
14122                this.marked_text_ranges(cx)
14123            };
14124
14125            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14126                let newest_selection_id = this.selections.newest_anchor().id;
14127                this.selections
14128                    .all::<OffsetUtf16>(cx)
14129                    .iter()
14130                    .zip(ranges_to_replace.iter())
14131                    .find_map(|(selection, range)| {
14132                        if selection.id == newest_selection_id {
14133                            Some(
14134                                (range.start.0 as isize - selection.head().0 as isize)
14135                                    ..(range.end.0 as isize - selection.head().0 as isize),
14136                            )
14137                        } else {
14138                            None
14139                        }
14140                    })
14141            });
14142
14143            cx.emit(EditorEvent::InputHandled {
14144                utf16_range_to_replace: range_to_replace,
14145                text: text.into(),
14146            });
14147
14148            if let Some(new_selected_ranges) = new_selected_ranges {
14149                this.change_selections(None, cx, |selections| {
14150                    selections.select_ranges(new_selected_ranges)
14151                });
14152                this.backspace(&Default::default(), cx);
14153            }
14154
14155            this.handle_input(text, cx);
14156        });
14157
14158        if let Some(transaction) = self.ime_transaction {
14159            self.buffer.update(cx, |buffer, cx| {
14160                buffer.group_until_transaction(transaction, cx);
14161            });
14162        }
14163
14164        self.unmark_text(cx);
14165    }
14166
14167    fn replace_and_mark_text_in_range(
14168        &mut self,
14169        range_utf16: Option<Range<usize>>,
14170        text: &str,
14171        new_selected_range_utf16: Option<Range<usize>>,
14172        cx: &mut ViewContext<Self>,
14173    ) {
14174        if !self.input_enabled {
14175            return;
14176        }
14177
14178        let transaction = self.transact(cx, |this, cx| {
14179            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14180                let snapshot = this.buffer.read(cx).read(cx);
14181                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14182                    for marked_range in &mut marked_ranges {
14183                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14184                        marked_range.start.0 += relative_range_utf16.start;
14185                        marked_range.start =
14186                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14187                        marked_range.end =
14188                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14189                    }
14190                }
14191                Some(marked_ranges)
14192            } else if let Some(range_utf16) = range_utf16 {
14193                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14194                Some(this.selection_replacement_ranges(range_utf16, cx))
14195            } else {
14196                None
14197            };
14198
14199            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14200                let newest_selection_id = this.selections.newest_anchor().id;
14201                this.selections
14202                    .all::<OffsetUtf16>(cx)
14203                    .iter()
14204                    .zip(ranges_to_replace.iter())
14205                    .find_map(|(selection, range)| {
14206                        if selection.id == newest_selection_id {
14207                            Some(
14208                                (range.start.0 as isize - selection.head().0 as isize)
14209                                    ..(range.end.0 as isize - selection.head().0 as isize),
14210                            )
14211                        } else {
14212                            None
14213                        }
14214                    })
14215            });
14216
14217            cx.emit(EditorEvent::InputHandled {
14218                utf16_range_to_replace: range_to_replace,
14219                text: text.into(),
14220            });
14221
14222            if let Some(ranges) = ranges_to_replace {
14223                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14224            }
14225
14226            let marked_ranges = {
14227                let snapshot = this.buffer.read(cx).read(cx);
14228                this.selections
14229                    .disjoint_anchors()
14230                    .iter()
14231                    .map(|selection| {
14232                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14233                    })
14234                    .collect::<Vec<_>>()
14235            };
14236
14237            if text.is_empty() {
14238                this.unmark_text(cx);
14239            } else {
14240                this.highlight_text::<InputComposition>(
14241                    marked_ranges.clone(),
14242                    HighlightStyle {
14243                        underline: Some(UnderlineStyle {
14244                            thickness: px(1.),
14245                            color: None,
14246                            wavy: false,
14247                        }),
14248                        ..Default::default()
14249                    },
14250                    cx,
14251                );
14252            }
14253
14254            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14255            let use_autoclose = this.use_autoclose;
14256            let use_auto_surround = this.use_auto_surround;
14257            this.set_use_autoclose(false);
14258            this.set_use_auto_surround(false);
14259            this.handle_input(text, cx);
14260            this.set_use_autoclose(use_autoclose);
14261            this.set_use_auto_surround(use_auto_surround);
14262
14263            if let Some(new_selected_range) = new_selected_range_utf16 {
14264                let snapshot = this.buffer.read(cx).read(cx);
14265                let new_selected_ranges = marked_ranges
14266                    .into_iter()
14267                    .map(|marked_range| {
14268                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14269                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14270                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14271                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14272                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14273                    })
14274                    .collect::<Vec<_>>();
14275
14276                drop(snapshot);
14277                this.change_selections(None, cx, |selections| {
14278                    selections.select_ranges(new_selected_ranges)
14279                });
14280            }
14281        });
14282
14283        self.ime_transaction = self.ime_transaction.or(transaction);
14284        if let Some(transaction) = self.ime_transaction {
14285            self.buffer.update(cx, |buffer, cx| {
14286                buffer.group_until_transaction(transaction, cx);
14287            });
14288        }
14289
14290        if self.text_highlights::<InputComposition>(cx).is_none() {
14291            self.ime_transaction.take();
14292        }
14293    }
14294
14295    fn bounds_for_range(
14296        &mut self,
14297        range_utf16: Range<usize>,
14298        element_bounds: gpui::Bounds<Pixels>,
14299        cx: &mut ViewContext<Self>,
14300    ) -> Option<gpui::Bounds<Pixels>> {
14301        let text_layout_details = self.text_layout_details(cx);
14302        let gpui::Point {
14303            x: em_width,
14304            y: line_height,
14305        } = self.character_size(cx);
14306
14307        let snapshot = self.snapshot(cx);
14308        let scroll_position = snapshot.scroll_position();
14309        let scroll_left = scroll_position.x * em_width;
14310
14311        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14312        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14313            + self.gutter_dimensions.width
14314            + self.gutter_dimensions.margin;
14315        let y = line_height * (start.row().as_f32() - scroll_position.y);
14316
14317        Some(Bounds {
14318            origin: element_bounds.origin + point(x, y),
14319            size: size(em_width, line_height),
14320        })
14321    }
14322}
14323
14324trait SelectionExt {
14325    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14326    fn spanned_rows(
14327        &self,
14328        include_end_if_at_line_start: bool,
14329        map: &DisplaySnapshot,
14330    ) -> Range<MultiBufferRow>;
14331}
14332
14333impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14334    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14335        let start = self
14336            .start
14337            .to_point(&map.buffer_snapshot)
14338            .to_display_point(map);
14339        let end = self
14340            .end
14341            .to_point(&map.buffer_snapshot)
14342            .to_display_point(map);
14343        if self.reversed {
14344            end..start
14345        } else {
14346            start..end
14347        }
14348    }
14349
14350    fn spanned_rows(
14351        &self,
14352        include_end_if_at_line_start: bool,
14353        map: &DisplaySnapshot,
14354    ) -> Range<MultiBufferRow> {
14355        let start = self.start.to_point(&map.buffer_snapshot);
14356        let mut end = self.end.to_point(&map.buffer_snapshot);
14357        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14358            end.row -= 1;
14359        }
14360
14361        let buffer_start = map.prev_line_boundary(start).0;
14362        let buffer_end = map.next_line_boundary(end).0;
14363        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14364    }
14365}
14366
14367impl<T: InvalidationRegion> InvalidationStack<T> {
14368    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14369    where
14370        S: Clone + ToOffset,
14371    {
14372        while let Some(region) = self.last() {
14373            let all_selections_inside_invalidation_ranges =
14374                if selections.len() == region.ranges().len() {
14375                    selections
14376                        .iter()
14377                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14378                        .all(|(selection, invalidation_range)| {
14379                            let head = selection.head().to_offset(buffer);
14380                            invalidation_range.start <= head && invalidation_range.end >= head
14381                        })
14382                } else {
14383                    false
14384                };
14385
14386            if all_selections_inside_invalidation_ranges {
14387                break;
14388            } else {
14389                self.pop();
14390            }
14391        }
14392    }
14393}
14394
14395impl<T> Default for InvalidationStack<T> {
14396    fn default() -> Self {
14397        Self(Default::default())
14398    }
14399}
14400
14401impl<T> Deref for InvalidationStack<T> {
14402    type Target = Vec<T>;
14403
14404    fn deref(&self) -> &Self::Target {
14405        &self.0
14406    }
14407}
14408
14409impl<T> DerefMut for InvalidationStack<T> {
14410    fn deref_mut(&mut self) -> &mut Self::Target {
14411        &mut self.0
14412    }
14413}
14414
14415impl InvalidationRegion for SnippetState {
14416    fn ranges(&self) -> &[Range<Anchor>] {
14417        &self.ranges[self.active_index]
14418    }
14419}
14420
14421pub fn diagnostic_block_renderer(
14422    diagnostic: Diagnostic,
14423    max_message_rows: Option<u8>,
14424    allow_closing: bool,
14425    _is_valid: bool,
14426) -> RenderBlock {
14427    let (text_without_backticks, code_ranges) =
14428        highlight_diagnostic_message(&diagnostic, max_message_rows);
14429
14430    Arc::new(move |cx: &mut BlockContext| {
14431        let group_id: SharedString = cx.block_id.to_string().into();
14432
14433        let mut text_style = cx.text_style().clone();
14434        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14435        let theme_settings = ThemeSettings::get_global(cx);
14436        text_style.font_family = theme_settings.buffer_font.family.clone();
14437        text_style.font_style = theme_settings.buffer_font.style;
14438        text_style.font_features = theme_settings.buffer_font.features.clone();
14439        text_style.font_weight = theme_settings.buffer_font.weight;
14440
14441        let multi_line_diagnostic = diagnostic.message.contains('\n');
14442
14443        let buttons = |diagnostic: &Diagnostic| {
14444            if multi_line_diagnostic {
14445                v_flex()
14446            } else {
14447                h_flex()
14448            }
14449            .when(allow_closing, |div| {
14450                div.children(diagnostic.is_primary.then(|| {
14451                    IconButton::new("close-block", IconName::XCircle)
14452                        .icon_color(Color::Muted)
14453                        .size(ButtonSize::Compact)
14454                        .style(ButtonStyle::Transparent)
14455                        .visible_on_hover(group_id.clone())
14456                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14457                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14458                }))
14459            })
14460            .child(
14461                IconButton::new("copy-block", IconName::Copy)
14462                    .icon_color(Color::Muted)
14463                    .size(ButtonSize::Compact)
14464                    .style(ButtonStyle::Transparent)
14465                    .visible_on_hover(group_id.clone())
14466                    .on_click({
14467                        let message = diagnostic.message.clone();
14468                        move |_click, cx| {
14469                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14470                        }
14471                    })
14472                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14473            )
14474        };
14475
14476        let icon_size = buttons(&diagnostic)
14477            .into_any_element()
14478            .layout_as_root(AvailableSpace::min_size(), cx);
14479
14480        h_flex()
14481            .id(cx.block_id)
14482            .group(group_id.clone())
14483            .relative()
14484            .size_full()
14485            .block_mouse_down()
14486            .pl(cx.gutter_dimensions.width)
14487            .w(cx.max_width - cx.gutter_dimensions.full_width())
14488            .child(
14489                div()
14490                    .flex()
14491                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14492                    .flex_shrink(),
14493            )
14494            .child(buttons(&diagnostic))
14495            .child(div().flex().flex_shrink_0().child(
14496                StyledText::new(text_without_backticks.clone()).with_highlights(
14497                    &text_style,
14498                    code_ranges.iter().map(|range| {
14499                        (
14500                            range.clone(),
14501                            HighlightStyle {
14502                                font_weight: Some(FontWeight::BOLD),
14503                                ..Default::default()
14504                            },
14505                        )
14506                    }),
14507                ),
14508            ))
14509            .into_any_element()
14510    })
14511}
14512
14513pub fn highlight_diagnostic_message(
14514    diagnostic: &Diagnostic,
14515    mut max_message_rows: Option<u8>,
14516) -> (SharedString, Vec<Range<usize>>) {
14517    let mut text_without_backticks = String::new();
14518    let mut code_ranges = Vec::new();
14519
14520    if let Some(source) = &diagnostic.source {
14521        text_without_backticks.push_str(source);
14522        code_ranges.push(0..source.len());
14523        text_without_backticks.push_str(": ");
14524    }
14525
14526    let mut prev_offset = 0;
14527    let mut in_code_block = false;
14528    let has_row_limit = max_message_rows.is_some();
14529    let mut newline_indices = diagnostic
14530        .message
14531        .match_indices('\n')
14532        .filter(|_| has_row_limit)
14533        .map(|(ix, _)| ix)
14534        .fuse()
14535        .peekable();
14536
14537    for (quote_ix, _) in diagnostic
14538        .message
14539        .match_indices('`')
14540        .chain([(diagnostic.message.len(), "")])
14541    {
14542        let mut first_newline_ix = None;
14543        let mut last_newline_ix = None;
14544        while let Some(newline_ix) = newline_indices.peek() {
14545            if *newline_ix < quote_ix {
14546                if first_newline_ix.is_none() {
14547                    first_newline_ix = Some(*newline_ix);
14548                }
14549                last_newline_ix = Some(*newline_ix);
14550
14551                if let Some(rows_left) = &mut max_message_rows {
14552                    if *rows_left == 0 {
14553                        break;
14554                    } else {
14555                        *rows_left -= 1;
14556                    }
14557                }
14558                let _ = newline_indices.next();
14559            } else {
14560                break;
14561            }
14562        }
14563        let prev_len = text_without_backticks.len();
14564        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14565        text_without_backticks.push_str(new_text);
14566        if in_code_block {
14567            code_ranges.push(prev_len..text_without_backticks.len());
14568        }
14569        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14570        in_code_block = !in_code_block;
14571        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14572            text_without_backticks.push_str("...");
14573            break;
14574        }
14575    }
14576
14577    (text_without_backticks.into(), code_ranges)
14578}
14579
14580fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14581    match severity {
14582        DiagnosticSeverity::ERROR => colors.error,
14583        DiagnosticSeverity::WARNING => colors.warning,
14584        DiagnosticSeverity::INFORMATION => colors.info,
14585        DiagnosticSeverity::HINT => colors.info,
14586        _ => colors.ignored,
14587    }
14588}
14589
14590pub fn styled_runs_for_code_label<'a>(
14591    label: &'a CodeLabel,
14592    syntax_theme: &'a theme::SyntaxTheme,
14593) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14594    let fade_out = HighlightStyle {
14595        fade_out: Some(0.35),
14596        ..Default::default()
14597    };
14598
14599    let mut prev_end = label.filter_range.end;
14600    label
14601        .runs
14602        .iter()
14603        .enumerate()
14604        .flat_map(move |(ix, (range, highlight_id))| {
14605            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14606                style
14607            } else {
14608                return Default::default();
14609            };
14610            let mut muted_style = style;
14611            muted_style.highlight(fade_out);
14612
14613            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14614            if range.start >= label.filter_range.end {
14615                if range.start > prev_end {
14616                    runs.push((prev_end..range.start, fade_out));
14617                }
14618                runs.push((range.clone(), muted_style));
14619            } else if range.end <= label.filter_range.end {
14620                runs.push((range.clone(), style));
14621            } else {
14622                runs.push((range.start..label.filter_range.end, style));
14623                runs.push((label.filter_range.end..range.end, muted_style));
14624            }
14625            prev_end = cmp::max(prev_end, range.end);
14626
14627            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14628                runs.push((prev_end..label.text.len(), fade_out));
14629            }
14630
14631            runs
14632        })
14633}
14634
14635pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14636    let mut prev_index = 0;
14637    let mut prev_codepoint: Option<char> = None;
14638    text.char_indices()
14639        .chain([(text.len(), '\0')])
14640        .filter_map(move |(index, codepoint)| {
14641            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14642            let is_boundary = index == text.len()
14643                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14644                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14645            if is_boundary {
14646                let chunk = &text[prev_index..index];
14647                prev_index = index;
14648                Some(chunk)
14649            } else {
14650                None
14651            }
14652        })
14653}
14654
14655pub trait RangeToAnchorExt: Sized {
14656    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14657
14658    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14659        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14660        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14661    }
14662}
14663
14664impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14665    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14666        let start_offset = self.start.to_offset(snapshot);
14667        let end_offset = self.end.to_offset(snapshot);
14668        if start_offset == end_offset {
14669            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14670        } else {
14671            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14672        }
14673    }
14674}
14675
14676pub trait RowExt {
14677    fn as_f32(&self) -> f32;
14678
14679    fn next_row(&self) -> Self;
14680
14681    fn previous_row(&self) -> Self;
14682
14683    fn minus(&self, other: Self) -> u32;
14684}
14685
14686impl RowExt for DisplayRow {
14687    fn as_f32(&self) -> f32 {
14688        self.0 as f32
14689    }
14690
14691    fn next_row(&self) -> Self {
14692        Self(self.0 + 1)
14693    }
14694
14695    fn previous_row(&self) -> Self {
14696        Self(self.0.saturating_sub(1))
14697    }
14698
14699    fn minus(&self, other: Self) -> u32 {
14700        self.0 - other.0
14701    }
14702}
14703
14704impl RowExt for MultiBufferRow {
14705    fn as_f32(&self) -> f32 {
14706        self.0 as f32
14707    }
14708
14709    fn next_row(&self) -> Self {
14710        Self(self.0 + 1)
14711    }
14712
14713    fn previous_row(&self) -> Self {
14714        Self(self.0.saturating_sub(1))
14715    }
14716
14717    fn minus(&self, other: Self) -> u32 {
14718        self.0 - other.0
14719    }
14720}
14721
14722trait RowRangeExt {
14723    type Row;
14724
14725    fn len(&self) -> usize;
14726
14727    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14728}
14729
14730impl RowRangeExt for Range<MultiBufferRow> {
14731    type Row = MultiBufferRow;
14732
14733    fn len(&self) -> usize {
14734        (self.end.0 - self.start.0) as usize
14735    }
14736
14737    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14738        (self.start.0..self.end.0).map(MultiBufferRow)
14739    }
14740}
14741
14742impl RowRangeExt for Range<DisplayRow> {
14743    type Row = DisplayRow;
14744
14745    fn len(&self) -> usize {
14746        (self.end.0 - self.start.0) as usize
14747    }
14748
14749    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14750        (self.start.0..self.end.0).map(DisplayRow)
14751    }
14752}
14753
14754fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14755    if hunk.diff_base_byte_range.is_empty() {
14756        DiffHunkStatus::Added
14757    } else if hunk.row_range.is_empty() {
14758        DiffHunkStatus::Removed
14759    } else {
14760        DiffHunkStatus::Modified
14761    }
14762}
14763
14764/// If select range has more than one line, we
14765/// just point the cursor to range.start.
14766fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14767    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14768        range
14769    } else {
14770        range.start..range.start
14771    }
14772}
14773
14774pub struct KillRing(ClipboardItem);
14775impl Global for KillRing {}
14776
14777const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);