editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51use ::git::diff::DiffHunkStatus;
   52pub(crate) use actions::*;
   53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{anyhow, Context as _, Result};
   56use blink_manager::BlinkManager;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::StringMatchCandidate;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   87    WeakView, WindowContext,
   88};
   89use highlight_matching_bracket::refresh_matching_bracket_highlights;
   90use hover_popover::{hide_hover, HoverState};
   91pub(crate) use hunk_diff::HoveredHunk;
   92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
  103    Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
  132    project_settings::{GitGutterSetting, ProjectSettings},
  133    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  134    LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  135};
  136use rand::prelude::*;
  137use rpc::{proto::*, ErrorExt};
  138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  139use selections_collection::{
  140    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  141};
  142use serde::{Deserialize, Serialize};
  143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  144use smallvec::SmallVec;
  145use snippet::Snippet;
  146use std::{
  147    any::TypeId,
  148    borrow::Cow,
  149    cell::RefCell,
  150    cmp::{self, Ordering, Reverse},
  151    mem,
  152    num::NonZeroU32,
  153    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  154    path::{Path, PathBuf},
  155    rc::Rc,
  156    sync::Arc,
  157    time::{Duration, Instant},
  158};
  159pub use sum_tree::Bias;
  160use sum_tree::TreeMap;
  161use text::{BufferId, OffsetUtf16, Rope};
  162use theme::{
  163    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  164    ThemeColors, ThemeSettings,
  165};
  166use ui::{
  167    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  168    PopoverMenuHandle, Tooltip,
  169};
  170use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  171use workspace::item::{ItemHandle, PreviewTabsSettings};
  172use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  173use workspace::{
  174    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  175};
  176use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  177
  178use crate::hover_links::{find_url, find_url_from_range};
  179use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  180
  181pub const FILE_HEADER_HEIGHT: u32 = 2;
  182pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  183pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  184pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  185const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  186const MAX_LINE_LEN: usize = 1024;
  187const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  188const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  189pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  190#[doc(hidden)]
  191pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  192
  193pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  194pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  195
  196pub fn render_parsed_markdown(
  197    element_id: impl Into<ElementId>,
  198    parsed: &language::ParsedMarkdown,
  199    editor_style: &EditorStyle,
  200    workspace: Option<WeakView<Workspace>>,
  201    cx: &mut WindowContext,
  202) -> InteractiveText {
  203    let code_span_background_color = cx
  204        .theme()
  205        .colors()
  206        .editor_document_highlight_read_background;
  207
  208    let highlights = gpui::combine_highlights(
  209        parsed.highlights.iter().filter_map(|(range, highlight)| {
  210            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  211            Some((range.clone(), highlight))
  212        }),
  213        parsed
  214            .regions
  215            .iter()
  216            .zip(&parsed.region_ranges)
  217            .filter_map(|(region, range)| {
  218                if region.code {
  219                    Some((
  220                        range.clone(),
  221                        HighlightStyle {
  222                            background_color: Some(code_span_background_color),
  223                            ..Default::default()
  224                        },
  225                    ))
  226                } else {
  227                    None
  228                }
  229            }),
  230    );
  231
  232    let mut links = Vec::new();
  233    let mut link_ranges = Vec::new();
  234    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  235        if let Some(link) = region.link.clone() {
  236            links.push(link);
  237            link_ranges.push(range.clone());
  238        }
  239    }
  240
  241    InteractiveText::new(
  242        element_id,
  243        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  244    )
  245    .on_click(link_ranges, move |clicked_range_ix, cx| {
  246        match &links[clicked_range_ix] {
  247            markdown::Link::Web { url } => cx.open_url(url),
  248            markdown::Link::Path { path } => {
  249                if let Some(workspace) = &workspace {
  250                    _ = workspace.update(cx, |workspace, cx| {
  251                        workspace.open_abs_path(path.clone(), false, cx).detach();
  252                    });
  253                }
  254            }
  255        }
  256    })
  257}
  258
  259#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  260pub(crate) enum InlayId {
  261    InlineCompletion(usize),
  262    Hint(usize),
  263}
  264
  265impl InlayId {
  266    fn id(&self) -> usize {
  267        match self {
  268            Self::InlineCompletion(id) => *id,
  269            Self::Hint(id) => *id,
  270        }
  271    }
  272}
  273
  274enum DiffRowHighlight {}
  275enum DocumentHighlightRead {}
  276enum DocumentHighlightWrite {}
  277enum InputComposition {}
  278
  279#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  280pub enum Navigated {
  281    Yes,
  282    No,
  283}
  284
  285impl Navigated {
  286    pub fn from_bool(yes: bool) -> Navigated {
  287        if yes {
  288            Navigated::Yes
  289        } else {
  290            Navigated::No
  291        }
  292    }
  293}
  294
  295pub fn init_settings(cx: &mut AppContext) {
  296    EditorSettings::register(cx);
  297}
  298
  299pub fn init(cx: &mut AppContext) {
  300    init_settings(cx);
  301
  302    workspace::register_project_item::<Editor>(cx);
  303    workspace::FollowableViewRegistry::register::<Editor>(cx);
  304    workspace::register_serializable_item::<Editor>(cx);
  305
  306    cx.observe_new_views(
  307        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  308            workspace.register_action(Editor::new_file);
  309            workspace.register_action(Editor::new_file_vertical);
  310            workspace.register_action(Editor::new_file_horizontal);
  311        },
  312    )
  313    .detach();
  314
  315    cx.on_action(move |_: &workspace::NewFile, cx| {
  316        let app_state = workspace::AppState::global(cx);
  317        if let Some(app_state) = app_state.upgrade() {
  318            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  319                Editor::new_file(workspace, &Default::default(), cx)
  320            })
  321            .detach();
  322        }
  323    });
  324    cx.on_action(move |_: &workspace::NewWindow, cx| {
  325        let app_state = workspace::AppState::global(cx);
  326        if let Some(app_state) = app_state.upgrade() {
  327            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  328                Editor::new_file(workspace, &Default::default(), cx)
  329            })
  330            .detach();
  331        }
  332    });
  333    git::project_diff::init(cx);
  334}
  335
  336pub struct SearchWithinRange;
  337
  338trait InvalidationRegion {
  339    fn ranges(&self) -> &[Range<Anchor>];
  340}
  341
  342#[derive(Clone, Debug, PartialEq)]
  343pub enum SelectPhase {
  344    Begin {
  345        position: DisplayPoint,
  346        add: bool,
  347        click_count: usize,
  348    },
  349    BeginColumnar {
  350        position: DisplayPoint,
  351        reset: bool,
  352        goal_column: u32,
  353    },
  354    Extend {
  355        position: DisplayPoint,
  356        click_count: usize,
  357    },
  358    Update {
  359        position: DisplayPoint,
  360        goal_column: u32,
  361        scroll_delta: gpui::Point<f32>,
  362    },
  363    End,
  364}
  365
  366#[derive(Clone, Debug)]
  367pub enum SelectMode {
  368    Character,
  369    Word(Range<Anchor>),
  370    Line(Range<Anchor>),
  371    All,
  372}
  373
  374#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  375pub enum EditorMode {
  376    SingleLine { auto_width: bool },
  377    AutoHeight { max_lines: usize },
  378    Full,
  379}
  380
  381#[derive(Copy, Clone, Debug)]
  382pub enum SoftWrap {
  383    /// Prefer not to wrap at all.
  384    ///
  385    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  386    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  387    GitDiff,
  388    /// Prefer a single line generally, unless an overly long line is encountered.
  389    None,
  390    /// Soft wrap lines that exceed the editor width.
  391    EditorWidth,
  392    /// Soft wrap lines at the preferred line length.
  393    Column(u32),
  394    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  395    Bounded(u32),
  396}
  397
  398#[derive(Clone)]
  399pub struct EditorStyle {
  400    pub background: Hsla,
  401    pub local_player: PlayerColor,
  402    pub text: TextStyle,
  403    pub scrollbar_width: Pixels,
  404    pub syntax: Arc<SyntaxTheme>,
  405    pub status: StatusColors,
  406    pub inlay_hints_style: HighlightStyle,
  407    pub inline_completion_styles: InlineCompletionStyles,
  408    pub unnecessary_code_fade: f32,
  409}
  410
  411impl Default for EditorStyle {
  412    fn default() -> Self {
  413        Self {
  414            background: Hsla::default(),
  415            local_player: PlayerColor::default(),
  416            text: TextStyle::default(),
  417            scrollbar_width: Pixels::default(),
  418            syntax: Default::default(),
  419            // HACK: Status colors don't have a real default.
  420            // We should look into removing the status colors from the editor
  421            // style and retrieve them directly from the theme.
  422            status: StatusColors::dark(),
  423            inlay_hints_style: HighlightStyle::default(),
  424            inline_completion_styles: InlineCompletionStyles {
  425                insertion: HighlightStyle::default(),
  426                whitespace: HighlightStyle::default(),
  427            },
  428            unnecessary_code_fade: Default::default(),
  429        }
  430    }
  431}
  432
  433pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  434    let show_background = language_settings::language_settings(None, None, cx)
  435        .inlay_hints
  436        .show_background;
  437
  438    HighlightStyle {
  439        color: Some(cx.theme().status().hint),
  440        background_color: show_background.then(|| cx.theme().status().hint_background),
  441        ..HighlightStyle::default()
  442    }
  443}
  444
  445pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  446    InlineCompletionStyles {
  447        insertion: HighlightStyle {
  448            color: Some(cx.theme().status().predictive),
  449            ..HighlightStyle::default()
  450        },
  451        whitespace: HighlightStyle {
  452            background_color: Some(cx.theme().status().created_background),
  453            ..HighlightStyle::default()
  454        },
  455    }
  456}
  457
  458type CompletionId = usize;
  459
  460enum InlineCompletion {
  461    Edit(Vec<(Range<Anchor>, String)>),
  462    Move(Anchor),
  463}
  464
  465struct InlineCompletionState {
  466    inlay_ids: Vec<InlayId>,
  467    completion: InlineCompletion,
  468    invalidation_range: Range<Anchor>,
  469}
  470
  471enum InlineCompletionHighlight {}
  472
  473#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  474struct EditorActionId(usize);
  475
  476impl EditorActionId {
  477    pub fn post_inc(&mut self) -> Self {
  478        let answer = self.0;
  479
  480        *self = Self(answer + 1);
  481
  482        Self(answer)
  483    }
  484}
  485
  486// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  487// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  488
  489type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  490type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  491
  492#[derive(Default)]
  493struct ScrollbarMarkerState {
  494    scrollbar_size: Size<Pixels>,
  495    dirty: bool,
  496    markers: Arc<[PaintQuad]>,
  497    pending_refresh: Option<Task<Result<()>>>,
  498}
  499
  500impl ScrollbarMarkerState {
  501    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  502        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  503    }
  504}
  505
  506#[derive(Clone, Debug)]
  507struct RunnableTasks {
  508    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  509    offset: MultiBufferOffset,
  510    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  511    column: u32,
  512    // Values of all named captures, including those starting with '_'
  513    extra_variables: HashMap<String, String>,
  514    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  515    context_range: Range<BufferOffset>,
  516}
  517
  518impl RunnableTasks {
  519    fn resolve<'a>(
  520        &'a self,
  521        cx: &'a task::TaskContext,
  522    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  523        self.templates.iter().filter_map(|(kind, template)| {
  524            template
  525                .resolve_task(&kind.to_id_base(), cx)
  526                .map(|task| (kind.clone(), task))
  527        })
  528    }
  529}
  530
  531#[derive(Clone)]
  532struct ResolvedTasks {
  533    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  534    position: Anchor,
  535}
  536#[derive(Copy, Clone, Debug)]
  537struct MultiBufferOffset(usize);
  538#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  539struct BufferOffset(usize);
  540
  541// Addons allow storing per-editor state in other crates (e.g. Vim)
  542pub trait Addon: 'static {
  543    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  544
  545    fn to_any(&self) -> &dyn std::any::Any;
  546}
  547
  548#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  549pub enum IsVimMode {
  550    Yes,
  551    No,
  552}
  553
  554/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  555///
  556/// See the [module level documentation](self) for more information.
  557pub struct Editor {
  558    focus_handle: FocusHandle,
  559    last_focused_descendant: Option<WeakFocusHandle>,
  560    /// The text buffer being edited
  561    buffer: Model<MultiBuffer>,
  562    /// Map of how text in the buffer should be displayed.
  563    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  564    pub display_map: Model<DisplayMap>,
  565    pub selections: SelectionsCollection,
  566    pub scroll_manager: ScrollManager,
  567    /// When inline assist editors are linked, they all render cursors because
  568    /// typing enters text into each of them, even the ones that aren't focused.
  569    pub(crate) show_cursor_when_unfocused: bool,
  570    columnar_selection_tail: Option<Anchor>,
  571    add_selections_state: Option<AddSelectionsState>,
  572    select_next_state: Option<SelectNextState>,
  573    select_prev_state: Option<SelectNextState>,
  574    selection_history: SelectionHistory,
  575    autoclose_regions: Vec<AutocloseRegion>,
  576    snippet_stack: InvalidationStack<SnippetState>,
  577    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  578    ime_transaction: Option<TransactionId>,
  579    active_diagnostics: Option<ActiveDiagnosticGroup>,
  580    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  581
  582    project: Option<Model<Project>>,
  583    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  584    completion_provider: Option<Box<dyn CompletionProvider>>,
  585    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  586    blink_manager: Model<BlinkManager>,
  587    show_cursor_names: bool,
  588    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  589    pub show_local_selections: bool,
  590    mode: EditorMode,
  591    show_breadcrumbs: bool,
  592    show_gutter: bool,
  593    show_line_numbers: Option<bool>,
  594    use_relative_line_numbers: Option<bool>,
  595    show_git_diff_gutter: Option<bool>,
  596    show_code_actions: Option<bool>,
  597    show_runnables: Option<bool>,
  598    show_wrap_guides: Option<bool>,
  599    show_indent_guides: Option<bool>,
  600    placeholder_text: Option<Arc<str>>,
  601    highlight_order: usize,
  602    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  603    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  604    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  605    scrollbar_marker_state: ScrollbarMarkerState,
  606    active_indent_guides_state: ActiveIndentGuidesState,
  607    nav_history: Option<ItemNavHistory>,
  608    context_menu: RefCell<Option<CodeContextMenu>>,
  609    mouse_context_menu: Option<MouseContextMenu>,
  610    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  611    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  612    signature_help_state: SignatureHelpState,
  613    auto_signature_help: Option<bool>,
  614    find_all_references_task_sources: Vec<Anchor>,
  615    next_completion_id: CompletionId,
  616    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  617    code_actions_task: Option<Task<Result<()>>>,
  618    document_highlights_task: Option<Task<()>>,
  619    linked_editing_range_task: Option<Task<Option<()>>>,
  620    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  621    pending_rename: Option<RenameState>,
  622    searchable: bool,
  623    cursor_shape: CursorShape,
  624    current_line_highlight: Option<CurrentLineHighlight>,
  625    collapse_matches: bool,
  626    autoindent_mode: Option<AutoindentMode>,
  627    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  628    input_enabled: bool,
  629    use_modal_editing: bool,
  630    read_only: bool,
  631    leader_peer_id: Option<PeerId>,
  632    remote_id: Option<ViewId>,
  633    hover_state: HoverState,
  634    gutter_hovered: bool,
  635    hovered_link_state: Option<HoveredLinkState>,
  636    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  637    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  638    active_inline_completion: Option<InlineCompletionState>,
  639    // enable_inline_completions is a switch that Vim can use to disable
  640    // inline completions based on its mode.
  641    enable_inline_completions: bool,
  642    show_inline_completions_override: Option<bool>,
  643    inlay_hint_cache: InlayHintCache,
  644    diff_map: DiffMap,
  645    next_inlay_id: usize,
  646    _subscriptions: Vec<Subscription>,
  647    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  648    gutter_dimensions: GutterDimensions,
  649    style: Option<EditorStyle>,
  650    text_style_refinement: Option<TextStyleRefinement>,
  651    next_editor_action_id: EditorActionId,
  652    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  653    use_autoclose: bool,
  654    use_auto_surround: bool,
  655    auto_replace_emoji_shortcode: bool,
  656    show_git_blame_gutter: bool,
  657    show_git_blame_inline: bool,
  658    show_git_blame_inline_delay_task: Option<Task<()>>,
  659    git_blame_inline_enabled: bool,
  660    serialize_dirty_buffers: bool,
  661    show_selection_menu: Option<bool>,
  662    blame: Option<Model<GitBlame>>,
  663    blame_subscription: Option<Subscription>,
  664    custom_context_menu: Option<
  665        Box<
  666            dyn 'static
  667                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  668        >,
  669    >,
  670    last_bounds: Option<Bounds<Pixels>>,
  671    expect_bounds_change: Option<Bounds<Pixels>>,
  672    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  673    tasks_update_task: Option<Task<()>>,
  674    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  675    breadcrumb_header: Option<String>,
  676    focused_block: Option<FocusedBlock>,
  677    next_scroll_position: NextScrollCursorCenterTopBottom,
  678    addons: HashMap<TypeId, Box<dyn Addon>>,
  679    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  680    toggle_fold_multiple_buffers: Task<()>,
  681    _scroll_cursor_center_top_bottom_task: Task<()>,
  682}
  683
  684#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  685enum NextScrollCursorCenterTopBottom {
  686    #[default]
  687    Center,
  688    Top,
  689    Bottom,
  690}
  691
  692impl NextScrollCursorCenterTopBottom {
  693    fn next(&self) -> Self {
  694        match self {
  695            Self::Center => Self::Top,
  696            Self::Top => Self::Bottom,
  697            Self::Bottom => Self::Center,
  698        }
  699    }
  700}
  701
  702#[derive(Clone)]
  703pub struct EditorSnapshot {
  704    pub mode: EditorMode,
  705    show_gutter: bool,
  706    show_line_numbers: Option<bool>,
  707    show_git_diff_gutter: Option<bool>,
  708    show_code_actions: Option<bool>,
  709    show_runnables: Option<bool>,
  710    git_blame_gutter_max_author_length: Option<usize>,
  711    pub display_snapshot: DisplaySnapshot,
  712    pub placeholder_text: Option<Arc<str>>,
  713    diff_map: DiffMapSnapshot,
  714    is_focused: bool,
  715    scroll_anchor: ScrollAnchor,
  716    ongoing_scroll: OngoingScroll,
  717    current_line_highlight: CurrentLineHighlight,
  718    gutter_hovered: bool,
  719}
  720
  721const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  722
  723#[derive(Default, Debug, Clone, Copy)]
  724pub struct GutterDimensions {
  725    pub left_padding: Pixels,
  726    pub right_padding: Pixels,
  727    pub width: Pixels,
  728    pub margin: Pixels,
  729    pub git_blame_entries_width: Option<Pixels>,
  730}
  731
  732impl GutterDimensions {
  733    /// The full width of the space taken up by the gutter.
  734    pub fn full_width(&self) -> Pixels {
  735        self.margin + self.width
  736    }
  737
  738    /// The width of the space reserved for the fold indicators,
  739    /// use alongside 'justify_end' and `gutter_width` to
  740    /// right align content with the line numbers
  741    pub fn fold_area_width(&self) -> Pixels {
  742        self.margin + self.right_padding
  743    }
  744}
  745
  746#[derive(Debug)]
  747pub struct RemoteSelection {
  748    pub replica_id: ReplicaId,
  749    pub selection: Selection<Anchor>,
  750    pub cursor_shape: CursorShape,
  751    pub peer_id: PeerId,
  752    pub line_mode: bool,
  753    pub participant_index: Option<ParticipantIndex>,
  754    pub user_name: Option<SharedString>,
  755}
  756
  757#[derive(Clone, Debug)]
  758struct SelectionHistoryEntry {
  759    selections: Arc<[Selection<Anchor>]>,
  760    select_next_state: Option<SelectNextState>,
  761    select_prev_state: Option<SelectNextState>,
  762    add_selections_state: Option<AddSelectionsState>,
  763}
  764
  765enum SelectionHistoryMode {
  766    Normal,
  767    Undoing,
  768    Redoing,
  769}
  770
  771#[derive(Clone, PartialEq, Eq, Hash)]
  772struct HoveredCursor {
  773    replica_id: u16,
  774    selection_id: usize,
  775}
  776
  777impl Default for SelectionHistoryMode {
  778    fn default() -> Self {
  779        Self::Normal
  780    }
  781}
  782
  783#[derive(Default)]
  784struct SelectionHistory {
  785    #[allow(clippy::type_complexity)]
  786    selections_by_transaction:
  787        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  788    mode: SelectionHistoryMode,
  789    undo_stack: VecDeque<SelectionHistoryEntry>,
  790    redo_stack: VecDeque<SelectionHistoryEntry>,
  791}
  792
  793impl SelectionHistory {
  794    fn insert_transaction(
  795        &mut self,
  796        transaction_id: TransactionId,
  797        selections: Arc<[Selection<Anchor>]>,
  798    ) {
  799        self.selections_by_transaction
  800            .insert(transaction_id, (selections, None));
  801    }
  802
  803    #[allow(clippy::type_complexity)]
  804    fn transaction(
  805        &self,
  806        transaction_id: TransactionId,
  807    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  808        self.selections_by_transaction.get(&transaction_id)
  809    }
  810
  811    #[allow(clippy::type_complexity)]
  812    fn transaction_mut(
  813        &mut self,
  814        transaction_id: TransactionId,
  815    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  816        self.selections_by_transaction.get_mut(&transaction_id)
  817    }
  818
  819    fn push(&mut self, entry: SelectionHistoryEntry) {
  820        if !entry.selections.is_empty() {
  821            match self.mode {
  822                SelectionHistoryMode::Normal => {
  823                    self.push_undo(entry);
  824                    self.redo_stack.clear();
  825                }
  826                SelectionHistoryMode::Undoing => self.push_redo(entry),
  827                SelectionHistoryMode::Redoing => self.push_undo(entry),
  828            }
  829        }
  830    }
  831
  832    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  833        if self
  834            .undo_stack
  835            .back()
  836            .map_or(true, |e| e.selections != entry.selections)
  837        {
  838            self.undo_stack.push_back(entry);
  839            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  840                self.undo_stack.pop_front();
  841            }
  842        }
  843    }
  844
  845    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  846        if self
  847            .redo_stack
  848            .back()
  849            .map_or(true, |e| e.selections != entry.selections)
  850        {
  851            self.redo_stack.push_back(entry);
  852            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  853                self.redo_stack.pop_front();
  854            }
  855        }
  856    }
  857}
  858
  859struct RowHighlight {
  860    index: usize,
  861    range: Range<Anchor>,
  862    color: Hsla,
  863    should_autoscroll: bool,
  864}
  865
  866#[derive(Clone, Debug)]
  867struct AddSelectionsState {
  868    above: bool,
  869    stack: Vec<usize>,
  870}
  871
  872#[derive(Clone)]
  873struct SelectNextState {
  874    query: AhoCorasick,
  875    wordwise: bool,
  876    done: bool,
  877}
  878
  879impl std::fmt::Debug for SelectNextState {
  880    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  881        f.debug_struct(std::any::type_name::<Self>())
  882            .field("wordwise", &self.wordwise)
  883            .field("done", &self.done)
  884            .finish()
  885    }
  886}
  887
  888#[derive(Debug)]
  889struct AutocloseRegion {
  890    selection_id: usize,
  891    range: Range<Anchor>,
  892    pair: BracketPair,
  893}
  894
  895#[derive(Debug)]
  896struct SnippetState {
  897    ranges: Vec<Vec<Range<Anchor>>>,
  898    active_index: usize,
  899    choices: Vec<Option<Vec<String>>>,
  900}
  901
  902#[doc(hidden)]
  903pub struct RenameState {
  904    pub range: Range<Anchor>,
  905    pub old_name: Arc<str>,
  906    pub editor: View<Editor>,
  907    block_id: CustomBlockId,
  908}
  909
  910struct InvalidationStack<T>(Vec<T>);
  911
  912struct RegisteredInlineCompletionProvider {
  913    provider: Arc<dyn InlineCompletionProviderHandle>,
  914    _subscription: Subscription,
  915}
  916
  917#[derive(Debug)]
  918struct ActiveDiagnosticGroup {
  919    primary_range: Range<Anchor>,
  920    primary_message: String,
  921    group_id: usize,
  922    blocks: HashMap<CustomBlockId, Diagnostic>,
  923    is_valid: bool,
  924}
  925
  926#[derive(Serialize, Deserialize, Clone, Debug)]
  927pub struct ClipboardSelection {
  928    pub len: usize,
  929    pub is_entire_line: bool,
  930    pub first_line_indent: u32,
  931}
  932
  933#[derive(Debug)]
  934pub(crate) struct NavigationData {
  935    cursor_anchor: Anchor,
  936    cursor_position: Point,
  937    scroll_anchor: ScrollAnchor,
  938    scroll_top_row: u32,
  939}
  940
  941#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  942pub enum GotoDefinitionKind {
  943    Symbol,
  944    Declaration,
  945    Type,
  946    Implementation,
  947}
  948
  949#[derive(Debug, Clone)]
  950enum InlayHintRefreshReason {
  951    Toggle(bool),
  952    SettingsChange(InlayHintSettings),
  953    NewLinesShown,
  954    BufferEdited(HashSet<Arc<Language>>),
  955    RefreshRequested,
  956    ExcerptsRemoved(Vec<ExcerptId>),
  957}
  958
  959impl InlayHintRefreshReason {
  960    fn description(&self) -> &'static str {
  961        match self {
  962            Self::Toggle(_) => "toggle",
  963            Self::SettingsChange(_) => "settings change",
  964            Self::NewLinesShown => "new lines shown",
  965            Self::BufferEdited(_) => "buffer edited",
  966            Self::RefreshRequested => "refresh requested",
  967            Self::ExcerptsRemoved(_) => "excerpts removed",
  968        }
  969    }
  970}
  971
  972pub(crate) struct FocusedBlock {
  973    id: BlockId,
  974    focus_handle: WeakFocusHandle,
  975}
  976
  977#[derive(Clone)]
  978struct JumpData {
  979    excerpt_id: ExcerptId,
  980    position: Point,
  981    anchor: text::Anchor,
  982    path: Option<project::ProjectPath>,
  983    line_offset_from_top: u32,
  984}
  985
  986impl Editor {
  987    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
  988        let buffer = cx.new_model(|cx| Buffer::local("", cx));
  989        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
  990        Self::new(
  991            EditorMode::SingleLine { auto_width: false },
  992            buffer,
  993            None,
  994            false,
  995            cx,
  996        )
  997    }
  998
  999    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1000        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1001        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1002        Self::new(EditorMode::Full, buffer, None, false, cx)
 1003    }
 1004
 1005    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1006        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1007        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1008        Self::new(
 1009            EditorMode::SingleLine { auto_width: true },
 1010            buffer,
 1011            None,
 1012            false,
 1013            cx,
 1014        )
 1015    }
 1016
 1017    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1018        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1019        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1020        Self::new(
 1021            EditorMode::AutoHeight { max_lines },
 1022            buffer,
 1023            None,
 1024            false,
 1025            cx,
 1026        )
 1027    }
 1028
 1029    pub fn for_buffer(
 1030        buffer: Model<Buffer>,
 1031        project: Option<Model<Project>>,
 1032        cx: &mut ViewContext<Self>,
 1033    ) -> Self {
 1034        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1035        Self::new(EditorMode::Full, buffer, project, false, cx)
 1036    }
 1037
 1038    pub fn for_multibuffer(
 1039        buffer: Model<MultiBuffer>,
 1040        project: Option<Model<Project>>,
 1041        show_excerpt_controls: bool,
 1042        cx: &mut ViewContext<Self>,
 1043    ) -> Self {
 1044        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1045    }
 1046
 1047    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1048        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1049        let mut clone = Self::new(
 1050            self.mode,
 1051            self.buffer.clone(),
 1052            self.project.clone(),
 1053            show_excerpt_controls,
 1054            cx,
 1055        );
 1056        self.display_map.update(cx, |display_map, cx| {
 1057            let snapshot = display_map.snapshot(cx);
 1058            clone.display_map.update(cx, |display_map, cx| {
 1059                display_map.set_state(&snapshot, cx);
 1060            });
 1061        });
 1062        clone.selections.clone_state(&self.selections);
 1063        clone.scroll_manager.clone_state(&self.scroll_manager);
 1064        clone.searchable = self.searchable;
 1065        clone
 1066    }
 1067
 1068    pub fn new(
 1069        mode: EditorMode,
 1070        buffer: Model<MultiBuffer>,
 1071        project: Option<Model<Project>>,
 1072        show_excerpt_controls: bool,
 1073        cx: &mut ViewContext<Self>,
 1074    ) -> Self {
 1075        let style = cx.text_style();
 1076        let font_size = style.font_size.to_pixels(cx.rem_size());
 1077        let editor = cx.view().downgrade();
 1078        let fold_placeholder = FoldPlaceholder {
 1079            constrain_width: true,
 1080            render: Arc::new(move |fold_id, fold_range, cx| {
 1081                let editor = editor.clone();
 1082                div()
 1083                    .id(fold_id)
 1084                    .bg(cx.theme().colors().ghost_element_background)
 1085                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1086                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1087                    .rounded_sm()
 1088                    .size_full()
 1089                    .cursor_pointer()
 1090                    .child("")
 1091                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1092                    .on_click(move |_, cx| {
 1093                        editor
 1094                            .update(cx, |editor, cx| {
 1095                                editor.unfold_ranges(
 1096                                    &[fold_range.start..fold_range.end],
 1097                                    true,
 1098                                    false,
 1099                                    cx,
 1100                                );
 1101                                cx.stop_propagation();
 1102                            })
 1103                            .ok();
 1104                    })
 1105                    .into_any()
 1106            }),
 1107            merge_adjacent: true,
 1108            ..Default::default()
 1109        };
 1110        let display_map = cx.new_model(|cx| {
 1111            DisplayMap::new(
 1112                buffer.clone(),
 1113                style.font(),
 1114                font_size,
 1115                None,
 1116                show_excerpt_controls,
 1117                FILE_HEADER_HEIGHT,
 1118                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1119                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1120                fold_placeholder,
 1121                cx,
 1122            )
 1123        });
 1124
 1125        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1126
 1127        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1128
 1129        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1130            .then(|| language_settings::SoftWrap::None);
 1131
 1132        let mut project_subscriptions = Vec::new();
 1133        if mode == EditorMode::Full {
 1134            if let Some(project) = project.as_ref() {
 1135                if buffer.read(cx).is_singleton() {
 1136                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1137                        cx.emit(EditorEvent::TitleChanged);
 1138                    }));
 1139                }
 1140                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1141                    if let project::Event::RefreshInlayHints = event {
 1142                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1143                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1144                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1145                            let focus_handle = editor.focus_handle(cx);
 1146                            if focus_handle.is_focused(cx) {
 1147                                let snapshot = buffer.read(cx).snapshot();
 1148                                for (range, snippet) in snippet_edits {
 1149                                    let editor_range =
 1150                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1151                                    editor
 1152                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1153                                        .ok();
 1154                                }
 1155                            }
 1156                        }
 1157                    }
 1158                }));
 1159                if let Some(task_inventory) = project
 1160                    .read(cx)
 1161                    .task_store()
 1162                    .read(cx)
 1163                    .task_inventory()
 1164                    .cloned()
 1165                {
 1166                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1167                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1168                    }));
 1169                }
 1170            }
 1171        }
 1172
 1173        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1174
 1175        let inlay_hint_settings =
 1176            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1177        let focus_handle = cx.focus_handle();
 1178        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1179        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1180            .detach();
 1181        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1182            .detach();
 1183        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1184
 1185        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1186            Some(false)
 1187        } else {
 1188            None
 1189        };
 1190
 1191        let mut code_action_providers = Vec::new();
 1192        if let Some(project) = project.clone() {
 1193            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1194            code_action_providers.push(Rc::new(project) as Rc<_>);
 1195        }
 1196
 1197        let mut this = Self {
 1198            focus_handle,
 1199            show_cursor_when_unfocused: false,
 1200            last_focused_descendant: None,
 1201            buffer: buffer.clone(),
 1202            display_map: display_map.clone(),
 1203            selections,
 1204            scroll_manager: ScrollManager::new(cx),
 1205            columnar_selection_tail: None,
 1206            add_selections_state: None,
 1207            select_next_state: None,
 1208            select_prev_state: None,
 1209            selection_history: Default::default(),
 1210            autoclose_regions: Default::default(),
 1211            snippet_stack: Default::default(),
 1212            select_larger_syntax_node_stack: Vec::new(),
 1213            ime_transaction: Default::default(),
 1214            active_diagnostics: None,
 1215            soft_wrap_mode_override,
 1216            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1217            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1218            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1219            project,
 1220            blink_manager: blink_manager.clone(),
 1221            show_local_selections: true,
 1222            mode,
 1223            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1224            show_gutter: mode == EditorMode::Full,
 1225            show_line_numbers: None,
 1226            use_relative_line_numbers: None,
 1227            show_git_diff_gutter: None,
 1228            show_code_actions: None,
 1229            show_runnables: None,
 1230            show_wrap_guides: None,
 1231            show_indent_guides,
 1232            placeholder_text: None,
 1233            highlight_order: 0,
 1234            highlighted_rows: HashMap::default(),
 1235            background_highlights: Default::default(),
 1236            gutter_highlights: TreeMap::default(),
 1237            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1238            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1239            nav_history: None,
 1240            context_menu: RefCell::new(None),
 1241            mouse_context_menu: None,
 1242            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1243            completion_tasks: Default::default(),
 1244            signature_help_state: SignatureHelpState::default(),
 1245            auto_signature_help: None,
 1246            find_all_references_task_sources: Vec::new(),
 1247            next_completion_id: 0,
 1248            next_inlay_id: 0,
 1249            code_action_providers,
 1250            available_code_actions: Default::default(),
 1251            code_actions_task: Default::default(),
 1252            document_highlights_task: Default::default(),
 1253            linked_editing_range_task: Default::default(),
 1254            pending_rename: Default::default(),
 1255            searchable: true,
 1256            cursor_shape: EditorSettings::get_global(cx)
 1257                .cursor_shape
 1258                .unwrap_or_default(),
 1259            current_line_highlight: None,
 1260            autoindent_mode: Some(AutoindentMode::EachLine),
 1261            collapse_matches: false,
 1262            workspace: None,
 1263            input_enabled: true,
 1264            use_modal_editing: mode == EditorMode::Full,
 1265            read_only: false,
 1266            use_autoclose: true,
 1267            use_auto_surround: true,
 1268            auto_replace_emoji_shortcode: false,
 1269            leader_peer_id: None,
 1270            remote_id: None,
 1271            hover_state: Default::default(),
 1272            hovered_link_state: Default::default(),
 1273            inline_completion_provider: None,
 1274            active_inline_completion: None,
 1275            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1276            diff_map: DiffMap::default(),
 1277            gutter_hovered: false,
 1278            pixel_position_of_newest_cursor: None,
 1279            last_bounds: None,
 1280            expect_bounds_change: None,
 1281            gutter_dimensions: GutterDimensions::default(),
 1282            style: None,
 1283            show_cursor_names: false,
 1284            hovered_cursors: Default::default(),
 1285            next_editor_action_id: EditorActionId::default(),
 1286            editor_actions: Rc::default(),
 1287            show_inline_completions_override: None,
 1288            enable_inline_completions: true,
 1289            custom_context_menu: None,
 1290            show_git_blame_gutter: false,
 1291            show_git_blame_inline: false,
 1292            show_selection_menu: None,
 1293            show_git_blame_inline_delay_task: None,
 1294            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1295            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1296                .session
 1297                .restore_unsaved_buffers,
 1298            blame: None,
 1299            blame_subscription: None,
 1300            tasks: Default::default(),
 1301            _subscriptions: vec![
 1302                cx.observe(&buffer, Self::on_buffer_changed),
 1303                cx.subscribe(&buffer, Self::on_buffer_event),
 1304                cx.observe(&display_map, Self::on_display_map_changed),
 1305                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1306                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1307                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1308                cx.observe_window_activation(|editor, cx| {
 1309                    let active = cx.is_window_active();
 1310                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1311                        if active {
 1312                            blink_manager.enable(cx);
 1313                        } else {
 1314                            blink_manager.disable(cx);
 1315                        }
 1316                    });
 1317                }),
 1318            ],
 1319            tasks_update_task: None,
 1320            linked_edit_ranges: Default::default(),
 1321            previous_search_ranges: None,
 1322            breadcrumb_header: None,
 1323            focused_block: None,
 1324            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1325            addons: HashMap::default(),
 1326            registered_buffers: HashMap::default(),
 1327            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1328            toggle_fold_multiple_buffers: Task::ready(()),
 1329            text_style_refinement: None,
 1330        };
 1331        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1332        this._subscriptions.extend(project_subscriptions);
 1333
 1334        this.end_selection(cx);
 1335        this.scroll_manager.show_scrollbar(cx);
 1336
 1337        if mode == EditorMode::Full {
 1338            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1339            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1340
 1341            if this.git_blame_inline_enabled {
 1342                this.git_blame_inline_enabled = true;
 1343                this.start_git_blame_inline(false, cx);
 1344            }
 1345
 1346            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1347                if let Some(project) = this.project.as_ref() {
 1348                    let lsp_store = project.read(cx).lsp_store();
 1349                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1350                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1351                    });
 1352                    this.registered_buffers
 1353                        .insert(buffer.read(cx).remote_id(), handle);
 1354                }
 1355            }
 1356        }
 1357
 1358        this.report_editor_event("open", None, cx);
 1359        this
 1360    }
 1361
 1362    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1363        self.mouse_context_menu
 1364            .as_ref()
 1365            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1366    }
 1367
 1368    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1369        let mut key_context = KeyContext::new_with_defaults();
 1370        key_context.add("Editor");
 1371        let mode = match self.mode {
 1372            EditorMode::SingleLine { .. } => "single_line",
 1373            EditorMode::AutoHeight { .. } => "auto_height",
 1374            EditorMode::Full => "full",
 1375        };
 1376
 1377        if EditorSettings::jupyter_enabled(cx) {
 1378            key_context.add("jupyter");
 1379        }
 1380
 1381        key_context.set("mode", mode);
 1382        if self.pending_rename.is_some() {
 1383            key_context.add("renaming");
 1384        }
 1385        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(false, 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        keep_inline_completion: bool,
 2448        should_report_inline_completion_event: bool,
 2449        cx: &mut ViewContext<Self>,
 2450    ) -> bool {
 2451        if self.take_rename(false, cx).is_some() {
 2452            return true;
 2453        }
 2454
 2455        if hide_hover(self, cx) {
 2456            return true;
 2457        }
 2458
 2459        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2460            return true;
 2461        }
 2462
 2463        if self.hide_context_menu(cx).is_some() {
 2464            return true;
 2465        }
 2466
 2467        if self.mouse_context_menu.take().is_some() {
 2468            return true;
 2469        }
 2470
 2471        if !keep_inline_completion
 2472            && self.discard_inline_completion(should_report_inline_completion_event, cx)
 2473        {
 2474            return true;
 2475        }
 2476
 2477        if self.snippet_stack.pop().is_some() {
 2478            return true;
 2479        }
 2480
 2481        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2482            self.dismiss_diagnostics(cx);
 2483            return true;
 2484        }
 2485
 2486        false
 2487    }
 2488
 2489    fn linked_editing_ranges_for(
 2490        &self,
 2491        selection: Range<text::Anchor>,
 2492        cx: &AppContext,
 2493    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2494        if self.linked_edit_ranges.is_empty() {
 2495            return None;
 2496        }
 2497        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2498            selection.end.buffer_id.and_then(|end_buffer_id| {
 2499                if selection.start.buffer_id != Some(end_buffer_id) {
 2500                    return None;
 2501                }
 2502                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2503                let snapshot = buffer.read(cx).snapshot();
 2504                self.linked_edit_ranges
 2505                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2506                    .map(|ranges| (ranges, snapshot, buffer))
 2507            })?;
 2508        use text::ToOffset as TO;
 2509        // find offset from the start of current range to current cursor position
 2510        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2511
 2512        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2513        let start_difference = start_offset - start_byte_offset;
 2514        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2515        let end_difference = end_offset - start_byte_offset;
 2516        // Current range has associated linked ranges.
 2517        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2518        for range in linked_ranges.iter() {
 2519            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2520            let end_offset = start_offset + end_difference;
 2521            let start_offset = start_offset + start_difference;
 2522            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2523                continue;
 2524            }
 2525            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2526                if s.start.buffer_id != selection.start.buffer_id
 2527                    || s.end.buffer_id != selection.end.buffer_id
 2528                {
 2529                    return false;
 2530                }
 2531                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2532                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2533            }) {
 2534                continue;
 2535            }
 2536            let start = buffer_snapshot.anchor_after(start_offset);
 2537            let end = buffer_snapshot.anchor_after(end_offset);
 2538            linked_edits
 2539                .entry(buffer.clone())
 2540                .or_default()
 2541                .push(start..end);
 2542        }
 2543        Some(linked_edits)
 2544    }
 2545
 2546    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2547        let text: Arc<str> = text.into();
 2548
 2549        if self.read_only(cx) {
 2550            return;
 2551        }
 2552
 2553        let selections = self.selections.all_adjusted(cx);
 2554        let mut bracket_inserted = false;
 2555        let mut edits = Vec::new();
 2556        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2557        let mut new_selections = Vec::with_capacity(selections.len());
 2558        let mut new_autoclose_regions = Vec::new();
 2559        let snapshot = self.buffer.read(cx).read(cx);
 2560
 2561        for (selection, autoclose_region) in
 2562            self.selections_with_autoclose_regions(selections, &snapshot)
 2563        {
 2564            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2565                // Determine if the inserted text matches the opening or closing
 2566                // bracket of any of this language's bracket pairs.
 2567                let mut bracket_pair = None;
 2568                let mut is_bracket_pair_start = false;
 2569                let mut is_bracket_pair_end = false;
 2570                if !text.is_empty() {
 2571                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2572                    //  and they are removing the character that triggered IME popup.
 2573                    for (pair, enabled) in scope.brackets() {
 2574                        if !pair.close && !pair.surround {
 2575                            continue;
 2576                        }
 2577
 2578                        if enabled && pair.start.ends_with(text.as_ref()) {
 2579                            let prefix_len = pair.start.len() - text.len();
 2580                            let preceding_text_matches_prefix = prefix_len == 0
 2581                                || (selection.start.column >= (prefix_len as u32)
 2582                                    && snapshot.contains_str_at(
 2583                                        Point::new(
 2584                                            selection.start.row,
 2585                                            selection.start.column - (prefix_len as u32),
 2586                                        ),
 2587                                        &pair.start[..prefix_len],
 2588                                    ));
 2589                            if preceding_text_matches_prefix {
 2590                                bracket_pair = Some(pair.clone());
 2591                                is_bracket_pair_start = true;
 2592                                break;
 2593                            }
 2594                        }
 2595                        if pair.end.as_str() == text.as_ref() {
 2596                            bracket_pair = Some(pair.clone());
 2597                            is_bracket_pair_end = true;
 2598                            break;
 2599                        }
 2600                    }
 2601                }
 2602
 2603                if let Some(bracket_pair) = bracket_pair {
 2604                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2605                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2606                    let auto_surround =
 2607                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2608                    if selection.is_empty() {
 2609                        if is_bracket_pair_start {
 2610                            // If the inserted text is a suffix of an opening bracket and the
 2611                            // selection is preceded by the rest of the opening bracket, then
 2612                            // insert the closing bracket.
 2613                            let following_text_allows_autoclose = snapshot
 2614                                .chars_at(selection.start)
 2615                                .next()
 2616                                .map_or(true, |c| scope.should_autoclose_before(c));
 2617
 2618                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2619                                && bracket_pair.start.len() == 1
 2620                            {
 2621                                let target = bracket_pair.start.chars().next().unwrap();
 2622                                let current_line_count = snapshot
 2623                                    .reversed_chars_at(selection.start)
 2624                                    .take_while(|&c| c != '\n')
 2625                                    .filter(|&c| c == target)
 2626                                    .count();
 2627                                current_line_count % 2 == 1
 2628                            } else {
 2629                                false
 2630                            };
 2631
 2632                            if autoclose
 2633                                && bracket_pair.close
 2634                                && following_text_allows_autoclose
 2635                                && !is_closing_quote
 2636                            {
 2637                                let anchor = snapshot.anchor_before(selection.end);
 2638                                new_selections.push((selection.map(|_| anchor), text.len()));
 2639                                new_autoclose_regions.push((
 2640                                    anchor,
 2641                                    text.len(),
 2642                                    selection.id,
 2643                                    bracket_pair.clone(),
 2644                                ));
 2645                                edits.push((
 2646                                    selection.range(),
 2647                                    format!("{}{}", text, bracket_pair.end).into(),
 2648                                ));
 2649                                bracket_inserted = true;
 2650                                continue;
 2651                            }
 2652                        }
 2653
 2654                        if let Some(region) = autoclose_region {
 2655                            // If the selection is followed by an auto-inserted closing bracket,
 2656                            // then don't insert that closing bracket again; just move the selection
 2657                            // past the closing bracket.
 2658                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2659                                && text.as_ref() == region.pair.end.as_str();
 2660                            if should_skip {
 2661                                let anchor = snapshot.anchor_after(selection.end);
 2662                                new_selections
 2663                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2664                                continue;
 2665                            }
 2666                        }
 2667
 2668                        let always_treat_brackets_as_autoclosed = snapshot
 2669                            .settings_at(selection.start, cx)
 2670                            .always_treat_brackets_as_autoclosed;
 2671                        if always_treat_brackets_as_autoclosed
 2672                            && is_bracket_pair_end
 2673                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2674                        {
 2675                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2676                            // and the inserted text is a closing bracket and the selection is followed
 2677                            // by the closing bracket then move the selection past the closing bracket.
 2678                            let anchor = snapshot.anchor_after(selection.end);
 2679                            new_selections.push((selection.map(|_| anchor), text.len()));
 2680                            continue;
 2681                        }
 2682                    }
 2683                    // If an opening bracket is 1 character long and is typed while
 2684                    // text is selected, then surround that text with the bracket pair.
 2685                    else if auto_surround
 2686                        && bracket_pair.surround
 2687                        && is_bracket_pair_start
 2688                        && bracket_pair.start.chars().count() == 1
 2689                    {
 2690                        edits.push((selection.start..selection.start, text.clone()));
 2691                        edits.push((
 2692                            selection.end..selection.end,
 2693                            bracket_pair.end.as_str().into(),
 2694                        ));
 2695                        bracket_inserted = true;
 2696                        new_selections.push((
 2697                            Selection {
 2698                                id: selection.id,
 2699                                start: snapshot.anchor_after(selection.start),
 2700                                end: snapshot.anchor_before(selection.end),
 2701                                reversed: selection.reversed,
 2702                                goal: selection.goal,
 2703                            },
 2704                            0,
 2705                        ));
 2706                        continue;
 2707                    }
 2708                }
 2709            }
 2710
 2711            if self.auto_replace_emoji_shortcode
 2712                && selection.is_empty()
 2713                && text.as_ref().ends_with(':')
 2714            {
 2715                if let Some(possible_emoji_short_code) =
 2716                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2717                {
 2718                    if !possible_emoji_short_code.is_empty() {
 2719                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2720                            let emoji_shortcode_start = Point::new(
 2721                                selection.start.row,
 2722                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2723                            );
 2724
 2725                            // Remove shortcode from buffer
 2726                            edits.push((
 2727                                emoji_shortcode_start..selection.start,
 2728                                "".to_string().into(),
 2729                            ));
 2730                            new_selections.push((
 2731                                Selection {
 2732                                    id: selection.id,
 2733                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2734                                    end: snapshot.anchor_before(selection.start),
 2735                                    reversed: selection.reversed,
 2736                                    goal: selection.goal,
 2737                                },
 2738                                0,
 2739                            ));
 2740
 2741                            // Insert emoji
 2742                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2743                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2744                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2745
 2746                            continue;
 2747                        }
 2748                    }
 2749                }
 2750            }
 2751
 2752            // If not handling any auto-close operation, then just replace the selected
 2753            // text with the given input and move the selection to the end of the
 2754            // newly inserted text.
 2755            let anchor = snapshot.anchor_after(selection.end);
 2756            if !self.linked_edit_ranges.is_empty() {
 2757                let start_anchor = snapshot.anchor_before(selection.start);
 2758
 2759                let is_word_char = text.chars().next().map_or(true, |char| {
 2760                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2761                    classifier.is_word(char)
 2762                });
 2763
 2764                if is_word_char {
 2765                    if let Some(ranges) = self
 2766                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2767                    {
 2768                        for (buffer, edits) in ranges {
 2769                            linked_edits
 2770                                .entry(buffer.clone())
 2771                                .or_default()
 2772                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2773                        }
 2774                    }
 2775                }
 2776            }
 2777
 2778            new_selections.push((selection.map(|_| anchor), 0));
 2779            edits.push((selection.start..selection.end, text.clone()));
 2780        }
 2781
 2782        drop(snapshot);
 2783
 2784        self.transact(cx, |this, cx| {
 2785            this.buffer.update(cx, |buffer, cx| {
 2786                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2787            });
 2788            for (buffer, edits) in linked_edits {
 2789                buffer.update(cx, |buffer, cx| {
 2790                    let snapshot = buffer.snapshot();
 2791                    let edits = edits
 2792                        .into_iter()
 2793                        .map(|(range, text)| {
 2794                            use text::ToPoint as TP;
 2795                            let end_point = TP::to_point(&range.end, &snapshot);
 2796                            let start_point = TP::to_point(&range.start, &snapshot);
 2797                            (start_point..end_point, text)
 2798                        })
 2799                        .sorted_by_key(|(range, _)| range.start)
 2800                        .collect::<Vec<_>>();
 2801                    buffer.edit(edits, None, cx);
 2802                })
 2803            }
 2804            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2805            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2806            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2807            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2808                .zip(new_selection_deltas)
 2809                .map(|(selection, delta)| Selection {
 2810                    id: selection.id,
 2811                    start: selection.start + delta,
 2812                    end: selection.end + delta,
 2813                    reversed: selection.reversed,
 2814                    goal: SelectionGoal::None,
 2815                })
 2816                .collect::<Vec<_>>();
 2817
 2818            let mut i = 0;
 2819            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2820                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2821                let start = map.buffer_snapshot.anchor_before(position);
 2822                let end = map.buffer_snapshot.anchor_after(position);
 2823                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2824                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2825                        Ordering::Less => i += 1,
 2826                        Ordering::Greater => break,
 2827                        Ordering::Equal => {
 2828                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2829                                Ordering::Less => i += 1,
 2830                                Ordering::Equal => break,
 2831                                Ordering::Greater => break,
 2832                            }
 2833                        }
 2834                    }
 2835                }
 2836                this.autoclose_regions.insert(
 2837                    i,
 2838                    AutocloseRegion {
 2839                        selection_id,
 2840                        range: start..end,
 2841                        pair,
 2842                    },
 2843                );
 2844            }
 2845
 2846            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2847                s.select(new_selections)
 2848            });
 2849
 2850            if !bracket_inserted {
 2851                if let Some(on_type_format_task) =
 2852                    this.trigger_on_type_formatting(text.to_string(), cx)
 2853                {
 2854                    on_type_format_task.detach_and_log_err(cx);
 2855                }
 2856            }
 2857
 2858            let editor_settings = EditorSettings::get_global(cx);
 2859            if bracket_inserted
 2860                && (editor_settings.auto_signature_help
 2861                    || editor_settings.show_signature_help_after_edits)
 2862            {
 2863                this.show_signature_help(&ShowSignatureHelp, cx);
 2864            }
 2865
 2866            this.trigger_completion_on_input(&text, true, cx);
 2867            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2868            this.refresh_inline_completion(true, false, cx);
 2869        });
 2870    }
 2871
 2872    fn find_possible_emoji_shortcode_at_position(
 2873        snapshot: &MultiBufferSnapshot,
 2874        position: Point,
 2875    ) -> Option<String> {
 2876        let mut chars = Vec::new();
 2877        let mut found_colon = false;
 2878        for char in snapshot.reversed_chars_at(position).take(100) {
 2879            // Found a possible emoji shortcode in the middle of the buffer
 2880            if found_colon {
 2881                if char.is_whitespace() {
 2882                    chars.reverse();
 2883                    return Some(chars.iter().collect());
 2884                }
 2885                // If the previous character is not a whitespace, we are in the middle of a word
 2886                // and we only want to complete the shortcode if the word is made up of other emojis
 2887                let mut containing_word = String::new();
 2888                for ch in snapshot
 2889                    .reversed_chars_at(position)
 2890                    .skip(chars.len() + 1)
 2891                    .take(100)
 2892                {
 2893                    if ch.is_whitespace() {
 2894                        break;
 2895                    }
 2896                    containing_word.push(ch);
 2897                }
 2898                let containing_word = containing_word.chars().rev().collect::<String>();
 2899                if util::word_consists_of_emojis(containing_word.as_str()) {
 2900                    chars.reverse();
 2901                    return Some(chars.iter().collect());
 2902                }
 2903            }
 2904
 2905            if char.is_whitespace() || !char.is_ascii() {
 2906                return None;
 2907            }
 2908            if char == ':' {
 2909                found_colon = true;
 2910            } else {
 2911                chars.push(char);
 2912            }
 2913        }
 2914        // Found a possible emoji shortcode at the beginning of the buffer
 2915        chars.reverse();
 2916        Some(chars.iter().collect())
 2917    }
 2918
 2919    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2920        self.transact(cx, |this, cx| {
 2921            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2922                let selections = this.selections.all::<usize>(cx);
 2923                let multi_buffer = this.buffer.read(cx);
 2924                let buffer = multi_buffer.snapshot(cx);
 2925                selections
 2926                    .iter()
 2927                    .map(|selection| {
 2928                        let start_point = selection.start.to_point(&buffer);
 2929                        let mut indent =
 2930                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2931                        indent.len = cmp::min(indent.len, start_point.column);
 2932                        let start = selection.start;
 2933                        let end = selection.end;
 2934                        let selection_is_empty = start == end;
 2935                        let language_scope = buffer.language_scope_at(start);
 2936                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2937                            &language_scope
 2938                        {
 2939                            let leading_whitespace_len = buffer
 2940                                .reversed_chars_at(start)
 2941                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2942                                .map(|c| c.len_utf8())
 2943                                .sum::<usize>();
 2944
 2945                            let trailing_whitespace_len = buffer
 2946                                .chars_at(end)
 2947                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2948                                .map(|c| c.len_utf8())
 2949                                .sum::<usize>();
 2950
 2951                            let insert_extra_newline =
 2952                                language.brackets().any(|(pair, enabled)| {
 2953                                    let pair_start = pair.start.trim_end();
 2954                                    let pair_end = pair.end.trim_start();
 2955
 2956                                    enabled
 2957                                        && pair.newline
 2958                                        && buffer.contains_str_at(
 2959                                            end + trailing_whitespace_len,
 2960                                            pair_end,
 2961                                        )
 2962                                        && buffer.contains_str_at(
 2963                                            (start - leading_whitespace_len)
 2964                                                .saturating_sub(pair_start.len()),
 2965                                            pair_start,
 2966                                        )
 2967                                });
 2968
 2969                            // Comment extension on newline is allowed only for cursor selections
 2970                            let comment_delimiter = maybe!({
 2971                                if !selection_is_empty {
 2972                                    return None;
 2973                                }
 2974
 2975                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 2976                                    return None;
 2977                                }
 2978
 2979                                let delimiters = language.line_comment_prefixes();
 2980                                let max_len_of_delimiter =
 2981                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 2982                                let (snapshot, range) =
 2983                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 2984
 2985                                let mut index_of_first_non_whitespace = 0;
 2986                                let comment_candidate = snapshot
 2987                                    .chars_for_range(range)
 2988                                    .skip_while(|c| {
 2989                                        let should_skip = c.is_whitespace();
 2990                                        if should_skip {
 2991                                            index_of_first_non_whitespace += 1;
 2992                                        }
 2993                                        should_skip
 2994                                    })
 2995                                    .take(max_len_of_delimiter)
 2996                                    .collect::<String>();
 2997                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 2998                                    comment_candidate.starts_with(comment_prefix.as_ref())
 2999                                })?;
 3000                                let cursor_is_placed_after_comment_marker =
 3001                                    index_of_first_non_whitespace + comment_prefix.len()
 3002                                        <= start_point.column as usize;
 3003                                if cursor_is_placed_after_comment_marker {
 3004                                    Some(comment_prefix.clone())
 3005                                } else {
 3006                                    None
 3007                                }
 3008                            });
 3009                            (comment_delimiter, insert_extra_newline)
 3010                        } else {
 3011                            (None, false)
 3012                        };
 3013
 3014                        let capacity_for_delimiter = comment_delimiter
 3015                            .as_deref()
 3016                            .map(str::len)
 3017                            .unwrap_or_default();
 3018                        let mut new_text =
 3019                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3020                        new_text.push('\n');
 3021                        new_text.extend(indent.chars());
 3022                        if let Some(delimiter) = &comment_delimiter {
 3023                            new_text.push_str(delimiter);
 3024                        }
 3025                        if insert_extra_newline {
 3026                            new_text = new_text.repeat(2);
 3027                        }
 3028
 3029                        let anchor = buffer.anchor_after(end);
 3030                        let new_selection = selection.map(|_| anchor);
 3031                        (
 3032                            (start..end, new_text),
 3033                            (insert_extra_newline, new_selection),
 3034                        )
 3035                    })
 3036                    .unzip()
 3037            };
 3038
 3039            this.edit_with_autoindent(edits, cx);
 3040            let buffer = this.buffer.read(cx).snapshot(cx);
 3041            let new_selections = selection_fixup_info
 3042                .into_iter()
 3043                .map(|(extra_newline_inserted, new_selection)| {
 3044                    let mut cursor = new_selection.end.to_point(&buffer);
 3045                    if extra_newline_inserted {
 3046                        cursor.row -= 1;
 3047                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3048                    }
 3049                    new_selection.map(|_| cursor)
 3050                })
 3051                .collect();
 3052
 3053            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3054            this.refresh_inline_completion(true, false, cx);
 3055        });
 3056    }
 3057
 3058    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3059        let buffer = self.buffer.read(cx);
 3060        let snapshot = buffer.snapshot(cx);
 3061
 3062        let mut edits = Vec::new();
 3063        let mut rows = Vec::new();
 3064
 3065        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3066            let cursor = selection.head();
 3067            let row = cursor.row;
 3068
 3069            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3070
 3071            let newline = "\n".to_string();
 3072            edits.push((start_of_line..start_of_line, newline));
 3073
 3074            rows.push(row + rows_inserted as u32);
 3075        }
 3076
 3077        self.transact(cx, |editor, cx| {
 3078            editor.edit(edits, cx);
 3079
 3080            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3081                let mut index = 0;
 3082                s.move_cursors_with(|map, _, _| {
 3083                    let row = rows[index];
 3084                    index += 1;
 3085
 3086                    let point = Point::new(row, 0);
 3087                    let boundary = map.next_line_boundary(point).1;
 3088                    let clipped = map.clip_point(boundary, Bias::Left);
 3089
 3090                    (clipped, SelectionGoal::None)
 3091                });
 3092            });
 3093
 3094            let mut indent_edits = Vec::new();
 3095            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3096            for row in rows {
 3097                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3098                for (row, indent) in indents {
 3099                    if indent.len == 0 {
 3100                        continue;
 3101                    }
 3102
 3103                    let text = match indent.kind {
 3104                        IndentKind::Space => " ".repeat(indent.len as usize),
 3105                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3106                    };
 3107                    let point = Point::new(row.0, 0);
 3108                    indent_edits.push((point..point, text));
 3109                }
 3110            }
 3111            editor.edit(indent_edits, cx);
 3112        });
 3113    }
 3114
 3115    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3116        let buffer = self.buffer.read(cx);
 3117        let snapshot = buffer.snapshot(cx);
 3118
 3119        let mut edits = Vec::new();
 3120        let mut rows = Vec::new();
 3121        let mut rows_inserted = 0;
 3122
 3123        for selection in self.selections.all_adjusted(cx) {
 3124            let cursor = selection.head();
 3125            let row = cursor.row;
 3126
 3127            let point = Point::new(row + 1, 0);
 3128            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3129
 3130            let newline = "\n".to_string();
 3131            edits.push((start_of_line..start_of_line, newline));
 3132
 3133            rows_inserted += 1;
 3134            rows.push(row + rows_inserted);
 3135        }
 3136
 3137        self.transact(cx, |editor, cx| {
 3138            editor.edit(edits, cx);
 3139
 3140            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3141                let mut index = 0;
 3142                s.move_cursors_with(|map, _, _| {
 3143                    let row = rows[index];
 3144                    index += 1;
 3145
 3146                    let point = Point::new(row, 0);
 3147                    let boundary = map.next_line_boundary(point).1;
 3148                    let clipped = map.clip_point(boundary, Bias::Left);
 3149
 3150                    (clipped, SelectionGoal::None)
 3151                });
 3152            });
 3153
 3154            let mut indent_edits = Vec::new();
 3155            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3156            for row in rows {
 3157                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3158                for (row, indent) in indents {
 3159                    if indent.len == 0 {
 3160                        continue;
 3161                    }
 3162
 3163                    let text = match indent.kind {
 3164                        IndentKind::Space => " ".repeat(indent.len as usize),
 3165                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3166                    };
 3167                    let point = Point::new(row.0, 0);
 3168                    indent_edits.push((point..point, text));
 3169                }
 3170            }
 3171            editor.edit(indent_edits, cx);
 3172        });
 3173    }
 3174
 3175    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3176        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3177            original_indent_columns: Vec::new(),
 3178        });
 3179        self.insert_with_autoindent_mode(text, autoindent, cx);
 3180    }
 3181
 3182    fn insert_with_autoindent_mode(
 3183        &mut self,
 3184        text: &str,
 3185        autoindent_mode: Option<AutoindentMode>,
 3186        cx: &mut ViewContext<Self>,
 3187    ) {
 3188        if self.read_only(cx) {
 3189            return;
 3190        }
 3191
 3192        let text: Arc<str> = text.into();
 3193        self.transact(cx, |this, cx| {
 3194            let old_selections = this.selections.all_adjusted(cx);
 3195            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3196                let anchors = {
 3197                    let snapshot = buffer.read(cx);
 3198                    old_selections
 3199                        .iter()
 3200                        .map(|s| {
 3201                            let anchor = snapshot.anchor_after(s.head());
 3202                            s.map(|_| anchor)
 3203                        })
 3204                        .collect::<Vec<_>>()
 3205                };
 3206                buffer.edit(
 3207                    old_selections
 3208                        .iter()
 3209                        .map(|s| (s.start..s.end, text.clone())),
 3210                    autoindent_mode,
 3211                    cx,
 3212                );
 3213                anchors
 3214            });
 3215
 3216            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3217                s.select_anchors(selection_anchors);
 3218            })
 3219        });
 3220    }
 3221
 3222    fn trigger_completion_on_input(
 3223        &mut self,
 3224        text: &str,
 3225        trigger_in_words: bool,
 3226        cx: &mut ViewContext<Self>,
 3227    ) {
 3228        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3229            self.show_completions(
 3230                &ShowCompletions {
 3231                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3232                },
 3233                cx,
 3234            );
 3235        } else {
 3236            self.hide_context_menu(cx);
 3237        }
 3238    }
 3239
 3240    fn is_completion_trigger(
 3241        &self,
 3242        text: &str,
 3243        trigger_in_words: bool,
 3244        cx: &mut ViewContext<Self>,
 3245    ) -> bool {
 3246        let position = self.selections.newest_anchor().head();
 3247        let multibuffer = self.buffer.read(cx);
 3248        let Some(buffer) = position
 3249            .buffer_id
 3250            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3251        else {
 3252            return false;
 3253        };
 3254
 3255        if let Some(completion_provider) = &self.completion_provider {
 3256            completion_provider.is_completion_trigger(
 3257                &buffer,
 3258                position.text_anchor,
 3259                text,
 3260                trigger_in_words,
 3261                cx,
 3262            )
 3263        } else {
 3264            false
 3265        }
 3266    }
 3267
 3268    /// If any empty selections is touching the start of its innermost containing autoclose
 3269    /// region, expand it to select the brackets.
 3270    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3271        let selections = self.selections.all::<usize>(cx);
 3272        let buffer = self.buffer.read(cx).read(cx);
 3273        let new_selections = self
 3274            .selections_with_autoclose_regions(selections, &buffer)
 3275            .map(|(mut selection, region)| {
 3276                if !selection.is_empty() {
 3277                    return selection;
 3278                }
 3279
 3280                if let Some(region) = region {
 3281                    let mut range = region.range.to_offset(&buffer);
 3282                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3283                        range.start -= region.pair.start.len();
 3284                        if buffer.contains_str_at(range.start, &region.pair.start)
 3285                            && buffer.contains_str_at(range.end, &region.pair.end)
 3286                        {
 3287                            range.end += region.pair.end.len();
 3288                            selection.start = range.start;
 3289                            selection.end = range.end;
 3290
 3291                            return selection;
 3292                        }
 3293                    }
 3294                }
 3295
 3296                let always_treat_brackets_as_autoclosed = buffer
 3297                    .settings_at(selection.start, cx)
 3298                    .always_treat_brackets_as_autoclosed;
 3299
 3300                if !always_treat_brackets_as_autoclosed {
 3301                    return selection;
 3302                }
 3303
 3304                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3305                    for (pair, enabled) in scope.brackets() {
 3306                        if !enabled || !pair.close {
 3307                            continue;
 3308                        }
 3309
 3310                        if buffer.contains_str_at(selection.start, &pair.end) {
 3311                            let pair_start_len = pair.start.len();
 3312                            if buffer.contains_str_at(
 3313                                selection.start.saturating_sub(pair_start_len),
 3314                                &pair.start,
 3315                            ) {
 3316                                selection.start -= pair_start_len;
 3317                                selection.end += pair.end.len();
 3318
 3319                                return selection;
 3320                            }
 3321                        }
 3322                    }
 3323                }
 3324
 3325                selection
 3326            })
 3327            .collect();
 3328
 3329        drop(buffer);
 3330        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3331    }
 3332
 3333    /// Iterate the given selections, and for each one, find the smallest surrounding
 3334    /// autoclose region. This uses the ordering of the selections and the autoclose
 3335    /// regions to avoid repeated comparisons.
 3336    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3337        &'a self,
 3338        selections: impl IntoIterator<Item = Selection<D>>,
 3339        buffer: &'a MultiBufferSnapshot,
 3340    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3341        let mut i = 0;
 3342        let mut regions = self.autoclose_regions.as_slice();
 3343        selections.into_iter().map(move |selection| {
 3344            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3345
 3346            let mut enclosing = None;
 3347            while let Some(pair_state) = regions.get(i) {
 3348                if pair_state.range.end.to_offset(buffer) < range.start {
 3349                    regions = &regions[i + 1..];
 3350                    i = 0;
 3351                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3352                    break;
 3353                } else {
 3354                    if pair_state.selection_id == selection.id {
 3355                        enclosing = Some(pair_state);
 3356                    }
 3357                    i += 1;
 3358                }
 3359            }
 3360
 3361            (selection, enclosing)
 3362        })
 3363    }
 3364
 3365    /// Remove any autoclose regions that no longer contain their selection.
 3366    fn invalidate_autoclose_regions(
 3367        &mut self,
 3368        mut selections: &[Selection<Anchor>],
 3369        buffer: &MultiBufferSnapshot,
 3370    ) {
 3371        self.autoclose_regions.retain(|state| {
 3372            let mut i = 0;
 3373            while let Some(selection) = selections.get(i) {
 3374                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3375                    selections = &selections[1..];
 3376                    continue;
 3377                }
 3378                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3379                    break;
 3380                }
 3381                if selection.id == state.selection_id {
 3382                    return true;
 3383                } else {
 3384                    i += 1;
 3385                }
 3386            }
 3387            false
 3388        });
 3389    }
 3390
 3391    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3392        let offset = position.to_offset(buffer);
 3393        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3394        if offset > word_range.start && kind == Some(CharKind::Word) {
 3395            Some(
 3396                buffer
 3397                    .text_for_range(word_range.start..offset)
 3398                    .collect::<String>(),
 3399            )
 3400        } else {
 3401            None
 3402        }
 3403    }
 3404
 3405    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3406        self.refresh_inlay_hints(
 3407            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3408            cx,
 3409        );
 3410    }
 3411
 3412    pub fn inlay_hints_enabled(&self) -> bool {
 3413        self.inlay_hint_cache.enabled
 3414    }
 3415
 3416    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3417        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3418            return;
 3419        }
 3420
 3421        let reason_description = reason.description();
 3422        let ignore_debounce = matches!(
 3423            reason,
 3424            InlayHintRefreshReason::SettingsChange(_)
 3425                | InlayHintRefreshReason::Toggle(_)
 3426                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3427        );
 3428        let (invalidate_cache, required_languages) = match reason {
 3429            InlayHintRefreshReason::Toggle(enabled) => {
 3430                self.inlay_hint_cache.enabled = enabled;
 3431                if enabled {
 3432                    (InvalidationStrategy::RefreshRequested, None)
 3433                } else {
 3434                    self.inlay_hint_cache.clear();
 3435                    self.splice_inlays(
 3436                        self.visible_inlay_hints(cx)
 3437                            .iter()
 3438                            .map(|inlay| inlay.id)
 3439                            .collect(),
 3440                        Vec::new(),
 3441                        cx,
 3442                    );
 3443                    return;
 3444                }
 3445            }
 3446            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3447                match self.inlay_hint_cache.update_settings(
 3448                    &self.buffer,
 3449                    new_settings,
 3450                    self.visible_inlay_hints(cx),
 3451                    cx,
 3452                ) {
 3453                    ControlFlow::Break(Some(InlaySplice {
 3454                        to_remove,
 3455                        to_insert,
 3456                    })) => {
 3457                        self.splice_inlays(to_remove, to_insert, cx);
 3458                        return;
 3459                    }
 3460                    ControlFlow::Break(None) => return,
 3461                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3462                }
 3463            }
 3464            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3465                if let Some(InlaySplice {
 3466                    to_remove,
 3467                    to_insert,
 3468                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3469                {
 3470                    self.splice_inlays(to_remove, to_insert, cx);
 3471                }
 3472                return;
 3473            }
 3474            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3475            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3476                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3477            }
 3478            InlayHintRefreshReason::RefreshRequested => {
 3479                (InvalidationStrategy::RefreshRequested, None)
 3480            }
 3481        };
 3482
 3483        if let Some(InlaySplice {
 3484            to_remove,
 3485            to_insert,
 3486        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3487            reason_description,
 3488            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3489            invalidate_cache,
 3490            ignore_debounce,
 3491            cx,
 3492        ) {
 3493            self.splice_inlays(to_remove, to_insert, cx);
 3494        }
 3495    }
 3496
 3497    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3498        self.display_map
 3499            .read(cx)
 3500            .current_inlays()
 3501            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3502            .cloned()
 3503            .collect()
 3504    }
 3505
 3506    pub fn excerpts_for_inlay_hints_query(
 3507        &self,
 3508        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3509        cx: &mut ViewContext<Editor>,
 3510    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3511        let Some(project) = self.project.as_ref() else {
 3512            return HashMap::default();
 3513        };
 3514        let project = project.read(cx);
 3515        let multi_buffer = self.buffer().read(cx);
 3516        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3517        let multi_buffer_visible_start = self
 3518            .scroll_manager
 3519            .anchor()
 3520            .anchor
 3521            .to_point(&multi_buffer_snapshot);
 3522        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3523            multi_buffer_visible_start
 3524                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3525            Bias::Left,
 3526        );
 3527        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3528        multi_buffer
 3529            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3530            .into_iter()
 3531            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3532            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3533                let buffer = buffer_handle.read(cx);
 3534                let buffer_file = project::File::from_dyn(buffer.file())?;
 3535                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3536                let worktree_entry = buffer_worktree
 3537                    .read(cx)
 3538                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3539                if worktree_entry.is_ignored {
 3540                    return None;
 3541                }
 3542
 3543                let language = buffer.language()?;
 3544                if let Some(restrict_to_languages) = restrict_to_languages {
 3545                    if !restrict_to_languages.contains(language) {
 3546                        return None;
 3547                    }
 3548                }
 3549                Some((
 3550                    excerpt_id,
 3551                    (
 3552                        buffer_handle,
 3553                        buffer.version().clone(),
 3554                        excerpt_visible_range,
 3555                    ),
 3556                ))
 3557            })
 3558            .collect()
 3559    }
 3560
 3561    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3562        TextLayoutDetails {
 3563            text_system: cx.text_system().clone(),
 3564            editor_style: self.style.clone().unwrap(),
 3565            rem_size: cx.rem_size(),
 3566            scroll_anchor: self.scroll_manager.anchor(),
 3567            visible_rows: self.visible_line_count(),
 3568            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3569        }
 3570    }
 3571
 3572    fn splice_inlays(
 3573        &self,
 3574        to_remove: Vec<InlayId>,
 3575        to_insert: Vec<Inlay>,
 3576        cx: &mut ViewContext<Self>,
 3577    ) {
 3578        self.display_map.update(cx, |display_map, cx| {
 3579            display_map.splice_inlays(to_remove, to_insert, cx)
 3580        });
 3581        cx.notify();
 3582    }
 3583
 3584    fn trigger_on_type_formatting(
 3585        &self,
 3586        input: String,
 3587        cx: &mut ViewContext<Self>,
 3588    ) -> Option<Task<Result<()>>> {
 3589        if input.len() != 1 {
 3590            return None;
 3591        }
 3592
 3593        let project = self.project.as_ref()?;
 3594        let position = self.selections.newest_anchor().head();
 3595        let (buffer, buffer_position) = self
 3596            .buffer
 3597            .read(cx)
 3598            .text_anchor_for_position(position, cx)?;
 3599
 3600        let settings = language_settings::language_settings(
 3601            buffer
 3602                .read(cx)
 3603                .language_at(buffer_position)
 3604                .map(|l| l.name()),
 3605            buffer.read(cx).file(),
 3606            cx,
 3607        );
 3608        if !settings.use_on_type_format {
 3609            return None;
 3610        }
 3611
 3612        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3613        // hence we do LSP request & edit on host side only — add formats to host's history.
 3614        let push_to_lsp_host_history = true;
 3615        // If this is not the host, append its history with new edits.
 3616        let push_to_client_history = project.read(cx).is_via_collab();
 3617
 3618        let on_type_formatting = project.update(cx, |project, cx| {
 3619            project.on_type_format(
 3620                buffer.clone(),
 3621                buffer_position,
 3622                input,
 3623                push_to_lsp_host_history,
 3624                cx,
 3625            )
 3626        });
 3627        Some(cx.spawn(|editor, mut cx| async move {
 3628            if let Some(transaction) = on_type_formatting.await? {
 3629                if push_to_client_history {
 3630                    buffer
 3631                        .update(&mut cx, |buffer, _| {
 3632                            buffer.push_transaction(transaction, Instant::now());
 3633                        })
 3634                        .ok();
 3635                }
 3636                editor.update(&mut cx, |editor, cx| {
 3637                    editor.refresh_document_highlights(cx);
 3638                })?;
 3639            }
 3640            Ok(())
 3641        }))
 3642    }
 3643
 3644    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3645        if self.pending_rename.is_some() {
 3646            return;
 3647        }
 3648
 3649        let Some(provider) = self.completion_provider.as_ref() else {
 3650            return;
 3651        };
 3652
 3653        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3654            return;
 3655        }
 3656
 3657        let position = self.selections.newest_anchor().head();
 3658        let (buffer, buffer_position) =
 3659            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3660                output
 3661            } else {
 3662                return;
 3663            };
 3664        let show_completion_documentation = buffer
 3665            .read(cx)
 3666            .snapshot()
 3667            .settings_at(buffer_position, cx)
 3668            .show_completion_documentation;
 3669
 3670        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3671
 3672        let aside_was_displayed = match self.context_menu.borrow().deref() {
 3673            Some(CodeContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
 3674            _ => false,
 3675        };
 3676        let trigger_kind = match &options.trigger {
 3677            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3678                CompletionTriggerKind::TRIGGER_CHARACTER
 3679            }
 3680            _ => CompletionTriggerKind::INVOKED,
 3681        };
 3682        let completion_context = CompletionContext {
 3683            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3684                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3685                    Some(String::from(trigger))
 3686                } else {
 3687                    None
 3688                }
 3689            }),
 3690            trigger_kind,
 3691        };
 3692        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3693        let sort_completions = provider.sort_completions();
 3694
 3695        let id = post_inc(&mut self.next_completion_id);
 3696        let task = cx.spawn(|editor, mut cx| {
 3697            async move {
 3698                editor.update(&mut cx, |this, _| {
 3699                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3700                })?;
 3701                let completions = completions.await.log_err();
 3702                let menu = if let Some(completions) = completions {
 3703                    let mut menu = CompletionsMenu::new(
 3704                        id,
 3705                        sort_completions,
 3706                        show_completion_documentation,
 3707                        position,
 3708                        buffer.clone(),
 3709                        completions.into(),
 3710                        aside_was_displayed,
 3711                    );
 3712                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3713                        .await;
 3714
 3715                    if menu.matches.is_empty() {
 3716                        None
 3717                    } else {
 3718                        Some(menu)
 3719                    }
 3720                } else {
 3721                    None
 3722                };
 3723
 3724                editor.update(&mut cx, |editor, cx| {
 3725                    let mut context_menu = editor.context_menu.borrow_mut();
 3726                    match context_menu.as_ref() {
 3727                        None => {}
 3728                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3729                            if prev_menu.id > id {
 3730                                return;
 3731                            }
 3732                        }
 3733                        _ => return,
 3734                    }
 3735
 3736                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3737                        let mut menu = menu.unwrap();
 3738                        menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
 3739                        *context_menu = Some(CodeContextMenu::Completions(menu));
 3740                        drop(context_menu);
 3741                        cx.notify();
 3742                    } else if editor.completion_tasks.len() <= 1 {
 3743                        // If there are no more completion tasks and the last menu was
 3744                        // empty, we should hide it. If it was already hidden, we should
 3745                        // also show the copilot completion when available.
 3746                        drop(context_menu);
 3747                        editor.hide_context_menu(cx);
 3748                    }
 3749                })?;
 3750
 3751                Ok::<_, anyhow::Error>(())
 3752            }
 3753            .log_err()
 3754        });
 3755
 3756        self.completion_tasks.push((id, task));
 3757    }
 3758
 3759    pub fn confirm_completion(
 3760        &mut self,
 3761        action: &ConfirmCompletion,
 3762        cx: &mut ViewContext<Self>,
 3763    ) -> Option<Task<Result<()>>> {
 3764        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3765    }
 3766
 3767    pub fn compose_completion(
 3768        &mut self,
 3769        action: &ComposeCompletion,
 3770        cx: &mut ViewContext<Self>,
 3771    ) -> Option<Task<Result<()>>> {
 3772        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3773    }
 3774
 3775    fn do_completion(
 3776        &mut self,
 3777        item_ix: Option<usize>,
 3778        intent: CompletionIntent,
 3779        cx: &mut ViewContext<Editor>,
 3780    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3781        use language::ToOffset as _;
 3782
 3783        self.discard_inline_completion(true, cx);
 3784        let completions_menu =
 3785            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3786                menu
 3787            } else {
 3788                return None;
 3789            };
 3790
 3791        let mat = completions_menu
 3792            .matches
 3793            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3794        let buffer_handle = completions_menu.buffer;
 3795        let completions = completions_menu.completions.borrow_mut();
 3796        let completion = completions.get(mat.candidate_id)?;
 3797        cx.stop_propagation();
 3798
 3799        let snippet;
 3800        let text;
 3801
 3802        if completion.is_snippet() {
 3803            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3804            text = snippet.as_ref().unwrap().text.clone();
 3805        } else {
 3806            snippet = None;
 3807            text = completion.new_text.clone();
 3808        };
 3809        let selections = self.selections.all::<usize>(cx);
 3810        let buffer = buffer_handle.read(cx);
 3811        let old_range = completion.old_range.to_offset(buffer);
 3812        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3813
 3814        let newest_selection = self.selections.newest_anchor();
 3815        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3816            return None;
 3817        }
 3818
 3819        let lookbehind = newest_selection
 3820            .start
 3821            .text_anchor
 3822            .to_offset(buffer)
 3823            .saturating_sub(old_range.start);
 3824        let lookahead = old_range
 3825            .end
 3826            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3827        let mut common_prefix_len = old_text
 3828            .bytes()
 3829            .zip(text.bytes())
 3830            .take_while(|(a, b)| a == b)
 3831            .count();
 3832
 3833        let snapshot = self.buffer.read(cx).snapshot(cx);
 3834        let mut range_to_replace: Option<Range<isize>> = None;
 3835        let mut ranges = Vec::new();
 3836        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3837        for selection in &selections {
 3838            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3839                let start = selection.start.saturating_sub(lookbehind);
 3840                let end = selection.end + lookahead;
 3841                if selection.id == newest_selection.id {
 3842                    range_to_replace = Some(
 3843                        ((start + common_prefix_len) as isize - selection.start as isize)
 3844                            ..(end as isize - selection.start as isize),
 3845                    );
 3846                }
 3847                ranges.push(start + common_prefix_len..end);
 3848            } else {
 3849                common_prefix_len = 0;
 3850                ranges.clear();
 3851                ranges.extend(selections.iter().map(|s| {
 3852                    if s.id == newest_selection.id {
 3853                        range_to_replace = Some(
 3854                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3855                                - selection.start as isize
 3856                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3857                                    - selection.start as isize,
 3858                        );
 3859                        old_range.clone()
 3860                    } else {
 3861                        s.start..s.end
 3862                    }
 3863                }));
 3864                break;
 3865            }
 3866            if !self.linked_edit_ranges.is_empty() {
 3867                let start_anchor = snapshot.anchor_before(selection.head());
 3868                let end_anchor = snapshot.anchor_after(selection.tail());
 3869                if let Some(ranges) = self
 3870                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3871                {
 3872                    for (buffer, edits) in ranges {
 3873                        linked_edits.entry(buffer.clone()).or_default().extend(
 3874                            edits
 3875                                .into_iter()
 3876                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3877                        );
 3878                    }
 3879                }
 3880            }
 3881        }
 3882        let text = &text[common_prefix_len..];
 3883
 3884        cx.emit(EditorEvent::InputHandled {
 3885            utf16_range_to_replace: range_to_replace,
 3886            text: text.into(),
 3887        });
 3888
 3889        self.transact(cx, |this, cx| {
 3890            if let Some(mut snippet) = snippet {
 3891                snippet.text = text.to_string();
 3892                for tabstop in snippet
 3893                    .tabstops
 3894                    .iter_mut()
 3895                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3896                {
 3897                    tabstop.start -= common_prefix_len as isize;
 3898                    tabstop.end -= common_prefix_len as isize;
 3899                }
 3900
 3901                this.insert_snippet(&ranges, snippet, cx).log_err();
 3902            } else {
 3903                this.buffer.update(cx, |buffer, cx| {
 3904                    buffer.edit(
 3905                        ranges.iter().map(|range| (range.clone(), text)),
 3906                        this.autoindent_mode.clone(),
 3907                        cx,
 3908                    );
 3909                });
 3910            }
 3911            for (buffer, edits) in linked_edits {
 3912                buffer.update(cx, |buffer, cx| {
 3913                    let snapshot = buffer.snapshot();
 3914                    let edits = edits
 3915                        .into_iter()
 3916                        .map(|(range, text)| {
 3917                            use text::ToPoint as TP;
 3918                            let end_point = TP::to_point(&range.end, &snapshot);
 3919                            let start_point = TP::to_point(&range.start, &snapshot);
 3920                            (start_point..end_point, text)
 3921                        })
 3922                        .sorted_by_key(|(range, _)| range.start)
 3923                        .collect::<Vec<_>>();
 3924                    buffer.edit(edits, None, cx);
 3925                })
 3926            }
 3927
 3928            this.refresh_inline_completion(true, false, cx);
 3929        });
 3930
 3931        let show_new_completions_on_confirm = completion
 3932            .confirm
 3933            .as_ref()
 3934            .map_or(false, |confirm| confirm(intent, cx));
 3935        if show_new_completions_on_confirm {
 3936            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3937        }
 3938
 3939        let provider = self.completion_provider.as_ref()?;
 3940        let apply_edits = provider.apply_additional_edits_for_completion(
 3941            buffer_handle,
 3942            completion.clone(),
 3943            true,
 3944            cx,
 3945        );
 3946
 3947        let editor_settings = EditorSettings::get_global(cx);
 3948        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3949            // After the code completion is finished, users often want to know what signatures are needed.
 3950            // so we should automatically call signature_help
 3951            self.show_signature_help(&ShowSignatureHelp, cx);
 3952        }
 3953
 3954        Some(cx.foreground_executor().spawn(async move {
 3955            apply_edits.await?;
 3956            Ok(())
 3957        }))
 3958    }
 3959
 3960    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3961        let mut context_menu = self.context_menu.borrow_mut();
 3962        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 3963            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 3964                // Toggle if we're selecting the same one
 3965                *context_menu = None;
 3966                cx.notify();
 3967                return;
 3968            } else {
 3969                // Otherwise, clear it and start a new one
 3970                *context_menu = None;
 3971                cx.notify();
 3972            }
 3973        }
 3974        drop(context_menu);
 3975        let snapshot = self.snapshot(cx);
 3976        let deployed_from_indicator = action.deployed_from_indicator;
 3977        let mut task = self.code_actions_task.take();
 3978        let action = action.clone();
 3979        cx.spawn(|editor, mut cx| async move {
 3980            while let Some(prev_task) = task {
 3981                prev_task.await.log_err();
 3982                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 3983            }
 3984
 3985            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 3986                if editor.focus_handle.is_focused(cx) {
 3987                    let multibuffer_point = action
 3988                        .deployed_from_indicator
 3989                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 3990                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 3991                    let (buffer, buffer_row) = snapshot
 3992                        .buffer_snapshot
 3993                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 3994                        .and_then(|(buffer_snapshot, range)| {
 3995                            editor
 3996                                .buffer
 3997                                .read(cx)
 3998                                .buffer(buffer_snapshot.remote_id())
 3999                                .map(|buffer| (buffer, range.start.row))
 4000                        })?;
 4001                    let (_, code_actions) = editor
 4002                        .available_code_actions
 4003                        .clone()
 4004                        .and_then(|(location, code_actions)| {
 4005                            let snapshot = location.buffer.read(cx).snapshot();
 4006                            let point_range = location.range.to_point(&snapshot);
 4007                            let point_range = point_range.start.row..=point_range.end.row;
 4008                            if point_range.contains(&buffer_row) {
 4009                                Some((location, code_actions))
 4010                            } else {
 4011                                None
 4012                            }
 4013                        })
 4014                        .unzip();
 4015                    let buffer_id = buffer.read(cx).remote_id();
 4016                    let tasks = editor
 4017                        .tasks
 4018                        .get(&(buffer_id, buffer_row))
 4019                        .map(|t| Arc::new(t.to_owned()));
 4020                    if tasks.is_none() && code_actions.is_none() {
 4021                        return None;
 4022                    }
 4023
 4024                    editor.completion_tasks.clear();
 4025                    editor.discard_inline_completion(false, cx);
 4026                    let task_context =
 4027                        tasks
 4028                            .as_ref()
 4029                            .zip(editor.project.clone())
 4030                            .map(|(tasks, project)| {
 4031                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4032                            });
 4033
 4034                    Some(cx.spawn(|editor, mut cx| async move {
 4035                        let task_context = match task_context {
 4036                            Some(task_context) => task_context.await,
 4037                            None => None,
 4038                        };
 4039                        let resolved_tasks =
 4040                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4041                                Rc::new(ResolvedTasks {
 4042                                    templates: tasks.resolve(&task_context).collect(),
 4043                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4044                                        multibuffer_point.row,
 4045                                        tasks.column,
 4046                                    )),
 4047                                })
 4048                            });
 4049                        let spawn_straight_away = resolved_tasks
 4050                            .as_ref()
 4051                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4052                            && code_actions
 4053                                .as_ref()
 4054                                .map_or(true, |actions| actions.is_empty());
 4055                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4056                            *editor.context_menu.borrow_mut() =
 4057                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4058                                    buffer,
 4059                                    actions: CodeActionContents {
 4060                                        tasks: resolved_tasks,
 4061                                        actions: code_actions,
 4062                                    },
 4063                                    selected_item: Default::default(),
 4064                                    scroll_handle: UniformListScrollHandle::default(),
 4065                                    deployed_from_indicator,
 4066                                }));
 4067                            if spawn_straight_away {
 4068                                if let Some(task) = editor.confirm_code_action(
 4069                                    &ConfirmCodeAction { item_ix: Some(0) },
 4070                                    cx,
 4071                                ) {
 4072                                    cx.notify();
 4073                                    return task;
 4074                                }
 4075                            }
 4076                            cx.notify();
 4077                            Task::ready(Ok(()))
 4078                        }) {
 4079                            task.await
 4080                        } else {
 4081                            Ok(())
 4082                        }
 4083                    }))
 4084                } else {
 4085                    Some(Task::ready(Ok(())))
 4086                }
 4087            })?;
 4088            if let Some(task) = spawned_test_task {
 4089                task.await?;
 4090            }
 4091
 4092            Ok::<_, anyhow::Error>(())
 4093        })
 4094        .detach_and_log_err(cx);
 4095    }
 4096
 4097    pub fn confirm_code_action(
 4098        &mut self,
 4099        action: &ConfirmCodeAction,
 4100        cx: &mut ViewContext<Self>,
 4101    ) -> Option<Task<Result<()>>> {
 4102        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4103            menu
 4104        } else {
 4105            return None;
 4106        };
 4107        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4108        let action = actions_menu.actions.get(action_ix)?;
 4109        let title = action.label();
 4110        let buffer = actions_menu.buffer;
 4111        let workspace = self.workspace()?;
 4112
 4113        match action {
 4114            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4115                workspace.update(cx, |workspace, cx| {
 4116                    workspace::tasks::schedule_resolved_task(
 4117                        workspace,
 4118                        task_source_kind,
 4119                        resolved_task,
 4120                        false,
 4121                        cx,
 4122                    );
 4123
 4124                    Some(Task::ready(Ok(())))
 4125                })
 4126            }
 4127            CodeActionsItem::CodeAction {
 4128                excerpt_id,
 4129                action,
 4130                provider,
 4131            } => {
 4132                let apply_code_action =
 4133                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4134                let workspace = workspace.downgrade();
 4135                Some(cx.spawn(|editor, cx| async move {
 4136                    let project_transaction = apply_code_action.await?;
 4137                    Self::open_project_transaction(
 4138                        &editor,
 4139                        workspace,
 4140                        project_transaction,
 4141                        title,
 4142                        cx,
 4143                    )
 4144                    .await
 4145                }))
 4146            }
 4147        }
 4148    }
 4149
 4150    pub async fn open_project_transaction(
 4151        this: &WeakView<Editor>,
 4152        workspace: WeakView<Workspace>,
 4153        transaction: ProjectTransaction,
 4154        title: String,
 4155        mut cx: AsyncWindowContext,
 4156    ) -> Result<()> {
 4157        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4158        cx.update(|cx| {
 4159            entries.sort_unstable_by_key(|(buffer, _)| {
 4160                buffer.read(cx).file().map(|f| f.path().clone())
 4161            });
 4162        })?;
 4163
 4164        // If the project transaction's edits are all contained within this editor, then
 4165        // avoid opening a new editor to display them.
 4166
 4167        if let Some((buffer, transaction)) = entries.first() {
 4168            if entries.len() == 1 {
 4169                let excerpt = this.update(&mut cx, |editor, cx| {
 4170                    editor
 4171                        .buffer()
 4172                        .read(cx)
 4173                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4174                })?;
 4175                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4176                    if excerpted_buffer == *buffer {
 4177                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4178                            let excerpt_range = excerpt_range.to_offset(buffer);
 4179                            buffer
 4180                                .edited_ranges_for_transaction::<usize>(transaction)
 4181                                .all(|range| {
 4182                                    excerpt_range.start <= range.start
 4183                                        && excerpt_range.end >= range.end
 4184                                })
 4185                        })?;
 4186
 4187                        if all_edits_within_excerpt {
 4188                            return Ok(());
 4189                        }
 4190                    }
 4191                }
 4192            }
 4193        } else {
 4194            return Ok(());
 4195        }
 4196
 4197        let mut ranges_to_highlight = Vec::new();
 4198        let excerpt_buffer = cx.new_model(|cx| {
 4199            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4200            for (buffer_handle, transaction) in &entries {
 4201                let buffer = buffer_handle.read(cx);
 4202                ranges_to_highlight.extend(
 4203                    multibuffer.push_excerpts_with_context_lines(
 4204                        buffer_handle.clone(),
 4205                        buffer
 4206                            .edited_ranges_for_transaction::<usize>(transaction)
 4207                            .collect(),
 4208                        DEFAULT_MULTIBUFFER_CONTEXT,
 4209                        cx,
 4210                    ),
 4211                );
 4212            }
 4213            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4214            multibuffer
 4215        })?;
 4216
 4217        workspace.update(&mut cx, |workspace, cx| {
 4218            let project = workspace.project().clone();
 4219            let editor =
 4220                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4221            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4222            editor.update(cx, |editor, cx| {
 4223                editor.highlight_background::<Self>(
 4224                    &ranges_to_highlight,
 4225                    |theme| theme.editor_highlighted_line_background,
 4226                    cx,
 4227                );
 4228            });
 4229        })?;
 4230
 4231        Ok(())
 4232    }
 4233
 4234    pub fn clear_code_action_providers(&mut self) {
 4235        self.code_action_providers.clear();
 4236        self.available_code_actions.take();
 4237    }
 4238
 4239    pub fn push_code_action_provider(
 4240        &mut self,
 4241        provider: Rc<dyn CodeActionProvider>,
 4242        cx: &mut ViewContext<Self>,
 4243    ) {
 4244        self.code_action_providers.push(provider);
 4245        self.refresh_code_actions(cx);
 4246    }
 4247
 4248    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4249        let buffer = self.buffer.read(cx);
 4250        let newest_selection = self.selections.newest_anchor().clone();
 4251        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4252        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4253        if start_buffer != end_buffer {
 4254            return None;
 4255        }
 4256
 4257        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4258            cx.background_executor()
 4259                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4260                .await;
 4261
 4262            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4263                let providers = this.code_action_providers.clone();
 4264                let tasks = this
 4265                    .code_action_providers
 4266                    .iter()
 4267                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4268                    .collect::<Vec<_>>();
 4269                (providers, tasks)
 4270            })?;
 4271
 4272            let mut actions = Vec::new();
 4273            for (provider, provider_actions) in
 4274                providers.into_iter().zip(future::join_all(tasks).await)
 4275            {
 4276                if let Some(provider_actions) = provider_actions.log_err() {
 4277                    actions.extend(provider_actions.into_iter().map(|action| {
 4278                        AvailableCodeAction {
 4279                            excerpt_id: newest_selection.start.excerpt_id,
 4280                            action,
 4281                            provider: provider.clone(),
 4282                        }
 4283                    }));
 4284                }
 4285            }
 4286
 4287            this.update(&mut cx, |this, cx| {
 4288                this.available_code_actions = if actions.is_empty() {
 4289                    None
 4290                } else {
 4291                    Some((
 4292                        Location {
 4293                            buffer: start_buffer,
 4294                            range: start..end,
 4295                        },
 4296                        actions.into(),
 4297                    ))
 4298                };
 4299                cx.notify();
 4300            })
 4301        }));
 4302        None
 4303    }
 4304
 4305    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4306        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4307            self.show_git_blame_inline = false;
 4308
 4309            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4310                cx.background_executor().timer(delay).await;
 4311
 4312                this.update(&mut cx, |this, cx| {
 4313                    this.show_git_blame_inline = true;
 4314                    cx.notify();
 4315                })
 4316                .log_err();
 4317            }));
 4318        }
 4319    }
 4320
 4321    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4322        if self.pending_rename.is_some() {
 4323            return None;
 4324        }
 4325
 4326        let provider = self.semantics_provider.clone()?;
 4327        let buffer = self.buffer.read(cx);
 4328        let newest_selection = self.selections.newest_anchor().clone();
 4329        let cursor_position = newest_selection.head();
 4330        let (cursor_buffer, cursor_buffer_position) =
 4331            buffer.text_anchor_for_position(cursor_position, cx)?;
 4332        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4333        if cursor_buffer != tail_buffer {
 4334            return None;
 4335        }
 4336        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4337        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4338            cx.background_executor()
 4339                .timer(Duration::from_millis(debounce))
 4340                .await;
 4341
 4342            let highlights = if let Some(highlights) = cx
 4343                .update(|cx| {
 4344                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4345                })
 4346                .ok()
 4347                .flatten()
 4348            {
 4349                highlights.await.log_err()
 4350            } else {
 4351                None
 4352            };
 4353
 4354            if let Some(highlights) = highlights {
 4355                this.update(&mut cx, |this, cx| {
 4356                    if this.pending_rename.is_some() {
 4357                        return;
 4358                    }
 4359
 4360                    let buffer_id = cursor_position.buffer_id;
 4361                    let buffer = this.buffer.read(cx);
 4362                    if !buffer
 4363                        .text_anchor_for_position(cursor_position, cx)
 4364                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4365                    {
 4366                        return;
 4367                    }
 4368
 4369                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4370                    let mut write_ranges = Vec::new();
 4371                    let mut read_ranges = Vec::new();
 4372                    for highlight in highlights {
 4373                        for (excerpt_id, excerpt_range) in
 4374                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4375                        {
 4376                            let start = highlight
 4377                                .range
 4378                                .start
 4379                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4380                            let end = highlight
 4381                                .range
 4382                                .end
 4383                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4384                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4385                                continue;
 4386                            }
 4387
 4388                            let range = Anchor {
 4389                                buffer_id,
 4390                                excerpt_id,
 4391                                text_anchor: start,
 4392                            }..Anchor {
 4393                                buffer_id,
 4394                                excerpt_id,
 4395                                text_anchor: end,
 4396                            };
 4397                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4398                                write_ranges.push(range);
 4399                            } else {
 4400                                read_ranges.push(range);
 4401                            }
 4402                        }
 4403                    }
 4404
 4405                    this.highlight_background::<DocumentHighlightRead>(
 4406                        &read_ranges,
 4407                        |theme| theme.editor_document_highlight_read_background,
 4408                        cx,
 4409                    );
 4410                    this.highlight_background::<DocumentHighlightWrite>(
 4411                        &write_ranges,
 4412                        |theme| theme.editor_document_highlight_write_background,
 4413                        cx,
 4414                    );
 4415                    cx.notify();
 4416                })
 4417                .log_err();
 4418            }
 4419        }));
 4420        None
 4421    }
 4422
 4423    pub fn refresh_inline_completion(
 4424        &mut self,
 4425        debounce: bool,
 4426        user_requested: bool,
 4427        cx: &mut ViewContext<Self>,
 4428    ) -> Option<()> {
 4429        let provider = self.inline_completion_provider()?;
 4430        let cursor = self.selections.newest_anchor().head();
 4431        let (buffer, cursor_buffer_position) =
 4432            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4433
 4434        if !user_requested
 4435            && (!self.enable_inline_completions
 4436                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4437                || !self.is_focused(cx))
 4438        {
 4439            self.discard_inline_completion(false, cx);
 4440            return None;
 4441        }
 4442
 4443        self.update_visible_inline_completion(cx);
 4444        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4445        Some(())
 4446    }
 4447
 4448    fn cycle_inline_completion(
 4449        &mut self,
 4450        direction: Direction,
 4451        cx: &mut ViewContext<Self>,
 4452    ) -> Option<()> {
 4453        let provider = self.inline_completion_provider()?;
 4454        let cursor = self.selections.newest_anchor().head();
 4455        let (buffer, cursor_buffer_position) =
 4456            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4457        if !self.enable_inline_completions
 4458            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4459        {
 4460            return None;
 4461        }
 4462
 4463        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4464        self.update_visible_inline_completion(cx);
 4465
 4466        Some(())
 4467    }
 4468
 4469    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4470        if !self.has_active_inline_completion() {
 4471            self.refresh_inline_completion(false, true, cx);
 4472            return;
 4473        }
 4474
 4475        self.update_visible_inline_completion(cx);
 4476    }
 4477
 4478    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4479        self.show_cursor_names(cx);
 4480    }
 4481
 4482    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4483        self.show_cursor_names = true;
 4484        cx.notify();
 4485        cx.spawn(|this, mut cx| async move {
 4486            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4487            this.update(&mut cx, |this, cx| {
 4488                this.show_cursor_names = false;
 4489                cx.notify()
 4490            })
 4491            .ok()
 4492        })
 4493        .detach();
 4494    }
 4495
 4496    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4497        if self.has_active_inline_completion() {
 4498            self.cycle_inline_completion(Direction::Next, cx);
 4499        } else {
 4500            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4501            if is_copilot_disabled {
 4502                cx.propagate();
 4503            }
 4504        }
 4505    }
 4506
 4507    pub fn previous_inline_completion(
 4508        &mut self,
 4509        _: &PreviousInlineCompletion,
 4510        cx: &mut ViewContext<Self>,
 4511    ) {
 4512        if self.has_active_inline_completion() {
 4513            self.cycle_inline_completion(Direction::Prev, cx);
 4514        } else {
 4515            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4516            if is_copilot_disabled {
 4517                cx.propagate();
 4518            }
 4519        }
 4520    }
 4521
 4522    pub fn accept_inline_completion(
 4523        &mut self,
 4524        _: &AcceptInlineCompletion,
 4525        cx: &mut ViewContext<Self>,
 4526    ) {
 4527        self.hide_context_menu(cx);
 4528
 4529        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4530            return;
 4531        };
 4532
 4533        self.report_inline_completion_event(true, cx);
 4534
 4535        match &active_inline_completion.completion {
 4536            InlineCompletion::Move(position) => {
 4537                let position = *position;
 4538                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4539                    selections.select_anchor_ranges([position..position]);
 4540                });
 4541            }
 4542            InlineCompletion::Edit(edits) => {
 4543                if let Some(provider) = self.inline_completion_provider() {
 4544                    provider.accept(cx);
 4545                }
 4546
 4547                let snapshot = self.buffer.read(cx).snapshot(cx);
 4548                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4549
 4550                self.buffer.update(cx, |buffer, cx| {
 4551                    buffer.edit(edits.iter().cloned(), None, cx)
 4552                });
 4553
 4554                self.change_selections(None, cx, |s| {
 4555                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4556                });
 4557
 4558                self.update_visible_inline_completion(cx);
 4559                if self.active_inline_completion.is_none() {
 4560                    self.refresh_inline_completion(true, true, cx);
 4561                }
 4562
 4563                cx.notify();
 4564            }
 4565        }
 4566    }
 4567
 4568    pub fn accept_partial_inline_completion(
 4569        &mut self,
 4570        _: &AcceptPartialInlineCompletion,
 4571        cx: &mut ViewContext<Self>,
 4572    ) {
 4573        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4574            return;
 4575        };
 4576        if self.selections.count() != 1 {
 4577            return;
 4578        }
 4579
 4580        self.report_inline_completion_event(true, cx);
 4581
 4582        match &active_inline_completion.completion {
 4583            InlineCompletion::Move(position) => {
 4584                let position = *position;
 4585                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4586                    selections.select_anchor_ranges([position..position]);
 4587                });
 4588            }
 4589            InlineCompletion::Edit(edits) => {
 4590                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4591                    let text = edits[0].1.as_str();
 4592                    let mut partial_completion = text
 4593                        .chars()
 4594                        .by_ref()
 4595                        .take_while(|c| c.is_alphabetic())
 4596                        .collect::<String>();
 4597                    if partial_completion.is_empty() {
 4598                        partial_completion = text
 4599                            .chars()
 4600                            .by_ref()
 4601                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4602                            .collect::<String>();
 4603                    }
 4604
 4605                    cx.emit(EditorEvent::InputHandled {
 4606                        utf16_range_to_replace: None,
 4607                        text: partial_completion.clone().into(),
 4608                    });
 4609
 4610                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4611
 4612                    self.refresh_inline_completion(true, true, cx);
 4613                    cx.notify();
 4614                }
 4615            }
 4616        }
 4617    }
 4618
 4619    fn discard_inline_completion(
 4620        &mut self,
 4621        should_report_inline_completion_event: bool,
 4622        cx: &mut ViewContext<Self>,
 4623    ) -> bool {
 4624        if should_report_inline_completion_event {
 4625            self.report_inline_completion_event(false, cx);
 4626        }
 4627
 4628        if let Some(provider) = self.inline_completion_provider() {
 4629            provider.discard(cx);
 4630        }
 4631
 4632        self.take_active_inline_completion(cx).is_some()
 4633    }
 4634
 4635    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4636        let Some(provider) = self.inline_completion_provider() else {
 4637            return;
 4638        };
 4639        let Some(project) = self.project.as_ref() else {
 4640            return;
 4641        };
 4642        let Some((_, buffer, _)) = self
 4643            .buffer
 4644            .read(cx)
 4645            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4646        else {
 4647            return;
 4648        };
 4649
 4650        let project = project.read(cx);
 4651        let extension = buffer
 4652            .read(cx)
 4653            .file()
 4654            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4655        project.client().telemetry().report_inline_completion_event(
 4656            provider.name().into(),
 4657            accepted,
 4658            extension,
 4659        );
 4660    }
 4661
 4662    pub fn has_active_inline_completion(&self) -> bool {
 4663        self.active_inline_completion.is_some()
 4664    }
 4665
 4666    fn take_active_inline_completion(
 4667        &mut self,
 4668        cx: &mut ViewContext<Self>,
 4669    ) -> Option<InlineCompletion> {
 4670        let active_inline_completion = self.active_inline_completion.take()?;
 4671        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4672        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4673        Some(active_inline_completion.completion)
 4674    }
 4675
 4676    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4677        let selection = self.selections.newest_anchor();
 4678        let cursor = selection.head();
 4679        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4680        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4681        let excerpt_id = cursor.excerpt_id;
 4682
 4683        if !offset_selection.is_empty()
 4684            || self
 4685                .active_inline_completion
 4686                .as_ref()
 4687                .map_or(false, |completion| {
 4688                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4689                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4690                    !invalidation_range.contains(&offset_selection.head())
 4691                })
 4692        {
 4693            self.discard_inline_completion(false, cx);
 4694            return None;
 4695        }
 4696
 4697        self.take_active_inline_completion(cx);
 4698        let provider = self.inline_completion_provider()?;
 4699
 4700        let (buffer, cursor_buffer_position) =
 4701            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4702
 4703        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4704        let edits = completion
 4705            .edits
 4706            .into_iter()
 4707            .map(|(range, new_text)| {
 4708                (
 4709                    multibuffer
 4710                        .anchor_in_excerpt(excerpt_id, range.start)
 4711                        .unwrap()
 4712                        ..multibuffer
 4713                            .anchor_in_excerpt(excerpt_id, range.end)
 4714                            .unwrap(),
 4715                    new_text,
 4716                )
 4717            })
 4718            .collect::<Vec<_>>();
 4719        if edits.is_empty() {
 4720            return None;
 4721        }
 4722
 4723        let first_edit_start = edits.first().unwrap().0.start;
 4724        let edit_start_row = first_edit_start
 4725            .to_point(&multibuffer)
 4726            .row
 4727            .saturating_sub(2);
 4728
 4729        let last_edit_end = edits.last().unwrap().0.end;
 4730        let edit_end_row = cmp::min(
 4731            multibuffer.max_point().row,
 4732            last_edit_end.to_point(&multibuffer).row + 2,
 4733        );
 4734
 4735        let cursor_row = cursor.to_point(&multibuffer).row;
 4736
 4737        let mut inlay_ids = Vec::new();
 4738        let invalidation_row_range;
 4739        let completion;
 4740        if cursor_row < edit_start_row {
 4741            invalidation_row_range = cursor_row..edit_end_row;
 4742            completion = InlineCompletion::Move(first_edit_start);
 4743        } else if cursor_row > edit_end_row {
 4744            invalidation_row_range = edit_start_row..cursor_row;
 4745            completion = InlineCompletion::Move(first_edit_start);
 4746        } else {
 4747            if edits
 4748                .iter()
 4749                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4750            {
 4751                let mut inlays = Vec::new();
 4752                for (range, new_text) in &edits {
 4753                    let inlay = Inlay::inline_completion(
 4754                        post_inc(&mut self.next_inlay_id),
 4755                        range.start,
 4756                        new_text.as_str(),
 4757                    );
 4758                    inlay_ids.push(inlay.id);
 4759                    inlays.push(inlay);
 4760                }
 4761
 4762                self.splice_inlays(vec![], inlays, cx);
 4763            } else {
 4764                let background_color = cx.theme().status().deleted_background;
 4765                self.highlight_text::<InlineCompletionHighlight>(
 4766                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4767                    HighlightStyle {
 4768                        background_color: Some(background_color),
 4769                        ..Default::default()
 4770                    },
 4771                    cx,
 4772                );
 4773            }
 4774
 4775            invalidation_row_range = edit_start_row..edit_end_row;
 4776            completion = InlineCompletion::Edit(edits);
 4777        };
 4778
 4779        let invalidation_range = multibuffer
 4780            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4781            ..multibuffer.anchor_after(Point::new(
 4782                invalidation_row_range.end,
 4783                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4784            ));
 4785
 4786        self.active_inline_completion = Some(InlineCompletionState {
 4787            inlay_ids,
 4788            completion,
 4789            invalidation_range,
 4790        });
 4791        cx.notify();
 4792
 4793        Some(())
 4794    }
 4795
 4796    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4797        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4798    }
 4799
 4800    fn render_code_actions_indicator(
 4801        &self,
 4802        _style: &EditorStyle,
 4803        row: DisplayRow,
 4804        is_active: bool,
 4805        cx: &mut ViewContext<Self>,
 4806    ) -> Option<IconButton> {
 4807        if self.available_code_actions.is_some() {
 4808            Some(
 4809                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4810                    .shape(ui::IconButtonShape::Square)
 4811                    .icon_size(IconSize::XSmall)
 4812                    .icon_color(Color::Muted)
 4813                    .toggle_state(is_active)
 4814                    .tooltip({
 4815                        let focus_handle = self.focus_handle.clone();
 4816                        move |cx| {
 4817                            Tooltip::for_action_in(
 4818                                "Toggle Code Actions",
 4819                                &ToggleCodeActions {
 4820                                    deployed_from_indicator: None,
 4821                                },
 4822                                &focus_handle,
 4823                                cx,
 4824                            )
 4825                        }
 4826                    })
 4827                    .on_click(cx.listener(move |editor, _e, cx| {
 4828                        editor.focus(cx);
 4829                        editor.toggle_code_actions(
 4830                            &ToggleCodeActions {
 4831                                deployed_from_indicator: Some(row),
 4832                            },
 4833                            cx,
 4834                        );
 4835                    })),
 4836            )
 4837        } else {
 4838            None
 4839        }
 4840    }
 4841
 4842    fn clear_tasks(&mut self) {
 4843        self.tasks.clear()
 4844    }
 4845
 4846    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4847        if self.tasks.insert(key, value).is_some() {
 4848            // This case should hopefully be rare, but just in case...
 4849            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4850        }
 4851    }
 4852
 4853    fn build_tasks_context(
 4854        project: &Model<Project>,
 4855        buffer: &Model<Buffer>,
 4856        buffer_row: u32,
 4857        tasks: &Arc<RunnableTasks>,
 4858        cx: &mut ViewContext<Self>,
 4859    ) -> Task<Option<task::TaskContext>> {
 4860        let position = Point::new(buffer_row, tasks.column);
 4861        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4862        let location = Location {
 4863            buffer: buffer.clone(),
 4864            range: range_start..range_start,
 4865        };
 4866        // Fill in the environmental variables from the tree-sitter captures
 4867        let mut captured_task_variables = TaskVariables::default();
 4868        for (capture_name, value) in tasks.extra_variables.clone() {
 4869            captured_task_variables.insert(
 4870                task::VariableName::Custom(capture_name.into()),
 4871                value.clone(),
 4872            );
 4873        }
 4874        project.update(cx, |project, cx| {
 4875            project.task_store().update(cx, |task_store, cx| {
 4876                task_store.task_context_for_location(captured_task_variables, location, cx)
 4877            })
 4878        })
 4879    }
 4880
 4881    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4882        let Some((workspace, _)) = self.workspace.clone() else {
 4883            return;
 4884        };
 4885        let Some(project) = self.project.clone() else {
 4886            return;
 4887        };
 4888
 4889        // Try to find a closest, enclosing node using tree-sitter that has a
 4890        // task
 4891        let Some((buffer, buffer_row, tasks)) = self
 4892            .find_enclosing_node_task(cx)
 4893            // Or find the task that's closest in row-distance.
 4894            .or_else(|| self.find_closest_task(cx))
 4895        else {
 4896            return;
 4897        };
 4898
 4899        let reveal_strategy = action.reveal;
 4900        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 4901        cx.spawn(|_, mut cx| async move {
 4902            let context = task_context.await?;
 4903            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 4904
 4905            let resolved = resolved_task.resolved.as_mut()?;
 4906            resolved.reveal = reveal_strategy;
 4907
 4908            workspace
 4909                .update(&mut cx, |workspace, cx| {
 4910                    workspace::tasks::schedule_resolved_task(
 4911                        workspace,
 4912                        task_source_kind,
 4913                        resolved_task,
 4914                        false,
 4915                        cx,
 4916                    );
 4917                })
 4918                .ok()
 4919        })
 4920        .detach();
 4921    }
 4922
 4923    fn find_closest_task(
 4924        &mut self,
 4925        cx: &mut ViewContext<Self>,
 4926    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4927        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 4928
 4929        let ((buffer_id, row), tasks) = self
 4930            .tasks
 4931            .iter()
 4932            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 4933
 4934        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 4935        let tasks = Arc::new(tasks.to_owned());
 4936        Some((buffer, *row, tasks))
 4937    }
 4938
 4939    fn find_enclosing_node_task(
 4940        &mut self,
 4941        cx: &mut ViewContext<Self>,
 4942    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4943        let snapshot = self.buffer.read(cx).snapshot(cx);
 4944        let offset = self.selections.newest::<usize>(cx).head();
 4945        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 4946        let buffer_id = excerpt.buffer().remote_id();
 4947
 4948        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 4949        let mut cursor = layer.node().walk();
 4950
 4951        while cursor.goto_first_child_for_byte(offset).is_some() {
 4952            if cursor.node().end_byte() == offset {
 4953                cursor.goto_next_sibling();
 4954            }
 4955        }
 4956
 4957        // Ascend to the smallest ancestor that contains the range and has a task.
 4958        loop {
 4959            let node = cursor.node();
 4960            let node_range = node.byte_range();
 4961            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 4962
 4963            // Check if this node contains our offset
 4964            if node_range.start <= offset && node_range.end >= offset {
 4965                // If it contains offset, check for task
 4966                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 4967                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 4968                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 4969                }
 4970            }
 4971
 4972            if !cursor.goto_parent() {
 4973                break;
 4974            }
 4975        }
 4976        None
 4977    }
 4978
 4979    fn render_run_indicator(
 4980        &self,
 4981        _style: &EditorStyle,
 4982        is_active: bool,
 4983        row: DisplayRow,
 4984        cx: &mut ViewContext<Self>,
 4985    ) -> IconButton {
 4986        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 4987            .shape(ui::IconButtonShape::Square)
 4988            .icon_size(IconSize::XSmall)
 4989            .icon_color(Color::Muted)
 4990            .toggle_state(is_active)
 4991            .on_click(cx.listener(move |editor, _e, cx| {
 4992                editor.focus(cx);
 4993                editor.toggle_code_actions(
 4994                    &ToggleCodeActions {
 4995                        deployed_from_indicator: Some(row),
 4996                    },
 4997                    cx,
 4998                );
 4999            }))
 5000    }
 5001
 5002    pub fn context_menu_visible(&self) -> bool {
 5003        self.context_menu
 5004            .borrow()
 5005            .as_ref()
 5006            .map_or(false, |menu| menu.visible())
 5007    }
 5008
 5009    fn render_context_menu(
 5010        &self,
 5011        cursor_position: DisplayPoint,
 5012        style: &EditorStyle,
 5013        max_height: Pixels,
 5014        cx: &mut ViewContext<Editor>,
 5015    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5016        self.context_menu.borrow().as_ref().map(|menu| {
 5017            menu.render(
 5018                cursor_position,
 5019                style,
 5020                max_height,
 5021                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5022                cx,
 5023            )
 5024        })
 5025    }
 5026
 5027    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5028        cx.notify();
 5029        self.completion_tasks.clear();
 5030        self.context_menu.borrow_mut().take()
 5031    }
 5032
 5033    fn show_snippet_choices(
 5034        &mut self,
 5035        choices: &Vec<String>,
 5036        selection: Range<Anchor>,
 5037        cx: &mut ViewContext<Self>,
 5038    ) {
 5039        if selection.start.buffer_id.is_none() {
 5040            return;
 5041        }
 5042        let buffer_id = selection.start.buffer_id.unwrap();
 5043        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5044        let id = post_inc(&mut self.next_completion_id);
 5045
 5046        if let Some(buffer) = buffer {
 5047            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5048                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5049            ));
 5050        }
 5051    }
 5052
 5053    pub fn insert_snippet(
 5054        &mut self,
 5055        insertion_ranges: &[Range<usize>],
 5056        snippet: Snippet,
 5057        cx: &mut ViewContext<Self>,
 5058    ) -> Result<()> {
 5059        struct Tabstop<T> {
 5060            is_end_tabstop: bool,
 5061            ranges: Vec<Range<T>>,
 5062            choices: Option<Vec<String>>,
 5063        }
 5064
 5065        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5066            let snippet_text: Arc<str> = snippet.text.clone().into();
 5067            buffer.edit(
 5068                insertion_ranges
 5069                    .iter()
 5070                    .cloned()
 5071                    .map(|range| (range, snippet_text.clone())),
 5072                Some(AutoindentMode::EachLine),
 5073                cx,
 5074            );
 5075
 5076            let snapshot = &*buffer.read(cx);
 5077            let snippet = &snippet;
 5078            snippet
 5079                .tabstops
 5080                .iter()
 5081                .map(|tabstop| {
 5082                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5083                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5084                    });
 5085                    let mut tabstop_ranges = tabstop
 5086                        .ranges
 5087                        .iter()
 5088                        .flat_map(|tabstop_range| {
 5089                            let mut delta = 0_isize;
 5090                            insertion_ranges.iter().map(move |insertion_range| {
 5091                                let insertion_start = insertion_range.start as isize + delta;
 5092                                delta +=
 5093                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5094
 5095                                let start = ((insertion_start + tabstop_range.start) as usize)
 5096                                    .min(snapshot.len());
 5097                                let end = ((insertion_start + tabstop_range.end) as usize)
 5098                                    .min(snapshot.len());
 5099                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5100                            })
 5101                        })
 5102                        .collect::<Vec<_>>();
 5103                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5104
 5105                    Tabstop {
 5106                        is_end_tabstop,
 5107                        ranges: tabstop_ranges,
 5108                        choices: tabstop.choices.clone(),
 5109                    }
 5110                })
 5111                .collect::<Vec<_>>()
 5112        });
 5113        if let Some(tabstop) = tabstops.first() {
 5114            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5115                s.select_ranges(tabstop.ranges.iter().cloned());
 5116            });
 5117
 5118            if let Some(choices) = &tabstop.choices {
 5119                if let Some(selection) = tabstop.ranges.first() {
 5120                    self.show_snippet_choices(choices, selection.clone(), cx)
 5121                }
 5122            }
 5123
 5124            // If we're already at the last tabstop and it's at the end of the snippet,
 5125            // we're done, we don't need to keep the state around.
 5126            if !tabstop.is_end_tabstop {
 5127                let choices = tabstops
 5128                    .iter()
 5129                    .map(|tabstop| tabstop.choices.clone())
 5130                    .collect();
 5131
 5132                let ranges = tabstops
 5133                    .into_iter()
 5134                    .map(|tabstop| tabstop.ranges)
 5135                    .collect::<Vec<_>>();
 5136
 5137                self.snippet_stack.push(SnippetState {
 5138                    active_index: 0,
 5139                    ranges,
 5140                    choices,
 5141                });
 5142            }
 5143
 5144            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5145            if self.autoclose_regions.is_empty() {
 5146                let snapshot = self.buffer.read(cx).snapshot(cx);
 5147                for selection in &mut self.selections.all::<Point>(cx) {
 5148                    let selection_head = selection.head();
 5149                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5150                        continue;
 5151                    };
 5152
 5153                    let mut bracket_pair = None;
 5154                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5155                    let prev_chars = snapshot
 5156                        .reversed_chars_at(selection_head)
 5157                        .collect::<String>();
 5158                    for (pair, enabled) in scope.brackets() {
 5159                        if enabled
 5160                            && pair.close
 5161                            && prev_chars.starts_with(pair.start.as_str())
 5162                            && next_chars.starts_with(pair.end.as_str())
 5163                        {
 5164                            bracket_pair = Some(pair.clone());
 5165                            break;
 5166                        }
 5167                    }
 5168                    if let Some(pair) = bracket_pair {
 5169                        let start = snapshot.anchor_after(selection_head);
 5170                        let end = snapshot.anchor_after(selection_head);
 5171                        self.autoclose_regions.push(AutocloseRegion {
 5172                            selection_id: selection.id,
 5173                            range: start..end,
 5174                            pair,
 5175                        });
 5176                    }
 5177                }
 5178            }
 5179        }
 5180        Ok(())
 5181    }
 5182
 5183    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5184        self.move_to_snippet_tabstop(Bias::Right, cx)
 5185    }
 5186
 5187    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5188        self.move_to_snippet_tabstop(Bias::Left, cx)
 5189    }
 5190
 5191    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5192        if let Some(mut snippet) = self.snippet_stack.pop() {
 5193            match bias {
 5194                Bias::Left => {
 5195                    if snippet.active_index > 0 {
 5196                        snippet.active_index -= 1;
 5197                    } else {
 5198                        self.snippet_stack.push(snippet);
 5199                        return false;
 5200                    }
 5201                }
 5202                Bias::Right => {
 5203                    if snippet.active_index + 1 < snippet.ranges.len() {
 5204                        snippet.active_index += 1;
 5205                    } else {
 5206                        self.snippet_stack.push(snippet);
 5207                        return false;
 5208                    }
 5209                }
 5210            }
 5211            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5212                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5213                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5214                });
 5215
 5216                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5217                    if let Some(selection) = current_ranges.first() {
 5218                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5219                    }
 5220                }
 5221
 5222                // If snippet state is not at the last tabstop, push it back on the stack
 5223                if snippet.active_index + 1 < snippet.ranges.len() {
 5224                    self.snippet_stack.push(snippet);
 5225                }
 5226                return true;
 5227            }
 5228        }
 5229
 5230        false
 5231    }
 5232
 5233    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5234        self.transact(cx, |this, cx| {
 5235            this.select_all(&SelectAll, cx);
 5236            this.insert("", cx);
 5237        });
 5238    }
 5239
 5240    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5241        self.transact(cx, |this, cx| {
 5242            this.select_autoclose_pair(cx);
 5243            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5244            if !this.linked_edit_ranges.is_empty() {
 5245                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5246                let snapshot = this.buffer.read(cx).snapshot(cx);
 5247
 5248                for selection in selections.iter() {
 5249                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5250                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5251                    if selection_start.buffer_id != selection_end.buffer_id {
 5252                        continue;
 5253                    }
 5254                    if let Some(ranges) =
 5255                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5256                    {
 5257                        for (buffer, entries) in ranges {
 5258                            linked_ranges.entry(buffer).or_default().extend(entries);
 5259                        }
 5260                    }
 5261                }
 5262            }
 5263
 5264            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5265            if !this.selections.line_mode {
 5266                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5267                for selection in &mut selections {
 5268                    if selection.is_empty() {
 5269                        let old_head = selection.head();
 5270                        let mut new_head =
 5271                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5272                                .to_point(&display_map);
 5273                        if let Some((buffer, line_buffer_range)) = display_map
 5274                            .buffer_snapshot
 5275                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5276                        {
 5277                            let indent_size =
 5278                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5279                            let indent_len = match indent_size.kind {
 5280                                IndentKind::Space => {
 5281                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5282                                }
 5283                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5284                            };
 5285                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5286                                let indent_len = indent_len.get();
 5287                                new_head = cmp::min(
 5288                                    new_head,
 5289                                    MultiBufferPoint::new(
 5290                                        old_head.row,
 5291                                        ((old_head.column - 1) / indent_len) * indent_len,
 5292                                    ),
 5293                                );
 5294                            }
 5295                        }
 5296
 5297                        selection.set_head(new_head, SelectionGoal::None);
 5298                    }
 5299                }
 5300            }
 5301
 5302            this.signature_help_state.set_backspace_pressed(true);
 5303            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5304            this.insert("", cx);
 5305            let empty_str: Arc<str> = Arc::from("");
 5306            for (buffer, edits) in linked_ranges {
 5307                let snapshot = buffer.read(cx).snapshot();
 5308                use text::ToPoint as TP;
 5309
 5310                let edits = edits
 5311                    .into_iter()
 5312                    .map(|range| {
 5313                        let end_point = TP::to_point(&range.end, &snapshot);
 5314                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5315
 5316                        if end_point == start_point {
 5317                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5318                                .saturating_sub(1);
 5319                            start_point = TP::to_point(&offset, &snapshot);
 5320                        };
 5321
 5322                        (start_point..end_point, empty_str.clone())
 5323                    })
 5324                    .sorted_by_key(|(range, _)| range.start)
 5325                    .collect::<Vec<_>>();
 5326                buffer.update(cx, |this, cx| {
 5327                    this.edit(edits, None, cx);
 5328                })
 5329            }
 5330            this.refresh_inline_completion(true, false, cx);
 5331            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5332        });
 5333    }
 5334
 5335    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5336        self.transact(cx, |this, cx| {
 5337            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5338                let line_mode = s.line_mode;
 5339                s.move_with(|map, selection| {
 5340                    if selection.is_empty() && !line_mode {
 5341                        let cursor = movement::right(map, selection.head());
 5342                        selection.end = cursor;
 5343                        selection.reversed = true;
 5344                        selection.goal = SelectionGoal::None;
 5345                    }
 5346                })
 5347            });
 5348            this.insert("", cx);
 5349            this.refresh_inline_completion(true, false, cx);
 5350        });
 5351    }
 5352
 5353    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5354        if self.move_to_prev_snippet_tabstop(cx) {
 5355            return;
 5356        }
 5357
 5358        self.outdent(&Outdent, cx);
 5359    }
 5360
 5361    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5362        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5363            return;
 5364        }
 5365
 5366        let mut selections = self.selections.all_adjusted(cx);
 5367        let buffer = self.buffer.read(cx);
 5368        let snapshot = buffer.snapshot(cx);
 5369        let rows_iter = selections.iter().map(|s| s.head().row);
 5370        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5371
 5372        let mut edits = Vec::new();
 5373        let mut prev_edited_row = 0;
 5374        let mut row_delta = 0;
 5375        for selection in &mut selections {
 5376            if selection.start.row != prev_edited_row {
 5377                row_delta = 0;
 5378            }
 5379            prev_edited_row = selection.end.row;
 5380
 5381            // If the selection is non-empty, then increase the indentation of the selected lines.
 5382            if !selection.is_empty() {
 5383                row_delta =
 5384                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5385                continue;
 5386            }
 5387
 5388            // If the selection is empty and the cursor is in the leading whitespace before the
 5389            // suggested indentation, then auto-indent the line.
 5390            let cursor = selection.head();
 5391            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5392            if let Some(suggested_indent) =
 5393                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5394            {
 5395                if cursor.column < suggested_indent.len
 5396                    && cursor.column <= current_indent.len
 5397                    && current_indent.len <= suggested_indent.len
 5398                {
 5399                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5400                    selection.end = selection.start;
 5401                    if row_delta == 0 {
 5402                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5403                            cursor.row,
 5404                            current_indent,
 5405                            suggested_indent,
 5406                        ));
 5407                        row_delta = suggested_indent.len - current_indent.len;
 5408                    }
 5409                    continue;
 5410                }
 5411            }
 5412
 5413            // Otherwise, insert a hard or soft tab.
 5414            let settings = buffer.settings_at(cursor, cx);
 5415            let tab_size = if settings.hard_tabs {
 5416                IndentSize::tab()
 5417            } else {
 5418                let tab_size = settings.tab_size.get();
 5419                let char_column = snapshot
 5420                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5421                    .flat_map(str::chars)
 5422                    .count()
 5423                    + row_delta as usize;
 5424                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5425                IndentSize::spaces(chars_to_next_tab_stop)
 5426            };
 5427            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5428            selection.end = selection.start;
 5429            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5430            row_delta += tab_size.len;
 5431        }
 5432
 5433        self.transact(cx, |this, cx| {
 5434            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5435            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5436            this.refresh_inline_completion(true, false, cx);
 5437        });
 5438    }
 5439
 5440    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5441        if self.read_only(cx) {
 5442            return;
 5443        }
 5444        let mut selections = self.selections.all::<Point>(cx);
 5445        let mut prev_edited_row = 0;
 5446        let mut row_delta = 0;
 5447        let mut edits = Vec::new();
 5448        let buffer = self.buffer.read(cx);
 5449        let snapshot = buffer.snapshot(cx);
 5450        for selection in &mut selections {
 5451            if selection.start.row != prev_edited_row {
 5452                row_delta = 0;
 5453            }
 5454            prev_edited_row = selection.end.row;
 5455
 5456            row_delta =
 5457                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5458        }
 5459
 5460        self.transact(cx, |this, cx| {
 5461            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5462            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5463        });
 5464    }
 5465
 5466    fn indent_selection(
 5467        buffer: &MultiBuffer,
 5468        snapshot: &MultiBufferSnapshot,
 5469        selection: &mut Selection<Point>,
 5470        edits: &mut Vec<(Range<Point>, String)>,
 5471        delta_for_start_row: u32,
 5472        cx: &AppContext,
 5473    ) -> u32 {
 5474        let settings = buffer.settings_at(selection.start, cx);
 5475        let tab_size = settings.tab_size.get();
 5476        let indent_kind = if settings.hard_tabs {
 5477            IndentKind::Tab
 5478        } else {
 5479            IndentKind::Space
 5480        };
 5481        let mut start_row = selection.start.row;
 5482        let mut end_row = selection.end.row + 1;
 5483
 5484        // If a selection ends at the beginning of a line, don't indent
 5485        // that last line.
 5486        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5487            end_row -= 1;
 5488        }
 5489
 5490        // Avoid re-indenting a row that has already been indented by a
 5491        // previous selection, but still update this selection's column
 5492        // to reflect that indentation.
 5493        if delta_for_start_row > 0 {
 5494            start_row += 1;
 5495            selection.start.column += delta_for_start_row;
 5496            if selection.end.row == selection.start.row {
 5497                selection.end.column += delta_for_start_row;
 5498            }
 5499        }
 5500
 5501        let mut delta_for_end_row = 0;
 5502        let has_multiple_rows = start_row + 1 != end_row;
 5503        for row in start_row..end_row {
 5504            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5505            let indent_delta = match (current_indent.kind, indent_kind) {
 5506                (IndentKind::Space, IndentKind::Space) => {
 5507                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5508                    IndentSize::spaces(columns_to_next_tab_stop)
 5509                }
 5510                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5511                (_, IndentKind::Tab) => IndentSize::tab(),
 5512            };
 5513
 5514            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5515                0
 5516            } else {
 5517                selection.start.column
 5518            };
 5519            let row_start = Point::new(row, start);
 5520            edits.push((
 5521                row_start..row_start,
 5522                indent_delta.chars().collect::<String>(),
 5523            ));
 5524
 5525            // Update this selection's endpoints to reflect the indentation.
 5526            if row == selection.start.row {
 5527                selection.start.column += indent_delta.len;
 5528            }
 5529            if row == selection.end.row {
 5530                selection.end.column += indent_delta.len;
 5531                delta_for_end_row = indent_delta.len;
 5532            }
 5533        }
 5534
 5535        if selection.start.row == selection.end.row {
 5536            delta_for_start_row + delta_for_end_row
 5537        } else {
 5538            delta_for_end_row
 5539        }
 5540    }
 5541
 5542    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5543        if self.read_only(cx) {
 5544            return;
 5545        }
 5546        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5547        let selections = self.selections.all::<Point>(cx);
 5548        let mut deletion_ranges = Vec::new();
 5549        let mut last_outdent = None;
 5550        {
 5551            let buffer = self.buffer.read(cx);
 5552            let snapshot = buffer.snapshot(cx);
 5553            for selection in &selections {
 5554                let settings = buffer.settings_at(selection.start, cx);
 5555                let tab_size = settings.tab_size.get();
 5556                let mut rows = selection.spanned_rows(false, &display_map);
 5557
 5558                // Avoid re-outdenting a row that has already been outdented by a
 5559                // previous selection.
 5560                if let Some(last_row) = last_outdent {
 5561                    if last_row == rows.start {
 5562                        rows.start = rows.start.next_row();
 5563                    }
 5564                }
 5565                let has_multiple_rows = rows.len() > 1;
 5566                for row in rows.iter_rows() {
 5567                    let indent_size = snapshot.indent_size_for_line(row);
 5568                    if indent_size.len > 0 {
 5569                        let deletion_len = match indent_size.kind {
 5570                            IndentKind::Space => {
 5571                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5572                                if columns_to_prev_tab_stop == 0 {
 5573                                    tab_size
 5574                                } else {
 5575                                    columns_to_prev_tab_stop
 5576                                }
 5577                            }
 5578                            IndentKind::Tab => 1,
 5579                        };
 5580                        let start = if has_multiple_rows
 5581                            || deletion_len > selection.start.column
 5582                            || indent_size.len < selection.start.column
 5583                        {
 5584                            0
 5585                        } else {
 5586                            selection.start.column - deletion_len
 5587                        };
 5588                        deletion_ranges.push(
 5589                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5590                        );
 5591                        last_outdent = Some(row);
 5592                    }
 5593                }
 5594            }
 5595        }
 5596
 5597        self.transact(cx, |this, cx| {
 5598            this.buffer.update(cx, |buffer, cx| {
 5599                let empty_str: Arc<str> = Arc::default();
 5600                buffer.edit(
 5601                    deletion_ranges
 5602                        .into_iter()
 5603                        .map(|range| (range, empty_str.clone())),
 5604                    None,
 5605                    cx,
 5606                );
 5607            });
 5608            let selections = this.selections.all::<usize>(cx);
 5609            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5610        });
 5611    }
 5612
 5613    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5614        if self.read_only(cx) {
 5615            return;
 5616        }
 5617        let selections = self
 5618            .selections
 5619            .all::<usize>(cx)
 5620            .into_iter()
 5621            .map(|s| s.range());
 5622
 5623        self.transact(cx, |this, cx| {
 5624            this.buffer.update(cx, |buffer, cx| {
 5625                buffer.autoindent_ranges(selections, cx);
 5626            });
 5627            let selections = this.selections.all::<usize>(cx);
 5628            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5629        });
 5630    }
 5631
 5632    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5633        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5634        let selections = self.selections.all::<Point>(cx);
 5635
 5636        let mut new_cursors = Vec::new();
 5637        let mut edit_ranges = Vec::new();
 5638        let mut selections = selections.iter().peekable();
 5639        while let Some(selection) = selections.next() {
 5640            let mut rows = selection.spanned_rows(false, &display_map);
 5641            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5642
 5643            // Accumulate contiguous regions of rows that we want to delete.
 5644            while let Some(next_selection) = selections.peek() {
 5645                let next_rows = next_selection.spanned_rows(false, &display_map);
 5646                if next_rows.start <= rows.end {
 5647                    rows.end = next_rows.end;
 5648                    selections.next().unwrap();
 5649                } else {
 5650                    break;
 5651                }
 5652            }
 5653
 5654            let buffer = &display_map.buffer_snapshot;
 5655            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5656            let edit_end;
 5657            let cursor_buffer_row;
 5658            if buffer.max_point().row >= rows.end.0 {
 5659                // If there's a line after the range, delete the \n from the end of the row range
 5660                // and position the cursor on the next line.
 5661                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5662                cursor_buffer_row = rows.end;
 5663            } else {
 5664                // If there isn't a line after the range, delete the \n from the line before the
 5665                // start of the row range and position the cursor there.
 5666                edit_start = edit_start.saturating_sub(1);
 5667                edit_end = buffer.len();
 5668                cursor_buffer_row = rows.start.previous_row();
 5669            }
 5670
 5671            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5672            *cursor.column_mut() =
 5673                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5674
 5675            new_cursors.push((
 5676                selection.id,
 5677                buffer.anchor_after(cursor.to_point(&display_map)),
 5678            ));
 5679            edit_ranges.push(edit_start..edit_end);
 5680        }
 5681
 5682        self.transact(cx, |this, cx| {
 5683            let buffer = this.buffer.update(cx, |buffer, cx| {
 5684                let empty_str: Arc<str> = Arc::default();
 5685                buffer.edit(
 5686                    edit_ranges
 5687                        .into_iter()
 5688                        .map(|range| (range, empty_str.clone())),
 5689                    None,
 5690                    cx,
 5691                );
 5692                buffer.snapshot(cx)
 5693            });
 5694            let new_selections = new_cursors
 5695                .into_iter()
 5696                .map(|(id, cursor)| {
 5697                    let cursor = cursor.to_point(&buffer);
 5698                    Selection {
 5699                        id,
 5700                        start: cursor,
 5701                        end: cursor,
 5702                        reversed: false,
 5703                        goal: SelectionGoal::None,
 5704                    }
 5705                })
 5706                .collect();
 5707
 5708            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5709                s.select(new_selections);
 5710            });
 5711        });
 5712    }
 5713
 5714    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5715        if self.read_only(cx) {
 5716            return;
 5717        }
 5718        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5719        for selection in self.selections.all::<Point>(cx) {
 5720            let start = MultiBufferRow(selection.start.row);
 5721            // Treat single line selections as if they include the next line. Otherwise this action
 5722            // would do nothing for single line selections individual cursors.
 5723            let end = if selection.start.row == selection.end.row {
 5724                MultiBufferRow(selection.start.row + 1)
 5725            } else {
 5726                MultiBufferRow(selection.end.row)
 5727            };
 5728
 5729            if let Some(last_row_range) = row_ranges.last_mut() {
 5730                if start <= last_row_range.end {
 5731                    last_row_range.end = end;
 5732                    continue;
 5733                }
 5734            }
 5735            row_ranges.push(start..end);
 5736        }
 5737
 5738        let snapshot = self.buffer.read(cx).snapshot(cx);
 5739        let mut cursor_positions = Vec::new();
 5740        for row_range in &row_ranges {
 5741            let anchor = snapshot.anchor_before(Point::new(
 5742                row_range.end.previous_row().0,
 5743                snapshot.line_len(row_range.end.previous_row()),
 5744            ));
 5745            cursor_positions.push(anchor..anchor);
 5746        }
 5747
 5748        self.transact(cx, |this, cx| {
 5749            for row_range in row_ranges.into_iter().rev() {
 5750                for row in row_range.iter_rows().rev() {
 5751                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5752                    let next_line_row = row.next_row();
 5753                    let indent = snapshot.indent_size_for_line(next_line_row);
 5754                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5755
 5756                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5757                        " "
 5758                    } else {
 5759                        ""
 5760                    };
 5761
 5762                    this.buffer.update(cx, |buffer, cx| {
 5763                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5764                    });
 5765                }
 5766            }
 5767
 5768            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5769                s.select_anchor_ranges(cursor_positions)
 5770            });
 5771        });
 5772    }
 5773
 5774    pub fn sort_lines_case_sensitive(
 5775        &mut self,
 5776        _: &SortLinesCaseSensitive,
 5777        cx: &mut ViewContext<Self>,
 5778    ) {
 5779        self.manipulate_lines(cx, |lines| lines.sort())
 5780    }
 5781
 5782    pub fn sort_lines_case_insensitive(
 5783        &mut self,
 5784        _: &SortLinesCaseInsensitive,
 5785        cx: &mut ViewContext<Self>,
 5786    ) {
 5787        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5788    }
 5789
 5790    pub fn unique_lines_case_insensitive(
 5791        &mut self,
 5792        _: &UniqueLinesCaseInsensitive,
 5793        cx: &mut ViewContext<Self>,
 5794    ) {
 5795        self.manipulate_lines(cx, |lines| {
 5796            let mut seen = HashSet::default();
 5797            lines.retain(|line| seen.insert(line.to_lowercase()));
 5798        })
 5799    }
 5800
 5801    pub fn unique_lines_case_sensitive(
 5802        &mut self,
 5803        _: &UniqueLinesCaseSensitive,
 5804        cx: &mut ViewContext<Self>,
 5805    ) {
 5806        self.manipulate_lines(cx, |lines| {
 5807            let mut seen = HashSet::default();
 5808            lines.retain(|line| seen.insert(*line));
 5809        })
 5810    }
 5811
 5812    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5813        let mut revert_changes = HashMap::default();
 5814        let snapshot = self.snapshot(cx);
 5815        for hunk in hunks_for_ranges(
 5816            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5817            &snapshot,
 5818        ) {
 5819            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5820        }
 5821        if !revert_changes.is_empty() {
 5822            self.transact(cx, |editor, cx| {
 5823                editor.revert(revert_changes, cx);
 5824            });
 5825        }
 5826    }
 5827
 5828    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5829        let Some(project) = self.project.clone() else {
 5830            return;
 5831        };
 5832        self.reload(project, cx).detach_and_notify_err(cx);
 5833    }
 5834
 5835    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5836        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5837        if !revert_changes.is_empty() {
 5838            self.transact(cx, |editor, cx| {
 5839                editor.revert(revert_changes, cx);
 5840            });
 5841        }
 5842    }
 5843
 5844    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5845        let snapshot = self.buffer.read(cx).read(cx);
 5846        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5847            drop(snapshot);
 5848            let mut revert_changes = HashMap::default();
 5849            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5850            if !revert_changes.is_empty() {
 5851                self.revert(revert_changes, cx)
 5852            }
 5853        }
 5854    }
 5855
 5856    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5857        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5858            let project_path = buffer.read(cx).project_path(cx)?;
 5859            let project = self.project.as_ref()?.read(cx);
 5860            let entry = project.entry_for_path(&project_path, cx)?;
 5861            let parent = match &entry.canonical_path {
 5862                Some(canonical_path) => canonical_path.to_path_buf(),
 5863                None => project.absolute_path(&project_path, cx)?,
 5864            }
 5865            .parent()?
 5866            .to_path_buf();
 5867            Some(parent)
 5868        }) {
 5869            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5870        }
 5871    }
 5872
 5873    fn gather_revert_changes(
 5874        &mut self,
 5875        selections: &[Selection<Point>],
 5876        cx: &mut ViewContext<'_, Editor>,
 5877    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5878        let mut revert_changes = HashMap::default();
 5879        let snapshot = self.snapshot(cx);
 5880        for hunk in hunks_for_selections(&snapshot, selections) {
 5881            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5882        }
 5883        revert_changes
 5884    }
 5885
 5886    pub fn prepare_revert_change(
 5887        &mut self,
 5888        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5889        hunk: &MultiBufferDiffHunk,
 5890        cx: &AppContext,
 5891    ) -> Option<()> {
 5892        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 5893        let buffer = buffer.read(cx);
 5894        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 5895        let original_text = change_set
 5896            .read(cx)
 5897            .base_text
 5898            .as_ref()?
 5899            .read(cx)
 5900            .as_rope()
 5901            .slice(hunk.diff_base_byte_range.clone());
 5902        let buffer_snapshot = buffer.snapshot();
 5903        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5904        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5905            probe
 5906                .0
 5907                .start
 5908                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5909                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5910        }) {
 5911            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5912            Some(())
 5913        } else {
 5914            None
 5915        }
 5916    }
 5917
 5918    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5919        self.manipulate_lines(cx, |lines| lines.reverse())
 5920    }
 5921
 5922    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5923        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5924    }
 5925
 5926    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5927    where
 5928        Fn: FnMut(&mut Vec<&str>),
 5929    {
 5930        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5931        let buffer = self.buffer.read(cx).snapshot(cx);
 5932
 5933        let mut edits = Vec::new();
 5934
 5935        let selections = self.selections.all::<Point>(cx);
 5936        let mut selections = selections.iter().peekable();
 5937        let mut contiguous_row_selections = Vec::new();
 5938        let mut new_selections = Vec::new();
 5939        let mut added_lines = 0;
 5940        let mut removed_lines = 0;
 5941
 5942        while let Some(selection) = selections.next() {
 5943            let (start_row, end_row) = consume_contiguous_rows(
 5944                &mut contiguous_row_selections,
 5945                selection,
 5946                &display_map,
 5947                &mut selections,
 5948            );
 5949
 5950            let start_point = Point::new(start_row.0, 0);
 5951            let end_point = Point::new(
 5952                end_row.previous_row().0,
 5953                buffer.line_len(end_row.previous_row()),
 5954            );
 5955            let text = buffer
 5956                .text_for_range(start_point..end_point)
 5957                .collect::<String>();
 5958
 5959            let mut lines = text.split('\n').collect_vec();
 5960
 5961            let lines_before = lines.len();
 5962            callback(&mut lines);
 5963            let lines_after = lines.len();
 5964
 5965            edits.push((start_point..end_point, lines.join("\n")));
 5966
 5967            // Selections must change based on added and removed line count
 5968            let start_row =
 5969                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5970            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5971            new_selections.push(Selection {
 5972                id: selection.id,
 5973                start: start_row,
 5974                end: end_row,
 5975                goal: SelectionGoal::None,
 5976                reversed: selection.reversed,
 5977            });
 5978
 5979            if lines_after > lines_before {
 5980                added_lines += lines_after - lines_before;
 5981            } else if lines_before > lines_after {
 5982                removed_lines += lines_before - lines_after;
 5983            }
 5984        }
 5985
 5986        self.transact(cx, |this, cx| {
 5987            let buffer = this.buffer.update(cx, |buffer, cx| {
 5988                buffer.edit(edits, None, cx);
 5989                buffer.snapshot(cx)
 5990            });
 5991
 5992            // Recalculate offsets on newly edited buffer
 5993            let new_selections = new_selections
 5994                .iter()
 5995                .map(|s| {
 5996                    let start_point = Point::new(s.start.0, 0);
 5997                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 5998                    Selection {
 5999                        id: s.id,
 6000                        start: buffer.point_to_offset(start_point),
 6001                        end: buffer.point_to_offset(end_point),
 6002                        goal: s.goal,
 6003                        reversed: s.reversed,
 6004                    }
 6005                })
 6006                .collect();
 6007
 6008            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6009                s.select(new_selections);
 6010            });
 6011
 6012            this.request_autoscroll(Autoscroll::fit(), cx);
 6013        });
 6014    }
 6015
 6016    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6017        self.manipulate_text(cx, |text| text.to_uppercase())
 6018    }
 6019
 6020    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6021        self.manipulate_text(cx, |text| text.to_lowercase())
 6022    }
 6023
 6024    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6025        self.manipulate_text(cx, |text| {
 6026            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6027            // https://github.com/rutrum/convert-case/issues/16
 6028            text.split('\n')
 6029                .map(|line| line.to_case(Case::Title))
 6030                .join("\n")
 6031        })
 6032    }
 6033
 6034    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6035        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6036    }
 6037
 6038    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6039        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6040    }
 6041
 6042    pub fn convert_to_upper_camel_case(
 6043        &mut self,
 6044        _: &ConvertToUpperCamelCase,
 6045        cx: &mut ViewContext<Self>,
 6046    ) {
 6047        self.manipulate_text(cx, |text| {
 6048            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6049            // https://github.com/rutrum/convert-case/issues/16
 6050            text.split('\n')
 6051                .map(|line| line.to_case(Case::UpperCamel))
 6052                .join("\n")
 6053        })
 6054    }
 6055
 6056    pub fn convert_to_lower_camel_case(
 6057        &mut self,
 6058        _: &ConvertToLowerCamelCase,
 6059        cx: &mut ViewContext<Self>,
 6060    ) {
 6061        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6062    }
 6063
 6064    pub fn convert_to_opposite_case(
 6065        &mut self,
 6066        _: &ConvertToOppositeCase,
 6067        cx: &mut ViewContext<Self>,
 6068    ) {
 6069        self.manipulate_text(cx, |text| {
 6070            text.chars()
 6071                .fold(String::with_capacity(text.len()), |mut t, c| {
 6072                    if c.is_uppercase() {
 6073                        t.extend(c.to_lowercase());
 6074                    } else {
 6075                        t.extend(c.to_uppercase());
 6076                    }
 6077                    t
 6078                })
 6079        })
 6080    }
 6081
 6082    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6083    where
 6084        Fn: FnMut(&str) -> String,
 6085    {
 6086        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6087        let buffer = self.buffer.read(cx).snapshot(cx);
 6088
 6089        let mut new_selections = Vec::new();
 6090        let mut edits = Vec::new();
 6091        let mut selection_adjustment = 0i32;
 6092
 6093        for selection in self.selections.all::<usize>(cx) {
 6094            let selection_is_empty = selection.is_empty();
 6095
 6096            let (start, end) = if selection_is_empty {
 6097                let word_range = movement::surrounding_word(
 6098                    &display_map,
 6099                    selection.start.to_display_point(&display_map),
 6100                );
 6101                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6102                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6103                (start, end)
 6104            } else {
 6105                (selection.start, selection.end)
 6106            };
 6107
 6108            let text = buffer.text_for_range(start..end).collect::<String>();
 6109            let old_length = text.len() as i32;
 6110            let text = callback(&text);
 6111
 6112            new_selections.push(Selection {
 6113                start: (start as i32 - selection_adjustment) as usize,
 6114                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6115                goal: SelectionGoal::None,
 6116                ..selection
 6117            });
 6118
 6119            selection_adjustment += old_length - text.len() as i32;
 6120
 6121            edits.push((start..end, text));
 6122        }
 6123
 6124        self.transact(cx, |this, cx| {
 6125            this.buffer.update(cx, |buffer, cx| {
 6126                buffer.edit(edits, None, cx);
 6127            });
 6128
 6129            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6130                s.select(new_selections);
 6131            });
 6132
 6133            this.request_autoscroll(Autoscroll::fit(), cx);
 6134        });
 6135    }
 6136
 6137    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6138        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6139        let buffer = &display_map.buffer_snapshot;
 6140        let selections = self.selections.all::<Point>(cx);
 6141
 6142        let mut edits = Vec::new();
 6143        let mut selections_iter = selections.iter().peekable();
 6144        while let Some(selection) = selections_iter.next() {
 6145            let mut rows = selection.spanned_rows(false, &display_map);
 6146            // duplicate line-wise
 6147            if whole_lines || selection.start == selection.end {
 6148                // Avoid duplicating the same lines twice.
 6149                while let Some(next_selection) = selections_iter.peek() {
 6150                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6151                    if next_rows.start < rows.end {
 6152                        rows.end = next_rows.end;
 6153                        selections_iter.next().unwrap();
 6154                    } else {
 6155                        break;
 6156                    }
 6157                }
 6158
 6159                // Copy the text from the selected row region and splice it either at the start
 6160                // or end of the region.
 6161                let start = Point::new(rows.start.0, 0);
 6162                let end = Point::new(
 6163                    rows.end.previous_row().0,
 6164                    buffer.line_len(rows.end.previous_row()),
 6165                );
 6166                let text = buffer
 6167                    .text_for_range(start..end)
 6168                    .chain(Some("\n"))
 6169                    .collect::<String>();
 6170                let insert_location = if upwards {
 6171                    Point::new(rows.end.0, 0)
 6172                } else {
 6173                    start
 6174                };
 6175                edits.push((insert_location..insert_location, text));
 6176            } else {
 6177                // duplicate character-wise
 6178                let start = selection.start;
 6179                let end = selection.end;
 6180                let text = buffer.text_for_range(start..end).collect::<String>();
 6181                edits.push((selection.end..selection.end, text));
 6182            }
 6183        }
 6184
 6185        self.transact(cx, |this, cx| {
 6186            this.buffer.update(cx, |buffer, cx| {
 6187                buffer.edit(edits, None, cx);
 6188            });
 6189
 6190            this.request_autoscroll(Autoscroll::fit(), cx);
 6191        });
 6192    }
 6193
 6194    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6195        self.duplicate(true, true, cx);
 6196    }
 6197
 6198    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6199        self.duplicate(false, true, cx);
 6200    }
 6201
 6202    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6203        self.duplicate(false, false, cx);
 6204    }
 6205
 6206    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6207        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6208        let buffer = self.buffer.read(cx).snapshot(cx);
 6209
 6210        let mut edits = Vec::new();
 6211        let mut unfold_ranges = Vec::new();
 6212        let mut refold_creases = Vec::new();
 6213
 6214        let selections = self.selections.all::<Point>(cx);
 6215        let mut selections = selections.iter().peekable();
 6216        let mut contiguous_row_selections = Vec::new();
 6217        let mut new_selections = Vec::new();
 6218
 6219        while let Some(selection) = selections.next() {
 6220            // Find all the selections that span a contiguous row range
 6221            let (start_row, end_row) = consume_contiguous_rows(
 6222                &mut contiguous_row_selections,
 6223                selection,
 6224                &display_map,
 6225                &mut selections,
 6226            );
 6227
 6228            // Move the text spanned by the row range to be before the line preceding the row range
 6229            if start_row.0 > 0 {
 6230                let range_to_move = Point::new(
 6231                    start_row.previous_row().0,
 6232                    buffer.line_len(start_row.previous_row()),
 6233                )
 6234                    ..Point::new(
 6235                        end_row.previous_row().0,
 6236                        buffer.line_len(end_row.previous_row()),
 6237                    );
 6238                let insertion_point = display_map
 6239                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6240                    .0;
 6241
 6242                // Don't move lines across excerpts
 6243                if buffer
 6244                    .excerpt_boundaries_in_range((
 6245                        Bound::Excluded(insertion_point),
 6246                        Bound::Included(range_to_move.end),
 6247                    ))
 6248                    .next()
 6249                    .is_none()
 6250                {
 6251                    let text = buffer
 6252                        .text_for_range(range_to_move.clone())
 6253                        .flat_map(|s| s.chars())
 6254                        .skip(1)
 6255                        .chain(['\n'])
 6256                        .collect::<String>();
 6257
 6258                    edits.push((
 6259                        buffer.anchor_after(range_to_move.start)
 6260                            ..buffer.anchor_before(range_to_move.end),
 6261                        String::new(),
 6262                    ));
 6263                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6264                    edits.push((insertion_anchor..insertion_anchor, text));
 6265
 6266                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6267
 6268                    // Move selections up
 6269                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6270                        |mut selection| {
 6271                            selection.start.row -= row_delta;
 6272                            selection.end.row -= row_delta;
 6273                            selection
 6274                        },
 6275                    ));
 6276
 6277                    // Move folds up
 6278                    unfold_ranges.push(range_to_move.clone());
 6279                    for fold in display_map.folds_in_range(
 6280                        buffer.anchor_before(range_to_move.start)
 6281                            ..buffer.anchor_after(range_to_move.end),
 6282                    ) {
 6283                        let mut start = fold.range.start.to_point(&buffer);
 6284                        let mut end = fold.range.end.to_point(&buffer);
 6285                        start.row -= row_delta;
 6286                        end.row -= row_delta;
 6287                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6288                    }
 6289                }
 6290            }
 6291
 6292            // If we didn't move line(s), preserve the existing selections
 6293            new_selections.append(&mut contiguous_row_selections);
 6294        }
 6295
 6296        self.transact(cx, |this, cx| {
 6297            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6298            this.buffer.update(cx, |buffer, cx| {
 6299                for (range, text) in edits {
 6300                    buffer.edit([(range, text)], None, cx);
 6301                }
 6302            });
 6303            this.fold_creases(refold_creases, true, cx);
 6304            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6305                s.select(new_selections);
 6306            })
 6307        });
 6308    }
 6309
 6310    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6311        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6312        let buffer = self.buffer.read(cx).snapshot(cx);
 6313
 6314        let mut edits = Vec::new();
 6315        let mut unfold_ranges = Vec::new();
 6316        let mut refold_creases = Vec::new();
 6317
 6318        let selections = self.selections.all::<Point>(cx);
 6319        let mut selections = selections.iter().peekable();
 6320        let mut contiguous_row_selections = Vec::new();
 6321        let mut new_selections = Vec::new();
 6322
 6323        while let Some(selection) = selections.next() {
 6324            // Find all the selections that span a contiguous row range
 6325            let (start_row, end_row) = consume_contiguous_rows(
 6326                &mut contiguous_row_selections,
 6327                selection,
 6328                &display_map,
 6329                &mut selections,
 6330            );
 6331
 6332            // Move the text spanned by the row range to be after the last line of the row range
 6333            if end_row.0 <= buffer.max_point().row {
 6334                let range_to_move =
 6335                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6336                let insertion_point = display_map
 6337                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6338                    .0;
 6339
 6340                // Don't move lines across excerpt boundaries
 6341                if buffer
 6342                    .excerpt_boundaries_in_range((
 6343                        Bound::Excluded(range_to_move.start),
 6344                        Bound::Included(insertion_point),
 6345                    ))
 6346                    .next()
 6347                    .is_none()
 6348                {
 6349                    let mut text = String::from("\n");
 6350                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6351                    text.pop(); // Drop trailing newline
 6352                    edits.push((
 6353                        buffer.anchor_after(range_to_move.start)
 6354                            ..buffer.anchor_before(range_to_move.end),
 6355                        String::new(),
 6356                    ));
 6357                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6358                    edits.push((insertion_anchor..insertion_anchor, text));
 6359
 6360                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6361
 6362                    // Move selections down
 6363                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6364                        |mut selection| {
 6365                            selection.start.row += row_delta;
 6366                            selection.end.row += row_delta;
 6367                            selection
 6368                        },
 6369                    ));
 6370
 6371                    // Move folds down
 6372                    unfold_ranges.push(range_to_move.clone());
 6373                    for fold in display_map.folds_in_range(
 6374                        buffer.anchor_before(range_to_move.start)
 6375                            ..buffer.anchor_after(range_to_move.end),
 6376                    ) {
 6377                        let mut start = fold.range.start.to_point(&buffer);
 6378                        let mut end = fold.range.end.to_point(&buffer);
 6379                        start.row += row_delta;
 6380                        end.row += row_delta;
 6381                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6382                    }
 6383                }
 6384            }
 6385
 6386            // If we didn't move line(s), preserve the existing selections
 6387            new_selections.append(&mut contiguous_row_selections);
 6388        }
 6389
 6390        self.transact(cx, |this, cx| {
 6391            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6392            this.buffer.update(cx, |buffer, cx| {
 6393                for (range, text) in edits {
 6394                    buffer.edit([(range, text)], None, cx);
 6395                }
 6396            });
 6397            this.fold_creases(refold_creases, true, cx);
 6398            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6399        });
 6400    }
 6401
 6402    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6403        let text_layout_details = &self.text_layout_details(cx);
 6404        self.transact(cx, |this, cx| {
 6405            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6406                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6407                let line_mode = s.line_mode;
 6408                s.move_with(|display_map, selection| {
 6409                    if !selection.is_empty() || line_mode {
 6410                        return;
 6411                    }
 6412
 6413                    let mut head = selection.head();
 6414                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6415                    if head.column() == display_map.line_len(head.row()) {
 6416                        transpose_offset = display_map
 6417                            .buffer_snapshot
 6418                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6419                    }
 6420
 6421                    if transpose_offset == 0 {
 6422                        return;
 6423                    }
 6424
 6425                    *head.column_mut() += 1;
 6426                    head = display_map.clip_point(head, Bias::Right);
 6427                    let goal = SelectionGoal::HorizontalPosition(
 6428                        display_map
 6429                            .x_for_display_point(head, text_layout_details)
 6430                            .into(),
 6431                    );
 6432                    selection.collapse_to(head, goal);
 6433
 6434                    let transpose_start = display_map
 6435                        .buffer_snapshot
 6436                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6437                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6438                        let transpose_end = display_map
 6439                            .buffer_snapshot
 6440                            .clip_offset(transpose_offset + 1, Bias::Right);
 6441                        if let Some(ch) =
 6442                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6443                        {
 6444                            edits.push((transpose_start..transpose_offset, String::new()));
 6445                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6446                        }
 6447                    }
 6448                });
 6449                edits
 6450            });
 6451            this.buffer
 6452                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6453            let selections = this.selections.all::<usize>(cx);
 6454            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6455                s.select(selections);
 6456            });
 6457        });
 6458    }
 6459
 6460    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6461        self.rewrap_impl(IsVimMode::No, cx)
 6462    }
 6463
 6464    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6465        let buffer = self.buffer.read(cx).snapshot(cx);
 6466        let selections = self.selections.all::<Point>(cx);
 6467        let mut selections = selections.iter().peekable();
 6468
 6469        let mut edits = Vec::new();
 6470        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6471
 6472        while let Some(selection) = selections.next() {
 6473            let mut start_row = selection.start.row;
 6474            let mut end_row = selection.end.row;
 6475
 6476            // Skip selections that overlap with a range that has already been rewrapped.
 6477            let selection_range = start_row..end_row;
 6478            if rewrapped_row_ranges
 6479                .iter()
 6480                .any(|range| range.overlaps(&selection_range))
 6481            {
 6482                continue;
 6483            }
 6484
 6485            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6486
 6487            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6488                match language_scope.language_name().0.as_ref() {
 6489                    "Markdown" | "Plain Text" => {
 6490                        should_rewrap = true;
 6491                    }
 6492                    _ => {}
 6493                }
 6494            }
 6495
 6496            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6497
 6498            // Since not all lines in the selection may be at the same indent
 6499            // level, choose the indent size that is the most common between all
 6500            // of the lines.
 6501            //
 6502            // If there is a tie, we use the deepest indent.
 6503            let (indent_size, indent_end) = {
 6504                let mut indent_size_occurrences = HashMap::default();
 6505                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6506
 6507                for row in start_row..=end_row {
 6508                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6509                    rows_by_indent_size.entry(indent).or_default().push(row);
 6510                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6511                }
 6512
 6513                let indent_size = indent_size_occurrences
 6514                    .into_iter()
 6515                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6516                    .map(|(indent, _)| indent)
 6517                    .unwrap_or_default();
 6518                let row = rows_by_indent_size[&indent_size][0];
 6519                let indent_end = Point::new(row, indent_size.len);
 6520
 6521                (indent_size, indent_end)
 6522            };
 6523
 6524            let mut line_prefix = indent_size.chars().collect::<String>();
 6525
 6526            if let Some(comment_prefix) =
 6527                buffer
 6528                    .language_scope_at(selection.head())
 6529                    .and_then(|language| {
 6530                        language
 6531                            .line_comment_prefixes()
 6532                            .iter()
 6533                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6534                            .cloned()
 6535                    })
 6536            {
 6537                line_prefix.push_str(&comment_prefix);
 6538                should_rewrap = true;
 6539            }
 6540
 6541            if !should_rewrap {
 6542                continue;
 6543            }
 6544
 6545            if selection.is_empty() {
 6546                'expand_upwards: while start_row > 0 {
 6547                    let prev_row = start_row - 1;
 6548                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6549                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6550                    {
 6551                        start_row = prev_row;
 6552                    } else {
 6553                        break 'expand_upwards;
 6554                    }
 6555                }
 6556
 6557                'expand_downwards: while end_row < buffer.max_point().row {
 6558                    let next_row = end_row + 1;
 6559                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6560                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6561                    {
 6562                        end_row = next_row;
 6563                    } else {
 6564                        break 'expand_downwards;
 6565                    }
 6566                }
 6567            }
 6568
 6569            let start = Point::new(start_row, 0);
 6570            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6571            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6572            let Some(lines_without_prefixes) = selection_text
 6573                .lines()
 6574                .map(|line| {
 6575                    line.strip_prefix(&line_prefix)
 6576                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6577                        .ok_or_else(|| {
 6578                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6579                        })
 6580                })
 6581                .collect::<Result<Vec<_>, _>>()
 6582                .log_err()
 6583            else {
 6584                continue;
 6585            };
 6586
 6587            let wrap_column = buffer
 6588                .settings_at(Point::new(start_row, 0), cx)
 6589                .preferred_line_length as usize;
 6590            let wrapped_text = wrap_with_prefix(
 6591                line_prefix,
 6592                lines_without_prefixes.join(" "),
 6593                wrap_column,
 6594                tab_size,
 6595            );
 6596
 6597            // TODO: should always use char-based diff while still supporting cursor behavior that
 6598            // matches vim.
 6599            let diff = match is_vim_mode {
 6600                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6601                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6602            };
 6603            let mut offset = start.to_offset(&buffer);
 6604            let mut moved_since_edit = true;
 6605
 6606            for change in diff.iter_all_changes() {
 6607                let value = change.value();
 6608                match change.tag() {
 6609                    ChangeTag::Equal => {
 6610                        offset += value.len();
 6611                        moved_since_edit = true;
 6612                    }
 6613                    ChangeTag::Delete => {
 6614                        let start = buffer.anchor_after(offset);
 6615                        let end = buffer.anchor_before(offset + value.len());
 6616
 6617                        if moved_since_edit {
 6618                            edits.push((start..end, String::new()));
 6619                        } else {
 6620                            edits.last_mut().unwrap().0.end = end;
 6621                        }
 6622
 6623                        offset += value.len();
 6624                        moved_since_edit = false;
 6625                    }
 6626                    ChangeTag::Insert => {
 6627                        if moved_since_edit {
 6628                            let anchor = buffer.anchor_after(offset);
 6629                            edits.push((anchor..anchor, value.to_string()));
 6630                        } else {
 6631                            edits.last_mut().unwrap().1.push_str(value);
 6632                        }
 6633
 6634                        moved_since_edit = false;
 6635                    }
 6636                }
 6637            }
 6638
 6639            rewrapped_row_ranges.push(start_row..=end_row);
 6640        }
 6641
 6642        self.buffer
 6643            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6644    }
 6645
 6646    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6647        let mut text = String::new();
 6648        let buffer = self.buffer.read(cx).snapshot(cx);
 6649        let mut selections = self.selections.all::<Point>(cx);
 6650        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6651        {
 6652            let max_point = buffer.max_point();
 6653            let mut is_first = true;
 6654            for selection in &mut selections {
 6655                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6656                if is_entire_line {
 6657                    selection.start = Point::new(selection.start.row, 0);
 6658                    if !selection.is_empty() && selection.end.column == 0 {
 6659                        selection.end = cmp::min(max_point, selection.end);
 6660                    } else {
 6661                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6662                    }
 6663                    selection.goal = SelectionGoal::None;
 6664                }
 6665                if is_first {
 6666                    is_first = false;
 6667                } else {
 6668                    text += "\n";
 6669                }
 6670                let mut len = 0;
 6671                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6672                    text.push_str(chunk);
 6673                    len += chunk.len();
 6674                }
 6675                clipboard_selections.push(ClipboardSelection {
 6676                    len,
 6677                    is_entire_line,
 6678                    first_line_indent: buffer
 6679                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6680                        .len,
 6681                });
 6682            }
 6683        }
 6684
 6685        self.transact(cx, |this, cx| {
 6686            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6687                s.select(selections);
 6688            });
 6689            this.insert("", cx);
 6690        });
 6691        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6692    }
 6693
 6694    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6695        let item = self.cut_common(cx);
 6696        cx.write_to_clipboard(item);
 6697    }
 6698
 6699    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6700        self.change_selections(None, cx, |s| {
 6701            s.move_with(|snapshot, sel| {
 6702                if sel.is_empty() {
 6703                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6704                }
 6705            });
 6706        });
 6707        let item = self.cut_common(cx);
 6708        cx.set_global(KillRing(item))
 6709    }
 6710
 6711    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6712        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6713            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6714                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6715            } else {
 6716                return;
 6717            }
 6718        } else {
 6719            return;
 6720        };
 6721        self.do_paste(&text, metadata, false, cx);
 6722    }
 6723
 6724    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6725        let selections = self.selections.all::<Point>(cx);
 6726        let buffer = self.buffer.read(cx).read(cx);
 6727        let mut text = String::new();
 6728
 6729        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6730        {
 6731            let max_point = buffer.max_point();
 6732            let mut is_first = true;
 6733            for selection in selections.iter() {
 6734                let mut start = selection.start;
 6735                let mut end = selection.end;
 6736                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6737                if is_entire_line {
 6738                    start = Point::new(start.row, 0);
 6739                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6740                }
 6741                if is_first {
 6742                    is_first = false;
 6743                } else {
 6744                    text += "\n";
 6745                }
 6746                let mut len = 0;
 6747                for chunk in buffer.text_for_range(start..end) {
 6748                    text.push_str(chunk);
 6749                    len += chunk.len();
 6750                }
 6751                clipboard_selections.push(ClipboardSelection {
 6752                    len,
 6753                    is_entire_line,
 6754                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6755                });
 6756            }
 6757        }
 6758
 6759        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6760            text,
 6761            clipboard_selections,
 6762        ));
 6763    }
 6764
 6765    pub fn do_paste(
 6766        &mut self,
 6767        text: &String,
 6768        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6769        handle_entire_lines: bool,
 6770        cx: &mut ViewContext<Self>,
 6771    ) {
 6772        if self.read_only(cx) {
 6773            return;
 6774        }
 6775
 6776        let clipboard_text = Cow::Borrowed(text);
 6777
 6778        self.transact(cx, |this, cx| {
 6779            if let Some(mut clipboard_selections) = clipboard_selections {
 6780                let old_selections = this.selections.all::<usize>(cx);
 6781                let all_selections_were_entire_line =
 6782                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6783                let first_selection_indent_column =
 6784                    clipboard_selections.first().map(|s| s.first_line_indent);
 6785                if clipboard_selections.len() != old_selections.len() {
 6786                    clipboard_selections.drain(..);
 6787                }
 6788                let cursor_offset = this.selections.last::<usize>(cx).head();
 6789                let mut auto_indent_on_paste = true;
 6790
 6791                this.buffer.update(cx, |buffer, cx| {
 6792                    let snapshot = buffer.read(cx);
 6793                    auto_indent_on_paste =
 6794                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6795
 6796                    let mut start_offset = 0;
 6797                    let mut edits = Vec::new();
 6798                    let mut original_indent_columns = Vec::new();
 6799                    for (ix, selection) in old_selections.iter().enumerate() {
 6800                        let to_insert;
 6801                        let entire_line;
 6802                        let original_indent_column;
 6803                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6804                            let end_offset = start_offset + clipboard_selection.len;
 6805                            to_insert = &clipboard_text[start_offset..end_offset];
 6806                            entire_line = clipboard_selection.is_entire_line;
 6807                            start_offset = end_offset + 1;
 6808                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6809                        } else {
 6810                            to_insert = clipboard_text.as_str();
 6811                            entire_line = all_selections_were_entire_line;
 6812                            original_indent_column = first_selection_indent_column
 6813                        }
 6814
 6815                        // If the corresponding selection was empty when this slice of the
 6816                        // clipboard text was written, then the entire line containing the
 6817                        // selection was copied. If this selection is also currently empty,
 6818                        // then paste the line before the current line of the buffer.
 6819                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6820                            let column = selection.start.to_point(&snapshot).column as usize;
 6821                            let line_start = selection.start - column;
 6822                            line_start..line_start
 6823                        } else {
 6824                            selection.range()
 6825                        };
 6826
 6827                        edits.push((range, to_insert));
 6828                        original_indent_columns.extend(original_indent_column);
 6829                    }
 6830                    drop(snapshot);
 6831
 6832                    buffer.edit(
 6833                        edits,
 6834                        if auto_indent_on_paste {
 6835                            Some(AutoindentMode::Block {
 6836                                original_indent_columns,
 6837                            })
 6838                        } else {
 6839                            None
 6840                        },
 6841                        cx,
 6842                    );
 6843                });
 6844
 6845                let selections = this.selections.all::<usize>(cx);
 6846                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6847            } else {
 6848                this.insert(&clipboard_text, cx);
 6849            }
 6850        });
 6851    }
 6852
 6853    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6854        if let Some(item) = cx.read_from_clipboard() {
 6855            let entries = item.entries();
 6856
 6857            match entries.first() {
 6858                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6859                // of all the pasted entries.
 6860                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6861                    .do_paste(
 6862                        clipboard_string.text(),
 6863                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 6864                        true,
 6865                        cx,
 6866                    ),
 6867                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 6868            }
 6869        }
 6870    }
 6871
 6872    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6873        if self.read_only(cx) {
 6874            return;
 6875        }
 6876
 6877        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6878            if let Some((selections, _)) =
 6879                self.selection_history.transaction(transaction_id).cloned()
 6880            {
 6881                self.change_selections(None, cx, |s| {
 6882                    s.select_anchors(selections.to_vec());
 6883                });
 6884            }
 6885            self.request_autoscroll(Autoscroll::fit(), cx);
 6886            self.unmark_text(cx);
 6887            self.refresh_inline_completion(true, false, cx);
 6888            cx.emit(EditorEvent::Edited { transaction_id });
 6889            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6890        }
 6891    }
 6892
 6893    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6894        if self.read_only(cx) {
 6895            return;
 6896        }
 6897
 6898        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6899            if let Some((_, Some(selections))) =
 6900                self.selection_history.transaction(transaction_id).cloned()
 6901            {
 6902                self.change_selections(None, cx, |s| {
 6903                    s.select_anchors(selections.to_vec());
 6904                });
 6905            }
 6906            self.request_autoscroll(Autoscroll::fit(), cx);
 6907            self.unmark_text(cx);
 6908            self.refresh_inline_completion(true, false, cx);
 6909            cx.emit(EditorEvent::Edited { transaction_id });
 6910        }
 6911    }
 6912
 6913    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6914        self.buffer
 6915            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6916    }
 6917
 6918    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6919        self.buffer
 6920            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6921    }
 6922
 6923    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6924        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6925            let line_mode = s.line_mode;
 6926            s.move_with(|map, selection| {
 6927                let cursor = if selection.is_empty() && !line_mode {
 6928                    movement::left(map, selection.start)
 6929                } else {
 6930                    selection.start
 6931                };
 6932                selection.collapse_to(cursor, SelectionGoal::None);
 6933            });
 6934        })
 6935    }
 6936
 6937    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6938        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6939            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6940        })
 6941    }
 6942
 6943    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6944        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6945            let line_mode = s.line_mode;
 6946            s.move_with(|map, selection| {
 6947                let cursor = if selection.is_empty() && !line_mode {
 6948                    movement::right(map, selection.end)
 6949                } else {
 6950                    selection.end
 6951                };
 6952                selection.collapse_to(cursor, SelectionGoal::None)
 6953            });
 6954        })
 6955    }
 6956
 6957    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6958        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6959            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6960        })
 6961    }
 6962
 6963    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6964        if self.take_rename(true, cx).is_some() {
 6965            return;
 6966        }
 6967
 6968        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6969            cx.propagate();
 6970            return;
 6971        }
 6972
 6973        let text_layout_details = &self.text_layout_details(cx);
 6974        let selection_count = self.selections.count();
 6975        let first_selection = self.selections.first_anchor();
 6976
 6977        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6978            let line_mode = s.line_mode;
 6979            s.move_with(|map, selection| {
 6980                if !selection.is_empty() && !line_mode {
 6981                    selection.goal = SelectionGoal::None;
 6982                }
 6983                let (cursor, goal) = movement::up(
 6984                    map,
 6985                    selection.start,
 6986                    selection.goal,
 6987                    false,
 6988                    text_layout_details,
 6989                );
 6990                selection.collapse_to(cursor, goal);
 6991            });
 6992        });
 6993
 6994        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6995        {
 6996            cx.propagate();
 6997        }
 6998    }
 6999
 7000    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7001        if self.take_rename(true, cx).is_some() {
 7002            return;
 7003        }
 7004
 7005        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7006            cx.propagate();
 7007            return;
 7008        }
 7009
 7010        let text_layout_details = &self.text_layout_details(cx);
 7011
 7012        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7013            let line_mode = s.line_mode;
 7014            s.move_with(|map, selection| {
 7015                if !selection.is_empty() && !line_mode {
 7016                    selection.goal = SelectionGoal::None;
 7017                }
 7018                let (cursor, goal) = movement::up_by_rows(
 7019                    map,
 7020                    selection.start,
 7021                    action.lines,
 7022                    selection.goal,
 7023                    false,
 7024                    text_layout_details,
 7025                );
 7026                selection.collapse_to(cursor, goal);
 7027            });
 7028        })
 7029    }
 7030
 7031    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7032        if self.take_rename(true, cx).is_some() {
 7033            return;
 7034        }
 7035
 7036        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7037            cx.propagate();
 7038            return;
 7039        }
 7040
 7041        let text_layout_details = &self.text_layout_details(cx);
 7042
 7043        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7044            let line_mode = s.line_mode;
 7045            s.move_with(|map, selection| {
 7046                if !selection.is_empty() && !line_mode {
 7047                    selection.goal = SelectionGoal::None;
 7048                }
 7049                let (cursor, goal) = movement::down_by_rows(
 7050                    map,
 7051                    selection.start,
 7052                    action.lines,
 7053                    selection.goal,
 7054                    false,
 7055                    text_layout_details,
 7056                );
 7057                selection.collapse_to(cursor, goal);
 7058            });
 7059        })
 7060    }
 7061
 7062    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7063        let text_layout_details = &self.text_layout_details(cx);
 7064        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7065            s.move_heads_with(|map, head, goal| {
 7066                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7067            })
 7068        })
 7069    }
 7070
 7071    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7072        let text_layout_details = &self.text_layout_details(cx);
 7073        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7074            s.move_heads_with(|map, head, goal| {
 7075                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7076            })
 7077        })
 7078    }
 7079
 7080    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7081        let Some(row_count) = self.visible_row_count() else {
 7082            return;
 7083        };
 7084
 7085        let text_layout_details = &self.text_layout_details(cx);
 7086
 7087        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7088            s.move_heads_with(|map, head, goal| {
 7089                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7090            })
 7091        })
 7092    }
 7093
 7094    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7095        if self.take_rename(true, cx).is_some() {
 7096            return;
 7097        }
 7098
 7099        if self
 7100            .context_menu
 7101            .borrow_mut()
 7102            .as_mut()
 7103            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7104            .unwrap_or(false)
 7105        {
 7106            return;
 7107        }
 7108
 7109        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7110            cx.propagate();
 7111            return;
 7112        }
 7113
 7114        let Some(row_count) = self.visible_row_count() else {
 7115            return;
 7116        };
 7117
 7118        let autoscroll = if action.center_cursor {
 7119            Autoscroll::center()
 7120        } else {
 7121            Autoscroll::fit()
 7122        };
 7123
 7124        let text_layout_details = &self.text_layout_details(cx);
 7125
 7126        self.change_selections(Some(autoscroll), cx, |s| {
 7127            let line_mode = s.line_mode;
 7128            s.move_with(|map, selection| {
 7129                if !selection.is_empty() && !line_mode {
 7130                    selection.goal = SelectionGoal::None;
 7131                }
 7132                let (cursor, goal) = movement::up_by_rows(
 7133                    map,
 7134                    selection.end,
 7135                    row_count,
 7136                    selection.goal,
 7137                    false,
 7138                    text_layout_details,
 7139                );
 7140                selection.collapse_to(cursor, goal);
 7141            });
 7142        });
 7143    }
 7144
 7145    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7146        let text_layout_details = &self.text_layout_details(cx);
 7147        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7148            s.move_heads_with(|map, head, goal| {
 7149                movement::up(map, head, goal, false, text_layout_details)
 7150            })
 7151        })
 7152    }
 7153
 7154    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7155        self.take_rename(true, cx);
 7156
 7157        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7158            cx.propagate();
 7159            return;
 7160        }
 7161
 7162        let text_layout_details = &self.text_layout_details(cx);
 7163        let selection_count = self.selections.count();
 7164        let first_selection = self.selections.first_anchor();
 7165
 7166        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7167            let line_mode = s.line_mode;
 7168            s.move_with(|map, selection| {
 7169                if !selection.is_empty() && !line_mode {
 7170                    selection.goal = SelectionGoal::None;
 7171                }
 7172                let (cursor, goal) = movement::down(
 7173                    map,
 7174                    selection.end,
 7175                    selection.goal,
 7176                    false,
 7177                    text_layout_details,
 7178                );
 7179                selection.collapse_to(cursor, goal);
 7180            });
 7181        });
 7182
 7183        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7184        {
 7185            cx.propagate();
 7186        }
 7187    }
 7188
 7189    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7190        let Some(row_count) = self.visible_row_count() else {
 7191            return;
 7192        };
 7193
 7194        let text_layout_details = &self.text_layout_details(cx);
 7195
 7196        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7197            s.move_heads_with(|map, head, goal| {
 7198                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7199            })
 7200        })
 7201    }
 7202
 7203    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7204        if self.take_rename(true, cx).is_some() {
 7205            return;
 7206        }
 7207
 7208        if self
 7209            .context_menu
 7210            .borrow_mut()
 7211            .as_mut()
 7212            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7213            .unwrap_or(false)
 7214        {
 7215            return;
 7216        }
 7217
 7218        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7219            cx.propagate();
 7220            return;
 7221        }
 7222
 7223        let Some(row_count) = self.visible_row_count() else {
 7224            return;
 7225        };
 7226
 7227        let autoscroll = if action.center_cursor {
 7228            Autoscroll::center()
 7229        } else {
 7230            Autoscroll::fit()
 7231        };
 7232
 7233        let text_layout_details = &self.text_layout_details(cx);
 7234        self.change_selections(Some(autoscroll), cx, |s| {
 7235            let line_mode = s.line_mode;
 7236            s.move_with(|map, selection| {
 7237                if !selection.is_empty() && !line_mode {
 7238                    selection.goal = SelectionGoal::None;
 7239                }
 7240                let (cursor, goal) = movement::down_by_rows(
 7241                    map,
 7242                    selection.end,
 7243                    row_count,
 7244                    selection.goal,
 7245                    false,
 7246                    text_layout_details,
 7247                );
 7248                selection.collapse_to(cursor, goal);
 7249            });
 7250        });
 7251    }
 7252
 7253    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7254        let text_layout_details = &self.text_layout_details(cx);
 7255        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7256            s.move_heads_with(|map, head, goal| {
 7257                movement::down(map, head, goal, false, text_layout_details)
 7258            })
 7259        });
 7260    }
 7261
 7262    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7263        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7264            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7265        }
 7266    }
 7267
 7268    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7269        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7270            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7271        }
 7272    }
 7273
 7274    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7275        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7276            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7277        }
 7278    }
 7279
 7280    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7281        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7282            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7283        }
 7284    }
 7285
 7286    pub fn move_to_previous_word_start(
 7287        &mut self,
 7288        _: &MoveToPreviousWordStart,
 7289        cx: &mut ViewContext<Self>,
 7290    ) {
 7291        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7292            s.move_cursors_with(|map, head, _| {
 7293                (
 7294                    movement::previous_word_start(map, head),
 7295                    SelectionGoal::None,
 7296                )
 7297            });
 7298        })
 7299    }
 7300
 7301    pub fn move_to_previous_subword_start(
 7302        &mut self,
 7303        _: &MoveToPreviousSubwordStart,
 7304        cx: &mut ViewContext<Self>,
 7305    ) {
 7306        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7307            s.move_cursors_with(|map, head, _| {
 7308                (
 7309                    movement::previous_subword_start(map, head),
 7310                    SelectionGoal::None,
 7311                )
 7312            });
 7313        })
 7314    }
 7315
 7316    pub fn select_to_previous_word_start(
 7317        &mut self,
 7318        _: &SelectToPreviousWordStart,
 7319        cx: &mut ViewContext<Self>,
 7320    ) {
 7321        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7322            s.move_heads_with(|map, head, _| {
 7323                (
 7324                    movement::previous_word_start(map, head),
 7325                    SelectionGoal::None,
 7326                )
 7327            });
 7328        })
 7329    }
 7330
 7331    pub fn select_to_previous_subword_start(
 7332        &mut self,
 7333        _: &SelectToPreviousSubwordStart,
 7334        cx: &mut ViewContext<Self>,
 7335    ) {
 7336        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7337            s.move_heads_with(|map, head, _| {
 7338                (
 7339                    movement::previous_subword_start(map, head),
 7340                    SelectionGoal::None,
 7341                )
 7342            });
 7343        })
 7344    }
 7345
 7346    pub fn delete_to_previous_word_start(
 7347        &mut self,
 7348        action: &DeleteToPreviousWordStart,
 7349        cx: &mut ViewContext<Self>,
 7350    ) {
 7351        self.transact(cx, |this, cx| {
 7352            this.select_autoclose_pair(cx);
 7353            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7354                let line_mode = s.line_mode;
 7355                s.move_with(|map, selection| {
 7356                    if selection.is_empty() && !line_mode {
 7357                        let cursor = if action.ignore_newlines {
 7358                            movement::previous_word_start(map, selection.head())
 7359                        } else {
 7360                            movement::previous_word_start_or_newline(map, selection.head())
 7361                        };
 7362                        selection.set_head(cursor, SelectionGoal::None);
 7363                    }
 7364                });
 7365            });
 7366            this.insert("", cx);
 7367        });
 7368    }
 7369
 7370    pub fn delete_to_previous_subword_start(
 7371        &mut self,
 7372        _: &DeleteToPreviousSubwordStart,
 7373        cx: &mut ViewContext<Self>,
 7374    ) {
 7375        self.transact(cx, |this, cx| {
 7376            this.select_autoclose_pair(cx);
 7377            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7378                let line_mode = s.line_mode;
 7379                s.move_with(|map, selection| {
 7380                    if selection.is_empty() && !line_mode {
 7381                        let cursor = movement::previous_subword_start(map, selection.head());
 7382                        selection.set_head(cursor, SelectionGoal::None);
 7383                    }
 7384                });
 7385            });
 7386            this.insert("", cx);
 7387        });
 7388    }
 7389
 7390    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7391        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7392            s.move_cursors_with(|map, head, _| {
 7393                (movement::next_word_end(map, head), SelectionGoal::None)
 7394            });
 7395        })
 7396    }
 7397
 7398    pub fn move_to_next_subword_end(
 7399        &mut self,
 7400        _: &MoveToNextSubwordEnd,
 7401        cx: &mut ViewContext<Self>,
 7402    ) {
 7403        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7404            s.move_cursors_with(|map, head, _| {
 7405                (movement::next_subword_end(map, head), SelectionGoal::None)
 7406            });
 7407        })
 7408    }
 7409
 7410    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7411        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7412            s.move_heads_with(|map, head, _| {
 7413                (movement::next_word_end(map, head), SelectionGoal::None)
 7414            });
 7415        })
 7416    }
 7417
 7418    pub fn select_to_next_subword_end(
 7419        &mut self,
 7420        _: &SelectToNextSubwordEnd,
 7421        cx: &mut ViewContext<Self>,
 7422    ) {
 7423        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7424            s.move_heads_with(|map, head, _| {
 7425                (movement::next_subword_end(map, head), SelectionGoal::None)
 7426            });
 7427        })
 7428    }
 7429
 7430    pub fn delete_to_next_word_end(
 7431        &mut self,
 7432        action: &DeleteToNextWordEnd,
 7433        cx: &mut ViewContext<Self>,
 7434    ) {
 7435        self.transact(cx, |this, cx| {
 7436            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7437                let line_mode = s.line_mode;
 7438                s.move_with(|map, selection| {
 7439                    if selection.is_empty() && !line_mode {
 7440                        let cursor = if action.ignore_newlines {
 7441                            movement::next_word_end(map, selection.head())
 7442                        } else {
 7443                            movement::next_word_end_or_newline(map, selection.head())
 7444                        };
 7445                        selection.set_head(cursor, SelectionGoal::None);
 7446                    }
 7447                });
 7448            });
 7449            this.insert("", cx);
 7450        });
 7451    }
 7452
 7453    pub fn delete_to_next_subword_end(
 7454        &mut self,
 7455        _: &DeleteToNextSubwordEnd,
 7456        cx: &mut ViewContext<Self>,
 7457    ) {
 7458        self.transact(cx, |this, cx| {
 7459            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7460                s.move_with(|map, selection| {
 7461                    if selection.is_empty() {
 7462                        let cursor = movement::next_subword_end(map, selection.head());
 7463                        selection.set_head(cursor, SelectionGoal::None);
 7464                    }
 7465                });
 7466            });
 7467            this.insert("", cx);
 7468        });
 7469    }
 7470
 7471    pub fn move_to_beginning_of_line(
 7472        &mut self,
 7473        action: &MoveToBeginningOfLine,
 7474        cx: &mut ViewContext<Self>,
 7475    ) {
 7476        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7477            s.move_cursors_with(|map, head, _| {
 7478                (
 7479                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7480                    SelectionGoal::None,
 7481                )
 7482            });
 7483        })
 7484    }
 7485
 7486    pub fn select_to_beginning_of_line(
 7487        &mut self,
 7488        action: &SelectToBeginningOfLine,
 7489        cx: &mut ViewContext<Self>,
 7490    ) {
 7491        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7492            s.move_heads_with(|map, head, _| {
 7493                (
 7494                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7495                    SelectionGoal::None,
 7496                )
 7497            });
 7498        });
 7499    }
 7500
 7501    pub fn delete_to_beginning_of_line(
 7502        &mut self,
 7503        _: &DeleteToBeginningOfLine,
 7504        cx: &mut ViewContext<Self>,
 7505    ) {
 7506        self.transact(cx, |this, cx| {
 7507            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7508                s.move_with(|_, selection| {
 7509                    selection.reversed = true;
 7510                });
 7511            });
 7512
 7513            this.select_to_beginning_of_line(
 7514                &SelectToBeginningOfLine {
 7515                    stop_at_soft_wraps: false,
 7516                },
 7517                cx,
 7518            );
 7519            this.backspace(&Backspace, cx);
 7520        });
 7521    }
 7522
 7523    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7524        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7525            s.move_cursors_with(|map, head, _| {
 7526                (
 7527                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7528                    SelectionGoal::None,
 7529                )
 7530            });
 7531        })
 7532    }
 7533
 7534    pub fn select_to_end_of_line(
 7535        &mut self,
 7536        action: &SelectToEndOfLine,
 7537        cx: &mut ViewContext<Self>,
 7538    ) {
 7539        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7540            s.move_heads_with(|map, head, _| {
 7541                (
 7542                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7543                    SelectionGoal::None,
 7544                )
 7545            });
 7546        })
 7547    }
 7548
 7549    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7550        self.transact(cx, |this, cx| {
 7551            this.select_to_end_of_line(
 7552                &SelectToEndOfLine {
 7553                    stop_at_soft_wraps: false,
 7554                },
 7555                cx,
 7556            );
 7557            this.delete(&Delete, cx);
 7558        });
 7559    }
 7560
 7561    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7562        self.transact(cx, |this, cx| {
 7563            this.select_to_end_of_line(
 7564                &SelectToEndOfLine {
 7565                    stop_at_soft_wraps: false,
 7566                },
 7567                cx,
 7568            );
 7569            this.cut(&Cut, cx);
 7570        });
 7571    }
 7572
 7573    pub fn move_to_start_of_paragraph(
 7574        &mut self,
 7575        _: &MoveToStartOfParagraph,
 7576        cx: &mut ViewContext<Self>,
 7577    ) {
 7578        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7579            cx.propagate();
 7580            return;
 7581        }
 7582
 7583        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7584            s.move_with(|map, selection| {
 7585                selection.collapse_to(
 7586                    movement::start_of_paragraph(map, selection.head(), 1),
 7587                    SelectionGoal::None,
 7588                )
 7589            });
 7590        })
 7591    }
 7592
 7593    pub fn move_to_end_of_paragraph(
 7594        &mut self,
 7595        _: &MoveToEndOfParagraph,
 7596        cx: &mut ViewContext<Self>,
 7597    ) {
 7598        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7599            cx.propagate();
 7600            return;
 7601        }
 7602
 7603        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7604            s.move_with(|map, selection| {
 7605                selection.collapse_to(
 7606                    movement::end_of_paragraph(map, selection.head(), 1),
 7607                    SelectionGoal::None,
 7608                )
 7609            });
 7610        })
 7611    }
 7612
 7613    pub fn select_to_start_of_paragraph(
 7614        &mut self,
 7615        _: &SelectToStartOfParagraph,
 7616        cx: &mut ViewContext<Self>,
 7617    ) {
 7618        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7619            cx.propagate();
 7620            return;
 7621        }
 7622
 7623        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7624            s.move_heads_with(|map, head, _| {
 7625                (
 7626                    movement::start_of_paragraph(map, head, 1),
 7627                    SelectionGoal::None,
 7628                )
 7629            });
 7630        })
 7631    }
 7632
 7633    pub fn select_to_end_of_paragraph(
 7634        &mut self,
 7635        _: &SelectToEndOfParagraph,
 7636        cx: &mut ViewContext<Self>,
 7637    ) {
 7638        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7639            cx.propagate();
 7640            return;
 7641        }
 7642
 7643        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7644            s.move_heads_with(|map, head, _| {
 7645                (
 7646                    movement::end_of_paragraph(map, head, 1),
 7647                    SelectionGoal::None,
 7648                )
 7649            });
 7650        })
 7651    }
 7652
 7653    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7654        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7655            cx.propagate();
 7656            return;
 7657        }
 7658
 7659        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7660            s.select_ranges(vec![0..0]);
 7661        });
 7662    }
 7663
 7664    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7665        let mut selection = self.selections.last::<Point>(cx);
 7666        selection.set_head(Point::zero(), SelectionGoal::None);
 7667
 7668        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7669            s.select(vec![selection]);
 7670        });
 7671    }
 7672
 7673    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7674        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7675            cx.propagate();
 7676            return;
 7677        }
 7678
 7679        let cursor = self.buffer.read(cx).read(cx).len();
 7680        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7681            s.select_ranges(vec![cursor..cursor])
 7682        });
 7683    }
 7684
 7685    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7686        self.nav_history = nav_history;
 7687    }
 7688
 7689    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7690        self.nav_history.as_ref()
 7691    }
 7692
 7693    fn push_to_nav_history(
 7694        &mut self,
 7695        cursor_anchor: Anchor,
 7696        new_position: Option<Point>,
 7697        cx: &mut ViewContext<Self>,
 7698    ) {
 7699        if let Some(nav_history) = self.nav_history.as_mut() {
 7700            let buffer = self.buffer.read(cx).read(cx);
 7701            let cursor_position = cursor_anchor.to_point(&buffer);
 7702            let scroll_state = self.scroll_manager.anchor();
 7703            let scroll_top_row = scroll_state.top_row(&buffer);
 7704            drop(buffer);
 7705
 7706            if let Some(new_position) = new_position {
 7707                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7708                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7709                    return;
 7710                }
 7711            }
 7712
 7713            nav_history.push(
 7714                Some(NavigationData {
 7715                    cursor_anchor,
 7716                    cursor_position,
 7717                    scroll_anchor: scroll_state,
 7718                    scroll_top_row,
 7719                }),
 7720                cx,
 7721            );
 7722        }
 7723    }
 7724
 7725    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7726        let buffer = self.buffer.read(cx).snapshot(cx);
 7727        let mut selection = self.selections.first::<usize>(cx);
 7728        selection.set_head(buffer.len(), SelectionGoal::None);
 7729        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7730            s.select(vec![selection]);
 7731        });
 7732    }
 7733
 7734    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7735        let end = self.buffer.read(cx).read(cx).len();
 7736        self.change_selections(None, cx, |s| {
 7737            s.select_ranges(vec![0..end]);
 7738        });
 7739    }
 7740
 7741    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7742        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7743        let mut selections = self.selections.all::<Point>(cx);
 7744        let max_point = display_map.buffer_snapshot.max_point();
 7745        for selection in &mut selections {
 7746            let rows = selection.spanned_rows(true, &display_map);
 7747            selection.start = Point::new(rows.start.0, 0);
 7748            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7749            selection.reversed = false;
 7750        }
 7751        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7752            s.select(selections);
 7753        });
 7754    }
 7755
 7756    pub fn split_selection_into_lines(
 7757        &mut self,
 7758        _: &SplitSelectionIntoLines,
 7759        cx: &mut ViewContext<Self>,
 7760    ) {
 7761        let mut to_unfold = Vec::new();
 7762        let mut new_selection_ranges = Vec::new();
 7763        {
 7764            let selections = self.selections.all::<Point>(cx);
 7765            let buffer = self.buffer.read(cx).read(cx);
 7766            for selection in selections {
 7767                for row in selection.start.row..selection.end.row {
 7768                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7769                    new_selection_ranges.push(cursor..cursor);
 7770                }
 7771                new_selection_ranges.push(selection.end..selection.end);
 7772                to_unfold.push(selection.start..selection.end);
 7773            }
 7774        }
 7775        self.unfold_ranges(&to_unfold, true, true, cx);
 7776        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7777            s.select_ranges(new_selection_ranges);
 7778        });
 7779    }
 7780
 7781    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7782        self.add_selection(true, cx);
 7783    }
 7784
 7785    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7786        self.add_selection(false, cx);
 7787    }
 7788
 7789    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7790        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7791        let mut selections = self.selections.all::<Point>(cx);
 7792        let text_layout_details = self.text_layout_details(cx);
 7793        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7794            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7795            let range = oldest_selection.display_range(&display_map).sorted();
 7796
 7797            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7798            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7799            let positions = start_x.min(end_x)..start_x.max(end_x);
 7800
 7801            selections.clear();
 7802            let mut stack = Vec::new();
 7803            for row in range.start.row().0..=range.end.row().0 {
 7804                if let Some(selection) = self.selections.build_columnar_selection(
 7805                    &display_map,
 7806                    DisplayRow(row),
 7807                    &positions,
 7808                    oldest_selection.reversed,
 7809                    &text_layout_details,
 7810                ) {
 7811                    stack.push(selection.id);
 7812                    selections.push(selection);
 7813                }
 7814            }
 7815
 7816            if above {
 7817                stack.reverse();
 7818            }
 7819
 7820            AddSelectionsState { above, stack }
 7821        });
 7822
 7823        let last_added_selection = *state.stack.last().unwrap();
 7824        let mut new_selections = Vec::new();
 7825        if above == state.above {
 7826            let end_row = if above {
 7827                DisplayRow(0)
 7828            } else {
 7829                display_map.max_point().row()
 7830            };
 7831
 7832            'outer: for selection in selections {
 7833                if selection.id == last_added_selection {
 7834                    let range = selection.display_range(&display_map).sorted();
 7835                    debug_assert_eq!(range.start.row(), range.end.row());
 7836                    let mut row = range.start.row();
 7837                    let positions =
 7838                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7839                            px(start)..px(end)
 7840                        } else {
 7841                            let start_x =
 7842                                display_map.x_for_display_point(range.start, &text_layout_details);
 7843                            let end_x =
 7844                                display_map.x_for_display_point(range.end, &text_layout_details);
 7845                            start_x.min(end_x)..start_x.max(end_x)
 7846                        };
 7847
 7848                    while row != end_row {
 7849                        if above {
 7850                            row.0 -= 1;
 7851                        } else {
 7852                            row.0 += 1;
 7853                        }
 7854
 7855                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7856                            &display_map,
 7857                            row,
 7858                            &positions,
 7859                            selection.reversed,
 7860                            &text_layout_details,
 7861                        ) {
 7862                            state.stack.push(new_selection.id);
 7863                            if above {
 7864                                new_selections.push(new_selection);
 7865                                new_selections.push(selection);
 7866                            } else {
 7867                                new_selections.push(selection);
 7868                                new_selections.push(new_selection);
 7869                            }
 7870
 7871                            continue 'outer;
 7872                        }
 7873                    }
 7874                }
 7875
 7876                new_selections.push(selection);
 7877            }
 7878        } else {
 7879            new_selections = selections;
 7880            new_selections.retain(|s| s.id != last_added_selection);
 7881            state.stack.pop();
 7882        }
 7883
 7884        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7885            s.select(new_selections);
 7886        });
 7887        if state.stack.len() > 1 {
 7888            self.add_selections_state = Some(state);
 7889        }
 7890    }
 7891
 7892    pub fn select_next_match_internal(
 7893        &mut self,
 7894        display_map: &DisplaySnapshot,
 7895        replace_newest: bool,
 7896        autoscroll: Option<Autoscroll>,
 7897        cx: &mut ViewContext<Self>,
 7898    ) -> Result<()> {
 7899        fn select_next_match_ranges(
 7900            this: &mut Editor,
 7901            range: Range<usize>,
 7902            replace_newest: bool,
 7903            auto_scroll: Option<Autoscroll>,
 7904            cx: &mut ViewContext<Editor>,
 7905        ) {
 7906            this.unfold_ranges(&[range.clone()], false, true, cx);
 7907            this.change_selections(auto_scroll, cx, |s| {
 7908                if replace_newest {
 7909                    s.delete(s.newest_anchor().id);
 7910                }
 7911                s.insert_range(range.clone());
 7912            });
 7913        }
 7914
 7915        let buffer = &display_map.buffer_snapshot;
 7916        let mut selections = self.selections.all::<usize>(cx);
 7917        if let Some(mut select_next_state) = self.select_next_state.take() {
 7918            let query = &select_next_state.query;
 7919            if !select_next_state.done {
 7920                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7921                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7922                let mut next_selected_range = None;
 7923
 7924                let bytes_after_last_selection =
 7925                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7926                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7927                let query_matches = query
 7928                    .stream_find_iter(bytes_after_last_selection)
 7929                    .map(|result| (last_selection.end, result))
 7930                    .chain(
 7931                        query
 7932                            .stream_find_iter(bytes_before_first_selection)
 7933                            .map(|result| (0, result)),
 7934                    );
 7935
 7936                for (start_offset, query_match) in query_matches {
 7937                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7938                    let offset_range =
 7939                        start_offset + query_match.start()..start_offset + query_match.end();
 7940                    let display_range = offset_range.start.to_display_point(display_map)
 7941                        ..offset_range.end.to_display_point(display_map);
 7942
 7943                    if !select_next_state.wordwise
 7944                        || (!movement::is_inside_word(display_map, display_range.start)
 7945                            && !movement::is_inside_word(display_map, display_range.end))
 7946                    {
 7947                        // TODO: This is n^2, because we might check all the selections
 7948                        if !selections
 7949                            .iter()
 7950                            .any(|selection| selection.range().overlaps(&offset_range))
 7951                        {
 7952                            next_selected_range = Some(offset_range);
 7953                            break;
 7954                        }
 7955                    }
 7956                }
 7957
 7958                if let Some(next_selected_range) = next_selected_range {
 7959                    select_next_match_ranges(
 7960                        self,
 7961                        next_selected_range,
 7962                        replace_newest,
 7963                        autoscroll,
 7964                        cx,
 7965                    );
 7966                } else {
 7967                    select_next_state.done = true;
 7968                }
 7969            }
 7970
 7971            self.select_next_state = Some(select_next_state);
 7972        } else {
 7973            let mut only_carets = true;
 7974            let mut same_text_selected = true;
 7975            let mut selected_text = None;
 7976
 7977            let mut selections_iter = selections.iter().peekable();
 7978            while let Some(selection) = selections_iter.next() {
 7979                if selection.start != selection.end {
 7980                    only_carets = false;
 7981                }
 7982
 7983                if same_text_selected {
 7984                    if selected_text.is_none() {
 7985                        selected_text =
 7986                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7987                    }
 7988
 7989                    if let Some(next_selection) = selections_iter.peek() {
 7990                        if next_selection.range().len() == selection.range().len() {
 7991                            let next_selected_text = buffer
 7992                                .text_for_range(next_selection.range())
 7993                                .collect::<String>();
 7994                            if Some(next_selected_text) != selected_text {
 7995                                same_text_selected = false;
 7996                                selected_text = None;
 7997                            }
 7998                        } else {
 7999                            same_text_selected = false;
 8000                            selected_text = None;
 8001                        }
 8002                    }
 8003                }
 8004            }
 8005
 8006            if only_carets {
 8007                for selection in &mut selections {
 8008                    let word_range = movement::surrounding_word(
 8009                        display_map,
 8010                        selection.start.to_display_point(display_map),
 8011                    );
 8012                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8013                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8014                    selection.goal = SelectionGoal::None;
 8015                    selection.reversed = false;
 8016                    select_next_match_ranges(
 8017                        self,
 8018                        selection.start..selection.end,
 8019                        replace_newest,
 8020                        autoscroll,
 8021                        cx,
 8022                    );
 8023                }
 8024
 8025                if selections.len() == 1 {
 8026                    let selection = selections
 8027                        .last()
 8028                        .expect("ensured that there's only one selection");
 8029                    let query = buffer
 8030                        .text_for_range(selection.start..selection.end)
 8031                        .collect::<String>();
 8032                    let is_empty = query.is_empty();
 8033                    let select_state = SelectNextState {
 8034                        query: AhoCorasick::new(&[query])?,
 8035                        wordwise: true,
 8036                        done: is_empty,
 8037                    };
 8038                    self.select_next_state = Some(select_state);
 8039                } else {
 8040                    self.select_next_state = None;
 8041                }
 8042            } else if let Some(selected_text) = selected_text {
 8043                self.select_next_state = Some(SelectNextState {
 8044                    query: AhoCorasick::new(&[selected_text])?,
 8045                    wordwise: false,
 8046                    done: false,
 8047                });
 8048                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8049            }
 8050        }
 8051        Ok(())
 8052    }
 8053
 8054    pub fn select_all_matches(
 8055        &mut self,
 8056        _action: &SelectAllMatches,
 8057        cx: &mut ViewContext<Self>,
 8058    ) -> Result<()> {
 8059        self.push_to_selection_history();
 8060        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8061
 8062        self.select_next_match_internal(&display_map, false, None, cx)?;
 8063        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8064            return Ok(());
 8065        };
 8066        if select_next_state.done {
 8067            return Ok(());
 8068        }
 8069
 8070        let mut new_selections = self.selections.all::<usize>(cx);
 8071
 8072        let buffer = &display_map.buffer_snapshot;
 8073        let query_matches = select_next_state
 8074            .query
 8075            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8076
 8077        for query_match in query_matches {
 8078            let query_match = query_match.unwrap(); // can only fail due to I/O
 8079            let offset_range = query_match.start()..query_match.end();
 8080            let display_range = offset_range.start.to_display_point(&display_map)
 8081                ..offset_range.end.to_display_point(&display_map);
 8082
 8083            if !select_next_state.wordwise
 8084                || (!movement::is_inside_word(&display_map, display_range.start)
 8085                    && !movement::is_inside_word(&display_map, display_range.end))
 8086            {
 8087                self.selections.change_with(cx, |selections| {
 8088                    new_selections.push(Selection {
 8089                        id: selections.new_selection_id(),
 8090                        start: offset_range.start,
 8091                        end: offset_range.end,
 8092                        reversed: false,
 8093                        goal: SelectionGoal::None,
 8094                    });
 8095                });
 8096            }
 8097        }
 8098
 8099        new_selections.sort_by_key(|selection| selection.start);
 8100        let mut ix = 0;
 8101        while ix + 1 < new_selections.len() {
 8102            let current_selection = &new_selections[ix];
 8103            let next_selection = &new_selections[ix + 1];
 8104            if current_selection.range().overlaps(&next_selection.range()) {
 8105                if current_selection.id < next_selection.id {
 8106                    new_selections.remove(ix + 1);
 8107                } else {
 8108                    new_selections.remove(ix);
 8109                }
 8110            } else {
 8111                ix += 1;
 8112            }
 8113        }
 8114
 8115        select_next_state.done = true;
 8116        self.unfold_ranges(
 8117            &new_selections
 8118                .iter()
 8119                .map(|selection| selection.range())
 8120                .collect::<Vec<_>>(),
 8121            false,
 8122            false,
 8123            cx,
 8124        );
 8125        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8126            selections.select(new_selections)
 8127        });
 8128
 8129        Ok(())
 8130    }
 8131
 8132    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8133        self.push_to_selection_history();
 8134        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8135        self.select_next_match_internal(
 8136            &display_map,
 8137            action.replace_newest,
 8138            Some(Autoscroll::newest()),
 8139            cx,
 8140        )?;
 8141        Ok(())
 8142    }
 8143
 8144    pub fn select_previous(
 8145        &mut self,
 8146        action: &SelectPrevious,
 8147        cx: &mut ViewContext<Self>,
 8148    ) -> Result<()> {
 8149        self.push_to_selection_history();
 8150        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8151        let buffer = &display_map.buffer_snapshot;
 8152        let mut selections = self.selections.all::<usize>(cx);
 8153        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8154            let query = &select_prev_state.query;
 8155            if !select_prev_state.done {
 8156                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8157                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8158                let mut next_selected_range = None;
 8159                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8160                let bytes_before_last_selection =
 8161                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8162                let bytes_after_first_selection =
 8163                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8164                let query_matches = query
 8165                    .stream_find_iter(bytes_before_last_selection)
 8166                    .map(|result| (last_selection.start, result))
 8167                    .chain(
 8168                        query
 8169                            .stream_find_iter(bytes_after_first_selection)
 8170                            .map(|result| (buffer.len(), result)),
 8171                    );
 8172                for (end_offset, query_match) in query_matches {
 8173                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8174                    let offset_range =
 8175                        end_offset - query_match.end()..end_offset - query_match.start();
 8176                    let display_range = offset_range.start.to_display_point(&display_map)
 8177                        ..offset_range.end.to_display_point(&display_map);
 8178
 8179                    if !select_prev_state.wordwise
 8180                        || (!movement::is_inside_word(&display_map, display_range.start)
 8181                            && !movement::is_inside_word(&display_map, display_range.end))
 8182                    {
 8183                        next_selected_range = Some(offset_range);
 8184                        break;
 8185                    }
 8186                }
 8187
 8188                if let Some(next_selected_range) = next_selected_range {
 8189                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8190                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8191                        if action.replace_newest {
 8192                            s.delete(s.newest_anchor().id);
 8193                        }
 8194                        s.insert_range(next_selected_range);
 8195                    });
 8196                } else {
 8197                    select_prev_state.done = true;
 8198                }
 8199            }
 8200
 8201            self.select_prev_state = Some(select_prev_state);
 8202        } else {
 8203            let mut only_carets = true;
 8204            let mut same_text_selected = true;
 8205            let mut selected_text = None;
 8206
 8207            let mut selections_iter = selections.iter().peekable();
 8208            while let Some(selection) = selections_iter.next() {
 8209                if selection.start != selection.end {
 8210                    only_carets = false;
 8211                }
 8212
 8213                if same_text_selected {
 8214                    if selected_text.is_none() {
 8215                        selected_text =
 8216                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8217                    }
 8218
 8219                    if let Some(next_selection) = selections_iter.peek() {
 8220                        if next_selection.range().len() == selection.range().len() {
 8221                            let next_selected_text = buffer
 8222                                .text_for_range(next_selection.range())
 8223                                .collect::<String>();
 8224                            if Some(next_selected_text) != selected_text {
 8225                                same_text_selected = false;
 8226                                selected_text = None;
 8227                            }
 8228                        } else {
 8229                            same_text_selected = false;
 8230                            selected_text = None;
 8231                        }
 8232                    }
 8233                }
 8234            }
 8235
 8236            if only_carets {
 8237                for selection in &mut selections {
 8238                    let word_range = movement::surrounding_word(
 8239                        &display_map,
 8240                        selection.start.to_display_point(&display_map),
 8241                    );
 8242                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8243                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8244                    selection.goal = SelectionGoal::None;
 8245                    selection.reversed = false;
 8246                }
 8247                if selections.len() == 1 {
 8248                    let selection = selections
 8249                        .last()
 8250                        .expect("ensured that there's only one selection");
 8251                    let query = buffer
 8252                        .text_for_range(selection.start..selection.end)
 8253                        .collect::<String>();
 8254                    let is_empty = query.is_empty();
 8255                    let select_state = SelectNextState {
 8256                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8257                        wordwise: true,
 8258                        done: is_empty,
 8259                    };
 8260                    self.select_prev_state = Some(select_state);
 8261                } else {
 8262                    self.select_prev_state = None;
 8263                }
 8264
 8265                self.unfold_ranges(
 8266                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8267                    false,
 8268                    true,
 8269                    cx,
 8270                );
 8271                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8272                    s.select(selections);
 8273                });
 8274            } else if let Some(selected_text) = selected_text {
 8275                self.select_prev_state = Some(SelectNextState {
 8276                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8277                    wordwise: false,
 8278                    done: false,
 8279                });
 8280                self.select_previous(action, cx)?;
 8281            }
 8282        }
 8283        Ok(())
 8284    }
 8285
 8286    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8287        if self.read_only(cx) {
 8288            return;
 8289        }
 8290        let text_layout_details = &self.text_layout_details(cx);
 8291        self.transact(cx, |this, cx| {
 8292            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8293            let mut edits = Vec::new();
 8294            let mut selection_edit_ranges = Vec::new();
 8295            let mut last_toggled_row = None;
 8296            let snapshot = this.buffer.read(cx).read(cx);
 8297            let empty_str: Arc<str> = Arc::default();
 8298            let mut suffixes_inserted = Vec::new();
 8299            let ignore_indent = action.ignore_indent;
 8300
 8301            fn comment_prefix_range(
 8302                snapshot: &MultiBufferSnapshot,
 8303                row: MultiBufferRow,
 8304                comment_prefix: &str,
 8305                comment_prefix_whitespace: &str,
 8306                ignore_indent: bool,
 8307            ) -> Range<Point> {
 8308                let indent_size = if ignore_indent {
 8309                    0
 8310                } else {
 8311                    snapshot.indent_size_for_line(row).len
 8312                };
 8313
 8314                let start = Point::new(row.0, indent_size);
 8315
 8316                let mut line_bytes = snapshot
 8317                    .bytes_in_range(start..snapshot.max_point())
 8318                    .flatten()
 8319                    .copied();
 8320
 8321                // If this line currently begins with the line comment prefix, then record
 8322                // the range containing the prefix.
 8323                if line_bytes
 8324                    .by_ref()
 8325                    .take(comment_prefix.len())
 8326                    .eq(comment_prefix.bytes())
 8327                {
 8328                    // Include any whitespace that matches the comment prefix.
 8329                    let matching_whitespace_len = line_bytes
 8330                        .zip(comment_prefix_whitespace.bytes())
 8331                        .take_while(|(a, b)| a == b)
 8332                        .count() as u32;
 8333                    let end = Point::new(
 8334                        start.row,
 8335                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8336                    );
 8337                    start..end
 8338                } else {
 8339                    start..start
 8340                }
 8341            }
 8342
 8343            fn comment_suffix_range(
 8344                snapshot: &MultiBufferSnapshot,
 8345                row: MultiBufferRow,
 8346                comment_suffix: &str,
 8347                comment_suffix_has_leading_space: bool,
 8348            ) -> Range<Point> {
 8349                let end = Point::new(row.0, snapshot.line_len(row));
 8350                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8351
 8352                let mut line_end_bytes = snapshot
 8353                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8354                    .flatten()
 8355                    .copied();
 8356
 8357                let leading_space_len = if suffix_start_column > 0
 8358                    && line_end_bytes.next() == Some(b' ')
 8359                    && comment_suffix_has_leading_space
 8360                {
 8361                    1
 8362                } else {
 8363                    0
 8364                };
 8365
 8366                // If this line currently begins with the line comment prefix, then record
 8367                // the range containing the prefix.
 8368                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8369                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8370                    start..end
 8371                } else {
 8372                    end..end
 8373                }
 8374            }
 8375
 8376            // TODO: Handle selections that cross excerpts
 8377            for selection in &mut selections {
 8378                let start_column = snapshot
 8379                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8380                    .len;
 8381                let language = if let Some(language) =
 8382                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8383                {
 8384                    language
 8385                } else {
 8386                    continue;
 8387                };
 8388
 8389                selection_edit_ranges.clear();
 8390
 8391                // If multiple selections contain a given row, avoid processing that
 8392                // row more than once.
 8393                let mut start_row = MultiBufferRow(selection.start.row);
 8394                if last_toggled_row == Some(start_row) {
 8395                    start_row = start_row.next_row();
 8396                }
 8397                let end_row =
 8398                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8399                        MultiBufferRow(selection.end.row - 1)
 8400                    } else {
 8401                        MultiBufferRow(selection.end.row)
 8402                    };
 8403                last_toggled_row = Some(end_row);
 8404
 8405                if start_row > end_row {
 8406                    continue;
 8407                }
 8408
 8409                // If the language has line comments, toggle those.
 8410                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8411
 8412                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8413                if ignore_indent {
 8414                    full_comment_prefixes = full_comment_prefixes
 8415                        .into_iter()
 8416                        .map(|s| Arc::from(s.trim_end()))
 8417                        .collect();
 8418                }
 8419
 8420                if !full_comment_prefixes.is_empty() {
 8421                    let first_prefix = full_comment_prefixes
 8422                        .first()
 8423                        .expect("prefixes is non-empty");
 8424                    let prefix_trimmed_lengths = full_comment_prefixes
 8425                        .iter()
 8426                        .map(|p| p.trim_end_matches(' ').len())
 8427                        .collect::<SmallVec<[usize; 4]>>();
 8428
 8429                    let mut all_selection_lines_are_comments = true;
 8430
 8431                    for row in start_row.0..=end_row.0 {
 8432                        let row = MultiBufferRow(row);
 8433                        if start_row < end_row && snapshot.is_line_blank(row) {
 8434                            continue;
 8435                        }
 8436
 8437                        let prefix_range = full_comment_prefixes
 8438                            .iter()
 8439                            .zip(prefix_trimmed_lengths.iter().copied())
 8440                            .map(|(prefix, trimmed_prefix_len)| {
 8441                                comment_prefix_range(
 8442                                    snapshot.deref(),
 8443                                    row,
 8444                                    &prefix[..trimmed_prefix_len],
 8445                                    &prefix[trimmed_prefix_len..],
 8446                                    ignore_indent,
 8447                                )
 8448                            })
 8449                            .max_by_key(|range| range.end.column - range.start.column)
 8450                            .expect("prefixes is non-empty");
 8451
 8452                        if prefix_range.is_empty() {
 8453                            all_selection_lines_are_comments = false;
 8454                        }
 8455
 8456                        selection_edit_ranges.push(prefix_range);
 8457                    }
 8458
 8459                    if all_selection_lines_are_comments {
 8460                        edits.extend(
 8461                            selection_edit_ranges
 8462                                .iter()
 8463                                .cloned()
 8464                                .map(|range| (range, empty_str.clone())),
 8465                        );
 8466                    } else {
 8467                        let min_column = selection_edit_ranges
 8468                            .iter()
 8469                            .map(|range| range.start.column)
 8470                            .min()
 8471                            .unwrap_or(0);
 8472                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8473                            let position = Point::new(range.start.row, min_column);
 8474                            (position..position, first_prefix.clone())
 8475                        }));
 8476                    }
 8477                } else if let Some((full_comment_prefix, comment_suffix)) =
 8478                    language.block_comment_delimiters()
 8479                {
 8480                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8481                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8482                    let prefix_range = comment_prefix_range(
 8483                        snapshot.deref(),
 8484                        start_row,
 8485                        comment_prefix,
 8486                        comment_prefix_whitespace,
 8487                        ignore_indent,
 8488                    );
 8489                    let suffix_range = comment_suffix_range(
 8490                        snapshot.deref(),
 8491                        end_row,
 8492                        comment_suffix.trim_start_matches(' '),
 8493                        comment_suffix.starts_with(' '),
 8494                    );
 8495
 8496                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8497                        edits.push((
 8498                            prefix_range.start..prefix_range.start,
 8499                            full_comment_prefix.clone(),
 8500                        ));
 8501                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8502                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8503                    } else {
 8504                        edits.push((prefix_range, empty_str.clone()));
 8505                        edits.push((suffix_range, empty_str.clone()));
 8506                    }
 8507                } else {
 8508                    continue;
 8509                }
 8510            }
 8511
 8512            drop(snapshot);
 8513            this.buffer.update(cx, |buffer, cx| {
 8514                buffer.edit(edits, None, cx);
 8515            });
 8516
 8517            // Adjust selections so that they end before any comment suffixes that
 8518            // were inserted.
 8519            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8520            let mut selections = this.selections.all::<Point>(cx);
 8521            let snapshot = this.buffer.read(cx).read(cx);
 8522            for selection in &mut selections {
 8523                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8524                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8525                        Ordering::Less => {
 8526                            suffixes_inserted.next();
 8527                            continue;
 8528                        }
 8529                        Ordering::Greater => break,
 8530                        Ordering::Equal => {
 8531                            if selection.end.column == snapshot.line_len(row) {
 8532                                if selection.is_empty() {
 8533                                    selection.start.column -= suffix_len as u32;
 8534                                }
 8535                                selection.end.column -= suffix_len as u32;
 8536                            }
 8537                            break;
 8538                        }
 8539                    }
 8540                }
 8541            }
 8542
 8543            drop(snapshot);
 8544            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8545
 8546            let selections = this.selections.all::<Point>(cx);
 8547            let selections_on_single_row = selections.windows(2).all(|selections| {
 8548                selections[0].start.row == selections[1].start.row
 8549                    && selections[0].end.row == selections[1].end.row
 8550                    && selections[0].start.row == selections[0].end.row
 8551            });
 8552            let selections_selecting = selections
 8553                .iter()
 8554                .any(|selection| selection.start != selection.end);
 8555            let advance_downwards = action.advance_downwards
 8556                && selections_on_single_row
 8557                && !selections_selecting
 8558                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8559
 8560            if advance_downwards {
 8561                let snapshot = this.buffer.read(cx).snapshot(cx);
 8562
 8563                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8564                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8565                        let mut point = display_point.to_point(display_snapshot);
 8566                        point.row += 1;
 8567                        point = snapshot.clip_point(point, Bias::Left);
 8568                        let display_point = point.to_display_point(display_snapshot);
 8569                        let goal = SelectionGoal::HorizontalPosition(
 8570                            display_snapshot
 8571                                .x_for_display_point(display_point, text_layout_details)
 8572                                .into(),
 8573                        );
 8574                        (display_point, goal)
 8575                    })
 8576                });
 8577            }
 8578        });
 8579    }
 8580
 8581    pub fn select_enclosing_symbol(
 8582        &mut self,
 8583        _: &SelectEnclosingSymbol,
 8584        cx: &mut ViewContext<Self>,
 8585    ) {
 8586        let buffer = self.buffer.read(cx).snapshot(cx);
 8587        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8588
 8589        fn update_selection(
 8590            selection: &Selection<usize>,
 8591            buffer_snap: &MultiBufferSnapshot,
 8592        ) -> Option<Selection<usize>> {
 8593            let cursor = selection.head();
 8594            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8595            for symbol in symbols.iter().rev() {
 8596                let start = symbol.range.start.to_offset(buffer_snap);
 8597                let end = symbol.range.end.to_offset(buffer_snap);
 8598                let new_range = start..end;
 8599                if start < selection.start || end > selection.end {
 8600                    return Some(Selection {
 8601                        id: selection.id,
 8602                        start: new_range.start,
 8603                        end: new_range.end,
 8604                        goal: SelectionGoal::None,
 8605                        reversed: selection.reversed,
 8606                    });
 8607                }
 8608            }
 8609            None
 8610        }
 8611
 8612        let mut selected_larger_symbol = false;
 8613        let new_selections = old_selections
 8614            .iter()
 8615            .map(|selection| match update_selection(selection, &buffer) {
 8616                Some(new_selection) => {
 8617                    if new_selection.range() != selection.range() {
 8618                        selected_larger_symbol = true;
 8619                    }
 8620                    new_selection
 8621                }
 8622                None => selection.clone(),
 8623            })
 8624            .collect::<Vec<_>>();
 8625
 8626        if selected_larger_symbol {
 8627            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8628                s.select(new_selections);
 8629            });
 8630        }
 8631    }
 8632
 8633    pub fn select_larger_syntax_node(
 8634        &mut self,
 8635        _: &SelectLargerSyntaxNode,
 8636        cx: &mut ViewContext<Self>,
 8637    ) {
 8638        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8639        let buffer = self.buffer.read(cx).snapshot(cx);
 8640        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8641
 8642        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8643        let mut selected_larger_node = false;
 8644        let new_selections = old_selections
 8645            .iter()
 8646            .map(|selection| {
 8647                let old_range = selection.start..selection.end;
 8648                let mut new_range = old_range.clone();
 8649                while let Some(containing_range) =
 8650                    buffer.range_for_syntax_ancestor(new_range.clone())
 8651                {
 8652                    new_range = containing_range;
 8653                    if !display_map.intersects_fold(new_range.start)
 8654                        && !display_map.intersects_fold(new_range.end)
 8655                    {
 8656                        break;
 8657                    }
 8658                }
 8659
 8660                selected_larger_node |= new_range != old_range;
 8661                Selection {
 8662                    id: selection.id,
 8663                    start: new_range.start,
 8664                    end: new_range.end,
 8665                    goal: SelectionGoal::None,
 8666                    reversed: selection.reversed,
 8667                }
 8668            })
 8669            .collect::<Vec<_>>();
 8670
 8671        if selected_larger_node {
 8672            stack.push(old_selections);
 8673            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8674                s.select(new_selections);
 8675            });
 8676        }
 8677        self.select_larger_syntax_node_stack = stack;
 8678    }
 8679
 8680    pub fn select_smaller_syntax_node(
 8681        &mut self,
 8682        _: &SelectSmallerSyntaxNode,
 8683        cx: &mut ViewContext<Self>,
 8684    ) {
 8685        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8686        if let Some(selections) = stack.pop() {
 8687            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8688                s.select(selections.to_vec());
 8689            });
 8690        }
 8691        self.select_larger_syntax_node_stack = stack;
 8692    }
 8693
 8694    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8695        if !EditorSettings::get_global(cx).gutter.runnables {
 8696            self.clear_tasks();
 8697            return Task::ready(());
 8698        }
 8699        let project = self.project.as_ref().map(Model::downgrade);
 8700        cx.spawn(|this, mut cx| async move {
 8701            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8702            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8703                return;
 8704            };
 8705            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8706                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8707            }) else {
 8708                return;
 8709            };
 8710
 8711            let hide_runnables = project
 8712                .update(&mut cx, |project, cx| {
 8713                    // Do not display any test indicators in non-dev server remote projects.
 8714                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8715                })
 8716                .unwrap_or(true);
 8717            if hide_runnables {
 8718                return;
 8719            }
 8720            let new_rows =
 8721                cx.background_executor()
 8722                    .spawn({
 8723                        let snapshot = display_snapshot.clone();
 8724                        async move {
 8725                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8726                        }
 8727                    })
 8728                    .await;
 8729            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8730
 8731            this.update(&mut cx, |this, _| {
 8732                this.clear_tasks();
 8733                for (key, value) in rows {
 8734                    this.insert_tasks(key, value);
 8735                }
 8736            })
 8737            .ok();
 8738        })
 8739    }
 8740    fn fetch_runnable_ranges(
 8741        snapshot: &DisplaySnapshot,
 8742        range: Range<Anchor>,
 8743    ) -> Vec<language::RunnableRange> {
 8744        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8745    }
 8746
 8747    fn runnable_rows(
 8748        project: Model<Project>,
 8749        snapshot: DisplaySnapshot,
 8750        runnable_ranges: Vec<RunnableRange>,
 8751        mut cx: AsyncWindowContext,
 8752    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8753        runnable_ranges
 8754            .into_iter()
 8755            .filter_map(|mut runnable| {
 8756                let tasks = cx
 8757                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8758                    .ok()?;
 8759                if tasks.is_empty() {
 8760                    return None;
 8761                }
 8762
 8763                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8764
 8765                let row = snapshot
 8766                    .buffer_snapshot
 8767                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8768                    .1
 8769                    .start
 8770                    .row;
 8771
 8772                let context_range =
 8773                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8774                Some((
 8775                    (runnable.buffer_id, row),
 8776                    RunnableTasks {
 8777                        templates: tasks,
 8778                        offset: MultiBufferOffset(runnable.run_range.start),
 8779                        context_range,
 8780                        column: point.column,
 8781                        extra_variables: runnable.extra_captures,
 8782                    },
 8783                ))
 8784            })
 8785            .collect()
 8786    }
 8787
 8788    fn templates_with_tags(
 8789        project: &Model<Project>,
 8790        runnable: &mut Runnable,
 8791        cx: &WindowContext<'_>,
 8792    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8793        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8794            let (worktree_id, file) = project
 8795                .buffer_for_id(runnable.buffer, cx)
 8796                .and_then(|buffer| buffer.read(cx).file())
 8797                .map(|file| (file.worktree_id(cx), file.clone()))
 8798                .unzip();
 8799
 8800            (
 8801                project.task_store().read(cx).task_inventory().cloned(),
 8802                worktree_id,
 8803                file,
 8804            )
 8805        });
 8806
 8807        let tags = mem::take(&mut runnable.tags);
 8808        let mut tags: Vec<_> = tags
 8809            .into_iter()
 8810            .flat_map(|tag| {
 8811                let tag = tag.0.clone();
 8812                inventory
 8813                    .as_ref()
 8814                    .into_iter()
 8815                    .flat_map(|inventory| {
 8816                        inventory.read(cx).list_tasks(
 8817                            file.clone(),
 8818                            Some(runnable.language.clone()),
 8819                            worktree_id,
 8820                            cx,
 8821                        )
 8822                    })
 8823                    .filter(move |(_, template)| {
 8824                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8825                    })
 8826            })
 8827            .sorted_by_key(|(kind, _)| kind.to_owned())
 8828            .collect();
 8829        if let Some((leading_tag_source, _)) = tags.first() {
 8830            // Strongest source wins; if we have worktree tag binding, prefer that to
 8831            // global and language bindings;
 8832            // if we have a global binding, prefer that to language binding.
 8833            let first_mismatch = tags
 8834                .iter()
 8835                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8836            if let Some(index) = first_mismatch {
 8837                tags.truncate(index);
 8838            }
 8839        }
 8840
 8841        tags
 8842    }
 8843
 8844    pub fn move_to_enclosing_bracket(
 8845        &mut self,
 8846        _: &MoveToEnclosingBracket,
 8847        cx: &mut ViewContext<Self>,
 8848    ) {
 8849        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8850            s.move_offsets_with(|snapshot, selection| {
 8851                let Some(enclosing_bracket_ranges) =
 8852                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8853                else {
 8854                    return;
 8855                };
 8856
 8857                let mut best_length = usize::MAX;
 8858                let mut best_inside = false;
 8859                let mut best_in_bracket_range = false;
 8860                let mut best_destination = None;
 8861                for (open, close) in enclosing_bracket_ranges {
 8862                    let close = close.to_inclusive();
 8863                    let length = close.end() - open.start;
 8864                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8865                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8866                        || close.contains(&selection.head());
 8867
 8868                    // If best is next to a bracket and current isn't, skip
 8869                    if !in_bracket_range && best_in_bracket_range {
 8870                        continue;
 8871                    }
 8872
 8873                    // Prefer smaller lengths unless best is inside and current isn't
 8874                    if length > best_length && (best_inside || !inside) {
 8875                        continue;
 8876                    }
 8877
 8878                    best_length = length;
 8879                    best_inside = inside;
 8880                    best_in_bracket_range = in_bracket_range;
 8881                    best_destination = Some(
 8882                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8883                            if inside {
 8884                                open.end
 8885                            } else {
 8886                                open.start
 8887                            }
 8888                        } else if inside {
 8889                            *close.start()
 8890                        } else {
 8891                            *close.end()
 8892                        },
 8893                    );
 8894                }
 8895
 8896                if let Some(destination) = best_destination {
 8897                    selection.collapse_to(destination, SelectionGoal::None);
 8898                }
 8899            })
 8900        });
 8901    }
 8902
 8903    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8904        self.end_selection(cx);
 8905        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8906        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8907            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8908            self.select_next_state = entry.select_next_state;
 8909            self.select_prev_state = entry.select_prev_state;
 8910            self.add_selections_state = entry.add_selections_state;
 8911            self.request_autoscroll(Autoscroll::newest(), cx);
 8912        }
 8913        self.selection_history.mode = SelectionHistoryMode::Normal;
 8914    }
 8915
 8916    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8917        self.end_selection(cx);
 8918        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8919        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8920            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8921            self.select_next_state = entry.select_next_state;
 8922            self.select_prev_state = entry.select_prev_state;
 8923            self.add_selections_state = entry.add_selections_state;
 8924            self.request_autoscroll(Autoscroll::newest(), cx);
 8925        }
 8926        self.selection_history.mode = SelectionHistoryMode::Normal;
 8927    }
 8928
 8929    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8930        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8931    }
 8932
 8933    pub fn expand_excerpts_down(
 8934        &mut self,
 8935        action: &ExpandExcerptsDown,
 8936        cx: &mut ViewContext<Self>,
 8937    ) {
 8938        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8939    }
 8940
 8941    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8942        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8943    }
 8944
 8945    pub fn expand_excerpts_for_direction(
 8946        &mut self,
 8947        lines: u32,
 8948        direction: ExpandExcerptDirection,
 8949        cx: &mut ViewContext<Self>,
 8950    ) {
 8951        let selections = self.selections.disjoint_anchors();
 8952
 8953        let lines = if lines == 0 {
 8954            EditorSettings::get_global(cx).expand_excerpt_lines
 8955        } else {
 8956            lines
 8957        };
 8958
 8959        self.buffer.update(cx, |buffer, cx| {
 8960            buffer.expand_excerpts(
 8961                selections
 8962                    .iter()
 8963                    .map(|selection| selection.head().excerpt_id)
 8964                    .dedup(),
 8965                lines,
 8966                direction,
 8967                cx,
 8968            )
 8969        })
 8970    }
 8971
 8972    pub fn expand_excerpt(
 8973        &mut self,
 8974        excerpt: ExcerptId,
 8975        direction: ExpandExcerptDirection,
 8976        cx: &mut ViewContext<Self>,
 8977    ) {
 8978        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8979        self.buffer.update(cx, |buffer, cx| {
 8980            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8981        })
 8982    }
 8983
 8984    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8985        self.go_to_diagnostic_impl(Direction::Next, cx)
 8986    }
 8987
 8988    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8989        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8990    }
 8991
 8992    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8993        let buffer = self.buffer.read(cx).snapshot(cx);
 8994        let selection = self.selections.newest::<usize>(cx);
 8995
 8996        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8997        if direction == Direction::Next {
 8998            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8999                let (group_id, jump_to) = popover.activation_info();
 9000                if self.activate_diagnostics(group_id, cx) {
 9001                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9002                        let mut new_selection = s.newest_anchor().clone();
 9003                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9004                        s.select_anchors(vec![new_selection.clone()]);
 9005                    });
 9006                }
 9007                return;
 9008            }
 9009        }
 9010
 9011        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9012            active_diagnostics
 9013                .primary_range
 9014                .to_offset(&buffer)
 9015                .to_inclusive()
 9016        });
 9017        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9018            if active_primary_range.contains(&selection.head()) {
 9019                *active_primary_range.start()
 9020            } else {
 9021                selection.head()
 9022            }
 9023        } else {
 9024            selection.head()
 9025        };
 9026        let snapshot = self.snapshot(cx);
 9027        loop {
 9028            let diagnostics = if direction == Direction::Prev {
 9029                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9030            } else {
 9031                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9032            }
 9033            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9034            let group = diagnostics
 9035                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9036                // be sorted in a stable way
 9037                // skip until we are at current active diagnostic, if it exists
 9038                .skip_while(|entry| {
 9039                    (match direction {
 9040                        Direction::Prev => entry.range.start >= search_start,
 9041                        Direction::Next => entry.range.start <= search_start,
 9042                    }) && self
 9043                        .active_diagnostics
 9044                        .as_ref()
 9045                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9046                })
 9047                .find_map(|entry| {
 9048                    if entry.diagnostic.is_primary
 9049                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9050                        && !entry.range.is_empty()
 9051                        // if we match with the active diagnostic, skip it
 9052                        && Some(entry.diagnostic.group_id)
 9053                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9054                    {
 9055                        Some((entry.range, entry.diagnostic.group_id))
 9056                    } else {
 9057                        None
 9058                    }
 9059                });
 9060
 9061            if let Some((primary_range, group_id)) = group {
 9062                if self.activate_diagnostics(group_id, cx) {
 9063                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9064                        s.select(vec![Selection {
 9065                            id: selection.id,
 9066                            start: primary_range.start,
 9067                            end: primary_range.start,
 9068                            reversed: false,
 9069                            goal: SelectionGoal::None,
 9070                        }]);
 9071                    });
 9072                }
 9073                break;
 9074            } else {
 9075                // Cycle around to the start of the buffer, potentially moving back to the start of
 9076                // the currently active diagnostic.
 9077                active_primary_range.take();
 9078                if direction == Direction::Prev {
 9079                    if search_start == buffer.len() {
 9080                        break;
 9081                    } else {
 9082                        search_start = buffer.len();
 9083                    }
 9084                } else if search_start == 0 {
 9085                    break;
 9086                } else {
 9087                    search_start = 0;
 9088                }
 9089            }
 9090        }
 9091    }
 9092
 9093    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9094        let snapshot = self.snapshot(cx);
 9095        let selection = self.selections.newest::<Point>(cx);
 9096        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9097    }
 9098
 9099    fn go_to_hunk_after_position(
 9100        &mut self,
 9101        snapshot: &EditorSnapshot,
 9102        position: Point,
 9103        cx: &mut ViewContext<'_, Editor>,
 9104    ) -> Option<MultiBufferDiffHunk> {
 9105        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9106            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9107                snapshot,
 9108                position,
 9109                ix > 0,
 9110                snapshot.diff_map.diff_hunks_in_range(
 9111                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9112                    &snapshot.buffer_snapshot,
 9113                ),
 9114                cx,
 9115            ) {
 9116                return Some(hunk);
 9117            }
 9118        }
 9119        None
 9120    }
 9121
 9122    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9123        let snapshot = self.snapshot(cx);
 9124        let selection = self.selections.newest::<Point>(cx);
 9125        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9126    }
 9127
 9128    fn go_to_hunk_before_position(
 9129        &mut self,
 9130        snapshot: &EditorSnapshot,
 9131        position: Point,
 9132        cx: &mut ViewContext<'_, Editor>,
 9133    ) -> Option<MultiBufferDiffHunk> {
 9134        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9135            .into_iter()
 9136            .enumerate()
 9137        {
 9138            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9139                snapshot,
 9140                position,
 9141                ix > 0,
 9142                snapshot
 9143                    .diff_map
 9144                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9145                cx,
 9146            ) {
 9147                return Some(hunk);
 9148            }
 9149        }
 9150        None
 9151    }
 9152
 9153    fn go_to_next_hunk_in_direction(
 9154        &mut self,
 9155        snapshot: &DisplaySnapshot,
 9156        initial_point: Point,
 9157        is_wrapped: bool,
 9158        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9159        cx: &mut ViewContext<Editor>,
 9160    ) -> Option<MultiBufferDiffHunk> {
 9161        let display_point = initial_point.to_display_point(snapshot);
 9162        let mut hunks = hunks
 9163            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9164            .filter(|(display_hunk, _)| {
 9165                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9166            })
 9167            .dedup();
 9168
 9169        if let Some((display_hunk, hunk)) = hunks.next() {
 9170            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9171                let row = display_hunk.start_display_row();
 9172                let point = DisplayPoint::new(row, 0);
 9173                s.select_display_ranges([point..point]);
 9174            });
 9175
 9176            Some(hunk)
 9177        } else {
 9178            None
 9179        }
 9180    }
 9181
 9182    pub fn go_to_definition(
 9183        &mut self,
 9184        _: &GoToDefinition,
 9185        cx: &mut ViewContext<Self>,
 9186    ) -> Task<Result<Navigated>> {
 9187        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9188        cx.spawn(|editor, mut cx| async move {
 9189            if definition.await? == Navigated::Yes {
 9190                return Ok(Navigated::Yes);
 9191            }
 9192            match editor.update(&mut cx, |editor, cx| {
 9193                editor.find_all_references(&FindAllReferences, cx)
 9194            })? {
 9195                Some(references) => references.await,
 9196                None => Ok(Navigated::No),
 9197            }
 9198        })
 9199    }
 9200
 9201    pub fn go_to_declaration(
 9202        &mut self,
 9203        _: &GoToDeclaration,
 9204        cx: &mut ViewContext<Self>,
 9205    ) -> Task<Result<Navigated>> {
 9206        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9207    }
 9208
 9209    pub fn go_to_declaration_split(
 9210        &mut self,
 9211        _: &GoToDeclaration,
 9212        cx: &mut ViewContext<Self>,
 9213    ) -> Task<Result<Navigated>> {
 9214        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9215    }
 9216
 9217    pub fn go_to_implementation(
 9218        &mut self,
 9219        _: &GoToImplementation,
 9220        cx: &mut ViewContext<Self>,
 9221    ) -> Task<Result<Navigated>> {
 9222        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9223    }
 9224
 9225    pub fn go_to_implementation_split(
 9226        &mut self,
 9227        _: &GoToImplementationSplit,
 9228        cx: &mut ViewContext<Self>,
 9229    ) -> Task<Result<Navigated>> {
 9230        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9231    }
 9232
 9233    pub fn go_to_type_definition(
 9234        &mut self,
 9235        _: &GoToTypeDefinition,
 9236        cx: &mut ViewContext<Self>,
 9237    ) -> Task<Result<Navigated>> {
 9238        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9239    }
 9240
 9241    pub fn go_to_definition_split(
 9242        &mut self,
 9243        _: &GoToDefinitionSplit,
 9244        cx: &mut ViewContext<Self>,
 9245    ) -> Task<Result<Navigated>> {
 9246        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9247    }
 9248
 9249    pub fn go_to_type_definition_split(
 9250        &mut self,
 9251        _: &GoToTypeDefinitionSplit,
 9252        cx: &mut ViewContext<Self>,
 9253    ) -> Task<Result<Navigated>> {
 9254        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9255    }
 9256
 9257    fn go_to_definition_of_kind(
 9258        &mut self,
 9259        kind: GotoDefinitionKind,
 9260        split: bool,
 9261        cx: &mut ViewContext<Self>,
 9262    ) -> Task<Result<Navigated>> {
 9263        let Some(provider) = self.semantics_provider.clone() else {
 9264            return Task::ready(Ok(Navigated::No));
 9265        };
 9266        let head = self.selections.newest::<usize>(cx).head();
 9267        let buffer = self.buffer.read(cx);
 9268        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9269            text_anchor
 9270        } else {
 9271            return Task::ready(Ok(Navigated::No));
 9272        };
 9273
 9274        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9275            return Task::ready(Ok(Navigated::No));
 9276        };
 9277
 9278        cx.spawn(|editor, mut cx| async move {
 9279            let definitions = definitions.await?;
 9280            let navigated = editor
 9281                .update(&mut cx, |editor, cx| {
 9282                    editor.navigate_to_hover_links(
 9283                        Some(kind),
 9284                        definitions
 9285                            .into_iter()
 9286                            .filter(|location| {
 9287                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9288                            })
 9289                            .map(HoverLink::Text)
 9290                            .collect::<Vec<_>>(),
 9291                        split,
 9292                        cx,
 9293                    )
 9294                })?
 9295                .await?;
 9296            anyhow::Ok(navigated)
 9297        })
 9298    }
 9299
 9300    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9301        let selection = self.selections.newest_anchor();
 9302        let head = selection.head();
 9303        let tail = selection.tail();
 9304
 9305        let Some((buffer, start_position)) =
 9306            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9307        else {
 9308            return;
 9309        };
 9310
 9311        let end_position = if head != tail {
 9312            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9313                return;
 9314            };
 9315            Some(pos)
 9316        } else {
 9317            None
 9318        };
 9319
 9320        let url_finder = cx.spawn(|editor, mut cx| async move {
 9321            let url = if let Some(end_pos) = end_position {
 9322                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9323            } else {
 9324                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9325            };
 9326
 9327            if let Some(url) = url {
 9328                editor.update(&mut cx, |_, cx| {
 9329                    cx.open_url(&url);
 9330                })
 9331            } else {
 9332                Ok(())
 9333            }
 9334        });
 9335
 9336        url_finder.detach();
 9337    }
 9338
 9339    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9340        let Some(workspace) = self.workspace() else {
 9341            return;
 9342        };
 9343
 9344        let position = self.selections.newest_anchor().head();
 9345
 9346        let Some((buffer, buffer_position)) =
 9347            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9348        else {
 9349            return;
 9350        };
 9351
 9352        let project = self.project.clone();
 9353
 9354        cx.spawn(|_, mut cx| async move {
 9355            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9356
 9357            if let Some((_, path)) = result {
 9358                workspace
 9359                    .update(&mut cx, |workspace, cx| {
 9360                        workspace.open_resolved_path(path, cx)
 9361                    })?
 9362                    .await?;
 9363            }
 9364            anyhow::Ok(())
 9365        })
 9366        .detach();
 9367    }
 9368
 9369    pub(crate) fn navigate_to_hover_links(
 9370        &mut self,
 9371        kind: Option<GotoDefinitionKind>,
 9372        mut definitions: Vec<HoverLink>,
 9373        split: bool,
 9374        cx: &mut ViewContext<Editor>,
 9375    ) -> Task<Result<Navigated>> {
 9376        // If there is one definition, just open it directly
 9377        if definitions.len() == 1 {
 9378            let definition = definitions.pop().unwrap();
 9379
 9380            enum TargetTaskResult {
 9381                Location(Option<Location>),
 9382                AlreadyNavigated,
 9383            }
 9384
 9385            let target_task = match definition {
 9386                HoverLink::Text(link) => {
 9387                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9388                }
 9389                HoverLink::InlayHint(lsp_location, server_id) => {
 9390                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9391                    cx.background_executor().spawn(async move {
 9392                        let location = computation.await?;
 9393                        Ok(TargetTaskResult::Location(location))
 9394                    })
 9395                }
 9396                HoverLink::Url(url) => {
 9397                    cx.open_url(&url);
 9398                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9399                }
 9400                HoverLink::File(path) => {
 9401                    if let Some(workspace) = self.workspace() {
 9402                        cx.spawn(|_, mut cx| async move {
 9403                            workspace
 9404                                .update(&mut cx, |workspace, cx| {
 9405                                    workspace.open_resolved_path(path, cx)
 9406                                })?
 9407                                .await
 9408                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9409                        })
 9410                    } else {
 9411                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9412                    }
 9413                }
 9414            };
 9415            cx.spawn(|editor, mut cx| async move {
 9416                let target = match target_task.await.context("target resolution task")? {
 9417                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9418                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9419                    TargetTaskResult::Location(Some(target)) => target,
 9420                };
 9421
 9422                editor.update(&mut cx, |editor, cx| {
 9423                    let Some(workspace) = editor.workspace() else {
 9424                        return Navigated::No;
 9425                    };
 9426                    let pane = workspace.read(cx).active_pane().clone();
 9427
 9428                    let range = target.range.to_offset(target.buffer.read(cx));
 9429                    let range = editor.range_for_match(&range);
 9430
 9431                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9432                        let buffer = target.buffer.read(cx);
 9433                        let range = check_multiline_range(buffer, range);
 9434                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9435                            s.select_ranges([range]);
 9436                        });
 9437                    } else {
 9438                        cx.window_context().defer(move |cx| {
 9439                            let target_editor: View<Self> =
 9440                                workspace.update(cx, |workspace, cx| {
 9441                                    let pane = if split {
 9442                                        workspace.adjacent_pane(cx)
 9443                                    } else {
 9444                                        workspace.active_pane().clone()
 9445                                    };
 9446
 9447                                    workspace.open_project_item(
 9448                                        pane,
 9449                                        target.buffer.clone(),
 9450                                        true,
 9451                                        true,
 9452                                        cx,
 9453                                    )
 9454                                });
 9455                            target_editor.update(cx, |target_editor, cx| {
 9456                                // When selecting a definition in a different buffer, disable the nav history
 9457                                // to avoid creating a history entry at the previous cursor location.
 9458                                pane.update(cx, |pane, _| pane.disable_history());
 9459                                let buffer = target.buffer.read(cx);
 9460                                let range = check_multiline_range(buffer, range);
 9461                                target_editor.change_selections(
 9462                                    Some(Autoscroll::focused()),
 9463                                    cx,
 9464                                    |s| {
 9465                                        s.select_ranges([range]);
 9466                                    },
 9467                                );
 9468                                pane.update(cx, |pane, _| pane.enable_history());
 9469                            });
 9470                        });
 9471                    }
 9472                    Navigated::Yes
 9473                })
 9474            })
 9475        } else if !definitions.is_empty() {
 9476            cx.spawn(|editor, mut cx| async move {
 9477                let (title, location_tasks, workspace) = editor
 9478                    .update(&mut cx, |editor, cx| {
 9479                        let tab_kind = match kind {
 9480                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9481                            _ => "Definitions",
 9482                        };
 9483                        let title = definitions
 9484                            .iter()
 9485                            .find_map(|definition| match definition {
 9486                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9487                                    let buffer = origin.buffer.read(cx);
 9488                                    format!(
 9489                                        "{} for {}",
 9490                                        tab_kind,
 9491                                        buffer
 9492                                            .text_for_range(origin.range.clone())
 9493                                            .collect::<String>()
 9494                                    )
 9495                                }),
 9496                                HoverLink::InlayHint(_, _) => None,
 9497                                HoverLink::Url(_) => None,
 9498                                HoverLink::File(_) => None,
 9499                            })
 9500                            .unwrap_or(tab_kind.to_string());
 9501                        let location_tasks = definitions
 9502                            .into_iter()
 9503                            .map(|definition| match definition {
 9504                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9505                                HoverLink::InlayHint(lsp_location, server_id) => {
 9506                                    editor.compute_target_location(lsp_location, server_id, cx)
 9507                                }
 9508                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9509                                HoverLink::File(_) => Task::ready(Ok(None)),
 9510                            })
 9511                            .collect::<Vec<_>>();
 9512                        (title, location_tasks, editor.workspace().clone())
 9513                    })
 9514                    .context("location tasks preparation")?;
 9515
 9516                let locations = future::join_all(location_tasks)
 9517                    .await
 9518                    .into_iter()
 9519                    .filter_map(|location| location.transpose())
 9520                    .collect::<Result<_>>()
 9521                    .context("location tasks")?;
 9522
 9523                let Some(workspace) = workspace else {
 9524                    return Ok(Navigated::No);
 9525                };
 9526                let opened = workspace
 9527                    .update(&mut cx, |workspace, cx| {
 9528                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9529                    })
 9530                    .ok();
 9531
 9532                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9533            })
 9534        } else {
 9535            Task::ready(Ok(Navigated::No))
 9536        }
 9537    }
 9538
 9539    fn compute_target_location(
 9540        &self,
 9541        lsp_location: lsp::Location,
 9542        server_id: LanguageServerId,
 9543        cx: &mut ViewContext<Self>,
 9544    ) -> Task<anyhow::Result<Option<Location>>> {
 9545        let Some(project) = self.project.clone() else {
 9546            return Task::ready(Ok(None));
 9547        };
 9548
 9549        cx.spawn(move |editor, mut cx| async move {
 9550            let location_task = editor.update(&mut cx, |_, cx| {
 9551                project.update(cx, |project, cx| {
 9552                    let language_server_name = project
 9553                        .language_server_statuses(cx)
 9554                        .find(|(id, _)| server_id == *id)
 9555                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9556                    language_server_name.map(|language_server_name| {
 9557                        project.open_local_buffer_via_lsp(
 9558                            lsp_location.uri.clone(),
 9559                            server_id,
 9560                            language_server_name,
 9561                            cx,
 9562                        )
 9563                    })
 9564                })
 9565            })?;
 9566            let location = match location_task {
 9567                Some(task) => Some({
 9568                    let target_buffer_handle = task.await.context("open local buffer")?;
 9569                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9570                        let target_start = target_buffer
 9571                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9572                        let target_end = target_buffer
 9573                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9574                        target_buffer.anchor_after(target_start)
 9575                            ..target_buffer.anchor_before(target_end)
 9576                    })?;
 9577                    Location {
 9578                        buffer: target_buffer_handle,
 9579                        range,
 9580                    }
 9581                }),
 9582                None => None,
 9583            };
 9584            Ok(location)
 9585        })
 9586    }
 9587
 9588    pub fn find_all_references(
 9589        &mut self,
 9590        _: &FindAllReferences,
 9591        cx: &mut ViewContext<Self>,
 9592    ) -> Option<Task<Result<Navigated>>> {
 9593        let selection = self.selections.newest::<usize>(cx);
 9594        let multi_buffer = self.buffer.read(cx);
 9595        let head = selection.head();
 9596
 9597        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9598        let head_anchor = multi_buffer_snapshot.anchor_at(
 9599            head,
 9600            if head < selection.tail() {
 9601                Bias::Right
 9602            } else {
 9603                Bias::Left
 9604            },
 9605        );
 9606
 9607        match self
 9608            .find_all_references_task_sources
 9609            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9610        {
 9611            Ok(_) => {
 9612                log::info!(
 9613                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9614                );
 9615                return None;
 9616            }
 9617            Err(i) => {
 9618                self.find_all_references_task_sources.insert(i, head_anchor);
 9619            }
 9620        }
 9621
 9622        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9623        let workspace = self.workspace()?;
 9624        let project = workspace.read(cx).project().clone();
 9625        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9626        Some(cx.spawn(|editor, mut cx| async move {
 9627            let _cleanup = defer({
 9628                let mut cx = cx.clone();
 9629                move || {
 9630                    let _ = editor.update(&mut cx, |editor, _| {
 9631                        if let Ok(i) =
 9632                            editor
 9633                                .find_all_references_task_sources
 9634                                .binary_search_by(|anchor| {
 9635                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9636                                })
 9637                        {
 9638                            editor.find_all_references_task_sources.remove(i);
 9639                        }
 9640                    });
 9641                }
 9642            });
 9643
 9644            let locations = references.await?;
 9645            if locations.is_empty() {
 9646                return anyhow::Ok(Navigated::No);
 9647            }
 9648
 9649            workspace.update(&mut cx, |workspace, cx| {
 9650                let title = locations
 9651                    .first()
 9652                    .as_ref()
 9653                    .map(|location| {
 9654                        let buffer = location.buffer.read(cx);
 9655                        format!(
 9656                            "References to `{}`",
 9657                            buffer
 9658                                .text_for_range(location.range.clone())
 9659                                .collect::<String>()
 9660                        )
 9661                    })
 9662                    .unwrap();
 9663                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9664                Navigated::Yes
 9665            })
 9666        }))
 9667    }
 9668
 9669    /// Opens a multibuffer with the given project locations in it
 9670    pub fn open_locations_in_multibuffer(
 9671        workspace: &mut Workspace,
 9672        mut locations: Vec<Location>,
 9673        title: String,
 9674        split: bool,
 9675        cx: &mut ViewContext<Workspace>,
 9676    ) {
 9677        // If there are multiple definitions, open them in a multibuffer
 9678        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9679        let mut locations = locations.into_iter().peekable();
 9680        let mut ranges_to_highlight = Vec::new();
 9681        let capability = workspace.project().read(cx).capability();
 9682
 9683        let excerpt_buffer = cx.new_model(|cx| {
 9684            let mut multibuffer = MultiBuffer::new(capability);
 9685            while let Some(location) = locations.next() {
 9686                let buffer = location.buffer.read(cx);
 9687                let mut ranges_for_buffer = Vec::new();
 9688                let range = location.range.to_offset(buffer);
 9689                ranges_for_buffer.push(range.clone());
 9690
 9691                while let Some(next_location) = locations.peek() {
 9692                    if next_location.buffer == location.buffer {
 9693                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9694                        locations.next();
 9695                    } else {
 9696                        break;
 9697                    }
 9698                }
 9699
 9700                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9701                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9702                    location.buffer.clone(),
 9703                    ranges_for_buffer,
 9704                    DEFAULT_MULTIBUFFER_CONTEXT,
 9705                    cx,
 9706                ))
 9707            }
 9708
 9709            multibuffer.with_title(title)
 9710        });
 9711
 9712        let editor = cx.new_view(|cx| {
 9713            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9714        });
 9715        editor.update(cx, |editor, cx| {
 9716            if let Some(first_range) = ranges_to_highlight.first() {
 9717                editor.change_selections(None, cx, |selections| {
 9718                    selections.clear_disjoint();
 9719                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9720                });
 9721            }
 9722            editor.highlight_background::<Self>(
 9723                &ranges_to_highlight,
 9724                |theme| theme.editor_highlighted_line_background,
 9725                cx,
 9726            );
 9727            editor.register_buffers_with_language_servers(cx);
 9728        });
 9729
 9730        let item = Box::new(editor);
 9731        let item_id = item.item_id();
 9732
 9733        if split {
 9734            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9735        } else {
 9736            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9737                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9738                    pane.close_current_preview_item(cx)
 9739                } else {
 9740                    None
 9741                }
 9742            });
 9743            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9744        }
 9745        workspace.active_pane().update(cx, |pane, cx| {
 9746            pane.set_preview_item_id(Some(item_id), cx);
 9747        });
 9748    }
 9749
 9750    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9751        use language::ToOffset as _;
 9752
 9753        let provider = self.semantics_provider.clone()?;
 9754        let selection = self.selections.newest_anchor().clone();
 9755        let (cursor_buffer, cursor_buffer_position) = self
 9756            .buffer
 9757            .read(cx)
 9758            .text_anchor_for_position(selection.head(), cx)?;
 9759        let (tail_buffer, cursor_buffer_position_end) = self
 9760            .buffer
 9761            .read(cx)
 9762            .text_anchor_for_position(selection.tail(), cx)?;
 9763        if tail_buffer != cursor_buffer {
 9764            return None;
 9765        }
 9766
 9767        let snapshot = cursor_buffer.read(cx).snapshot();
 9768        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9769        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9770        let prepare_rename = provider
 9771            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9772            .unwrap_or_else(|| Task::ready(Ok(None)));
 9773        drop(snapshot);
 9774
 9775        Some(cx.spawn(|this, mut cx| async move {
 9776            let rename_range = if let Some(range) = prepare_rename.await? {
 9777                Some(range)
 9778            } else {
 9779                this.update(&mut cx, |this, cx| {
 9780                    let buffer = this.buffer.read(cx).snapshot(cx);
 9781                    let mut buffer_highlights = this
 9782                        .document_highlights_for_position(selection.head(), &buffer)
 9783                        .filter(|highlight| {
 9784                            highlight.start.excerpt_id == selection.head().excerpt_id
 9785                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9786                        });
 9787                    buffer_highlights
 9788                        .next()
 9789                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9790                })?
 9791            };
 9792            if let Some(rename_range) = rename_range {
 9793                this.update(&mut cx, |this, cx| {
 9794                    let snapshot = cursor_buffer.read(cx).snapshot();
 9795                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9796                    let cursor_offset_in_rename_range =
 9797                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9798                    let cursor_offset_in_rename_range_end =
 9799                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9800
 9801                    this.take_rename(false, cx);
 9802                    let buffer = this.buffer.read(cx).read(cx);
 9803                    let cursor_offset = selection.head().to_offset(&buffer);
 9804                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9805                    let rename_end = rename_start + rename_buffer_range.len();
 9806                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9807                    let mut old_highlight_id = None;
 9808                    let old_name: Arc<str> = buffer
 9809                        .chunks(rename_start..rename_end, true)
 9810                        .map(|chunk| {
 9811                            if old_highlight_id.is_none() {
 9812                                old_highlight_id = chunk.syntax_highlight_id;
 9813                            }
 9814                            chunk.text
 9815                        })
 9816                        .collect::<String>()
 9817                        .into();
 9818
 9819                    drop(buffer);
 9820
 9821                    // Position the selection in the rename editor so that it matches the current selection.
 9822                    this.show_local_selections = false;
 9823                    let rename_editor = cx.new_view(|cx| {
 9824                        let mut editor = Editor::single_line(cx);
 9825                        editor.buffer.update(cx, |buffer, cx| {
 9826                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9827                        });
 9828                        let rename_selection_range = match cursor_offset_in_rename_range
 9829                            .cmp(&cursor_offset_in_rename_range_end)
 9830                        {
 9831                            Ordering::Equal => {
 9832                                editor.select_all(&SelectAll, cx);
 9833                                return editor;
 9834                            }
 9835                            Ordering::Less => {
 9836                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9837                            }
 9838                            Ordering::Greater => {
 9839                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9840                            }
 9841                        };
 9842                        if rename_selection_range.end > old_name.len() {
 9843                            editor.select_all(&SelectAll, cx);
 9844                        } else {
 9845                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9846                                s.select_ranges([rename_selection_range]);
 9847                            });
 9848                        }
 9849                        editor
 9850                    });
 9851                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9852                        if e == &EditorEvent::Focused {
 9853                            cx.emit(EditorEvent::FocusedIn)
 9854                        }
 9855                    })
 9856                    .detach();
 9857
 9858                    let write_highlights =
 9859                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9860                    let read_highlights =
 9861                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9862                    let ranges = write_highlights
 9863                        .iter()
 9864                        .flat_map(|(_, ranges)| ranges.iter())
 9865                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9866                        .cloned()
 9867                        .collect();
 9868
 9869                    this.highlight_text::<Rename>(
 9870                        ranges,
 9871                        HighlightStyle {
 9872                            fade_out: Some(0.6),
 9873                            ..Default::default()
 9874                        },
 9875                        cx,
 9876                    );
 9877                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9878                    cx.focus(&rename_focus_handle);
 9879                    let block_id = this.insert_blocks(
 9880                        [BlockProperties {
 9881                            style: BlockStyle::Flex,
 9882                            placement: BlockPlacement::Below(range.start),
 9883                            height: 1,
 9884                            render: Arc::new({
 9885                                let rename_editor = rename_editor.clone();
 9886                                move |cx: &mut BlockContext| {
 9887                                    let mut text_style = cx.editor_style.text.clone();
 9888                                    if let Some(highlight_style) = old_highlight_id
 9889                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9890                                    {
 9891                                        text_style = text_style.highlight(highlight_style);
 9892                                    }
 9893                                    div()
 9894                                        .block_mouse_down()
 9895                                        .pl(cx.anchor_x)
 9896                                        .child(EditorElement::new(
 9897                                            &rename_editor,
 9898                                            EditorStyle {
 9899                                                background: cx.theme().system().transparent,
 9900                                                local_player: cx.editor_style.local_player,
 9901                                                text: text_style,
 9902                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9903                                                syntax: cx.editor_style.syntax.clone(),
 9904                                                status: cx.editor_style.status.clone(),
 9905                                                inlay_hints_style: HighlightStyle {
 9906                                                    font_weight: Some(FontWeight::BOLD),
 9907                                                    ..make_inlay_hints_style(cx)
 9908                                                },
 9909                                                inline_completion_styles: make_suggestion_styles(
 9910                                                    cx,
 9911                                                ),
 9912                                                ..EditorStyle::default()
 9913                                            },
 9914                                        ))
 9915                                        .into_any_element()
 9916                                }
 9917                            }),
 9918                            priority: 0,
 9919                        }],
 9920                        Some(Autoscroll::fit()),
 9921                        cx,
 9922                    )[0];
 9923                    this.pending_rename = Some(RenameState {
 9924                        range,
 9925                        old_name,
 9926                        editor: rename_editor,
 9927                        block_id,
 9928                    });
 9929                })?;
 9930            }
 9931
 9932            Ok(())
 9933        }))
 9934    }
 9935
 9936    pub fn confirm_rename(
 9937        &mut self,
 9938        _: &ConfirmRename,
 9939        cx: &mut ViewContext<Self>,
 9940    ) -> Option<Task<Result<()>>> {
 9941        let rename = self.take_rename(false, cx)?;
 9942        let workspace = self.workspace()?.downgrade();
 9943        let (buffer, start) = self
 9944            .buffer
 9945            .read(cx)
 9946            .text_anchor_for_position(rename.range.start, cx)?;
 9947        let (end_buffer, _) = self
 9948            .buffer
 9949            .read(cx)
 9950            .text_anchor_for_position(rename.range.end, cx)?;
 9951        if buffer != end_buffer {
 9952            return None;
 9953        }
 9954
 9955        let old_name = rename.old_name;
 9956        let new_name = rename.editor.read(cx).text(cx);
 9957
 9958        let rename = self.semantics_provider.as_ref()?.perform_rename(
 9959            &buffer,
 9960            start,
 9961            new_name.clone(),
 9962            cx,
 9963        )?;
 9964
 9965        Some(cx.spawn(|editor, mut cx| async move {
 9966            let project_transaction = rename.await?;
 9967            Self::open_project_transaction(
 9968                &editor,
 9969                workspace,
 9970                project_transaction,
 9971                format!("Rename: {}{}", old_name, new_name),
 9972                cx.clone(),
 9973            )
 9974            .await?;
 9975
 9976            editor.update(&mut cx, |editor, cx| {
 9977                editor.refresh_document_highlights(cx);
 9978            })?;
 9979            Ok(())
 9980        }))
 9981    }
 9982
 9983    fn take_rename(
 9984        &mut self,
 9985        moving_cursor: bool,
 9986        cx: &mut ViewContext<Self>,
 9987    ) -> Option<RenameState> {
 9988        let rename = self.pending_rename.take()?;
 9989        if rename.editor.focus_handle(cx).is_focused(cx) {
 9990            cx.focus(&self.focus_handle);
 9991        }
 9992
 9993        self.remove_blocks(
 9994            [rename.block_id].into_iter().collect(),
 9995            Some(Autoscroll::fit()),
 9996            cx,
 9997        );
 9998        self.clear_highlights::<Rename>(cx);
 9999        self.show_local_selections = true;
10000
10001        if moving_cursor {
10002            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10003                editor.selections.newest::<usize>(cx).head()
10004            });
10005
10006            // Update the selection to match the position of the selection inside
10007            // the rename editor.
10008            let snapshot = self.buffer.read(cx).read(cx);
10009            let rename_range = rename.range.to_offset(&snapshot);
10010            let cursor_in_editor = snapshot
10011                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10012                .min(rename_range.end);
10013            drop(snapshot);
10014
10015            self.change_selections(None, cx, |s| {
10016                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10017            });
10018        } else {
10019            self.refresh_document_highlights(cx);
10020        }
10021
10022        Some(rename)
10023    }
10024
10025    pub fn pending_rename(&self) -> Option<&RenameState> {
10026        self.pending_rename.as_ref()
10027    }
10028
10029    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10030        let project = match &self.project {
10031            Some(project) => project.clone(),
10032            None => return None,
10033        };
10034
10035        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10036    }
10037
10038    fn format_selections(
10039        &mut self,
10040        _: &FormatSelections,
10041        cx: &mut ViewContext<Self>,
10042    ) -> Option<Task<Result<()>>> {
10043        let project = match &self.project {
10044            Some(project) => project.clone(),
10045            None => return None,
10046        };
10047
10048        let selections = self
10049            .selections
10050            .all_adjusted(cx)
10051            .into_iter()
10052            .filter(|s| !s.is_empty())
10053            .collect_vec();
10054
10055        Some(self.perform_format(
10056            project,
10057            FormatTrigger::Manual,
10058            FormatTarget::Ranges(selections),
10059            cx,
10060        ))
10061    }
10062
10063    fn perform_format(
10064        &mut self,
10065        project: Model<Project>,
10066        trigger: FormatTrigger,
10067        target: FormatTarget,
10068        cx: &mut ViewContext<Self>,
10069    ) -> Task<Result<()>> {
10070        let buffer = self.buffer().clone();
10071        let mut buffers = buffer.read(cx).all_buffers();
10072        if trigger == FormatTrigger::Save {
10073            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10074        }
10075
10076        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10077        let format = project.update(cx, |project, cx| {
10078            project.format(buffers, true, trigger, target, cx)
10079        });
10080
10081        cx.spawn(|_, mut cx| async move {
10082            let transaction = futures::select_biased! {
10083                () = timeout => {
10084                    log::warn!("timed out waiting for formatting");
10085                    None
10086                }
10087                transaction = format.log_err().fuse() => transaction,
10088            };
10089
10090            buffer
10091                .update(&mut cx, |buffer, cx| {
10092                    if let Some(transaction) = transaction {
10093                        if !buffer.is_singleton() {
10094                            buffer.push_transaction(&transaction.0, cx);
10095                        }
10096                    }
10097
10098                    cx.notify();
10099                })
10100                .ok();
10101
10102            Ok(())
10103        })
10104    }
10105
10106    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10107        if let Some(project) = self.project.clone() {
10108            self.buffer.update(cx, |multi_buffer, cx| {
10109                project.update(cx, |project, cx| {
10110                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10111                });
10112            })
10113        }
10114    }
10115
10116    fn cancel_language_server_work(
10117        &mut self,
10118        _: &actions::CancelLanguageServerWork,
10119        cx: &mut ViewContext<Self>,
10120    ) {
10121        if let Some(project) = self.project.clone() {
10122            self.buffer.update(cx, |multi_buffer, cx| {
10123                project.update(cx, |project, cx| {
10124                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10125                });
10126            })
10127        }
10128    }
10129
10130    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10131        cx.show_character_palette();
10132    }
10133
10134    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10135        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10136            let buffer = self.buffer.read(cx).snapshot(cx);
10137            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10138            let is_valid = buffer
10139                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10140                .any(|entry| {
10141                    entry.diagnostic.is_primary
10142                        && !entry.range.is_empty()
10143                        && entry.range.start == primary_range_start
10144                        && entry.diagnostic.message == active_diagnostics.primary_message
10145                });
10146
10147            if is_valid != active_diagnostics.is_valid {
10148                active_diagnostics.is_valid = is_valid;
10149                let mut new_styles = HashMap::default();
10150                for (block_id, diagnostic) in &active_diagnostics.blocks {
10151                    new_styles.insert(
10152                        *block_id,
10153                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10154                    );
10155                }
10156                self.display_map.update(cx, |display_map, _cx| {
10157                    display_map.replace_blocks(new_styles)
10158                });
10159            }
10160        }
10161    }
10162
10163    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10164        self.dismiss_diagnostics(cx);
10165        let snapshot = self.snapshot(cx);
10166        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10167            let buffer = self.buffer.read(cx).snapshot(cx);
10168
10169            let mut primary_range = None;
10170            let mut primary_message = None;
10171            let mut group_end = Point::zero();
10172            let diagnostic_group = buffer
10173                .diagnostic_group::<MultiBufferPoint>(group_id)
10174                .filter_map(|entry| {
10175                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10176                        && (entry.range.start.row == entry.range.end.row
10177                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10178                    {
10179                        return None;
10180                    }
10181                    if entry.range.end > group_end {
10182                        group_end = entry.range.end;
10183                    }
10184                    if entry.diagnostic.is_primary {
10185                        primary_range = Some(entry.range.clone());
10186                        primary_message = Some(entry.diagnostic.message.clone());
10187                    }
10188                    Some(entry)
10189                })
10190                .collect::<Vec<_>>();
10191            let primary_range = primary_range?;
10192            let primary_message = primary_message?;
10193            let primary_range =
10194                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10195
10196            let blocks = display_map
10197                .insert_blocks(
10198                    diagnostic_group.iter().map(|entry| {
10199                        let diagnostic = entry.diagnostic.clone();
10200                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10201                        BlockProperties {
10202                            style: BlockStyle::Fixed,
10203                            placement: BlockPlacement::Below(
10204                                buffer.anchor_after(entry.range.start),
10205                            ),
10206                            height: message_height,
10207                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10208                            priority: 0,
10209                        }
10210                    }),
10211                    cx,
10212                )
10213                .into_iter()
10214                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10215                .collect();
10216
10217            Some(ActiveDiagnosticGroup {
10218                primary_range,
10219                primary_message,
10220                group_id,
10221                blocks,
10222                is_valid: true,
10223            })
10224        });
10225        self.active_diagnostics.is_some()
10226    }
10227
10228    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10229        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10230            self.display_map.update(cx, |display_map, cx| {
10231                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10232            });
10233            cx.notify();
10234        }
10235    }
10236
10237    pub fn set_selections_from_remote(
10238        &mut self,
10239        selections: Vec<Selection<Anchor>>,
10240        pending_selection: Option<Selection<Anchor>>,
10241        cx: &mut ViewContext<Self>,
10242    ) {
10243        let old_cursor_position = self.selections.newest_anchor().head();
10244        self.selections.change_with(cx, |s| {
10245            s.select_anchors(selections);
10246            if let Some(pending_selection) = pending_selection {
10247                s.set_pending(pending_selection, SelectMode::Character);
10248            } else {
10249                s.clear_pending();
10250            }
10251        });
10252        self.selections_did_change(false, &old_cursor_position, true, cx);
10253    }
10254
10255    fn push_to_selection_history(&mut self) {
10256        self.selection_history.push(SelectionHistoryEntry {
10257            selections: self.selections.disjoint_anchors(),
10258            select_next_state: self.select_next_state.clone(),
10259            select_prev_state: self.select_prev_state.clone(),
10260            add_selections_state: self.add_selections_state.clone(),
10261        });
10262    }
10263
10264    pub fn transact(
10265        &mut self,
10266        cx: &mut ViewContext<Self>,
10267        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10268    ) -> Option<TransactionId> {
10269        self.start_transaction_at(Instant::now(), cx);
10270        update(self, cx);
10271        self.end_transaction_at(Instant::now(), cx)
10272    }
10273
10274    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10275        self.end_selection(cx);
10276        if let Some(tx_id) = self
10277            .buffer
10278            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10279        {
10280            self.selection_history
10281                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10282            cx.emit(EditorEvent::TransactionBegun {
10283                transaction_id: tx_id,
10284            })
10285        }
10286    }
10287
10288    fn end_transaction_at(
10289        &mut self,
10290        now: Instant,
10291        cx: &mut ViewContext<Self>,
10292    ) -> Option<TransactionId> {
10293        if let Some(transaction_id) = self
10294            .buffer
10295            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10296        {
10297            if let Some((_, end_selections)) =
10298                self.selection_history.transaction_mut(transaction_id)
10299            {
10300                *end_selections = Some(self.selections.disjoint_anchors());
10301            } else {
10302                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10303            }
10304
10305            cx.emit(EditorEvent::Edited { transaction_id });
10306            Some(transaction_id)
10307        } else {
10308            None
10309        }
10310    }
10311
10312    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10313        if self.is_singleton(cx) {
10314            let selection = self.selections.newest::<Point>(cx);
10315
10316            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10317            let range = if selection.is_empty() {
10318                let point = selection.head().to_display_point(&display_map);
10319                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10320                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10321                    .to_point(&display_map);
10322                start..end
10323            } else {
10324                selection.range()
10325            };
10326            if display_map.folds_in_range(range).next().is_some() {
10327                self.unfold_lines(&Default::default(), cx)
10328            } else {
10329                self.fold(&Default::default(), cx)
10330            }
10331        } else {
10332            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10333            let mut toggled_buffers = HashSet::default();
10334            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10335                self.selections
10336                    .disjoint_anchors()
10337                    .into_iter()
10338                    .map(|selection| selection.range()),
10339            ) {
10340                let buffer_id = buffer_snapshot.remote_id();
10341                if toggled_buffers.insert(buffer_id) {
10342                    if self.buffer_folded(buffer_id, cx) {
10343                        self.unfold_buffer(buffer_id, cx);
10344                    } else {
10345                        self.fold_buffer(buffer_id, cx);
10346                    }
10347                }
10348            }
10349        }
10350    }
10351
10352    pub fn toggle_fold_recursive(
10353        &mut self,
10354        _: &actions::ToggleFoldRecursive,
10355        cx: &mut ViewContext<Self>,
10356    ) {
10357        let selection = self.selections.newest::<Point>(cx);
10358
10359        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10360        let range = if selection.is_empty() {
10361            let point = selection.head().to_display_point(&display_map);
10362            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10363            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10364                .to_point(&display_map);
10365            start..end
10366        } else {
10367            selection.range()
10368        };
10369        if display_map.folds_in_range(range).next().is_some() {
10370            self.unfold_recursive(&Default::default(), cx)
10371        } else {
10372            self.fold_recursive(&Default::default(), cx)
10373        }
10374    }
10375
10376    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10377        if self.is_singleton(cx) {
10378            let mut to_fold = Vec::new();
10379            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10380            let selections = self.selections.all_adjusted(cx);
10381
10382            for selection in selections {
10383                let range = selection.range().sorted();
10384                let buffer_start_row = range.start.row;
10385
10386                if range.start.row != range.end.row {
10387                    let mut found = false;
10388                    let mut row = range.start.row;
10389                    while row <= range.end.row {
10390                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10391                        {
10392                            found = true;
10393                            row = crease.range().end.row + 1;
10394                            to_fold.push(crease);
10395                        } else {
10396                            row += 1
10397                        }
10398                    }
10399                    if found {
10400                        continue;
10401                    }
10402                }
10403
10404                for row in (0..=range.start.row).rev() {
10405                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10406                        if crease.range().end.row >= buffer_start_row {
10407                            to_fold.push(crease);
10408                            if row <= range.start.row {
10409                                break;
10410                            }
10411                        }
10412                    }
10413                }
10414            }
10415
10416            self.fold_creases(to_fold, true, cx);
10417        } else {
10418            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10419            let mut folded_buffers = HashSet::default();
10420            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10421                self.selections
10422                    .disjoint_anchors()
10423                    .into_iter()
10424                    .map(|selection| selection.range()),
10425            ) {
10426                let buffer_id = buffer_snapshot.remote_id();
10427                if folded_buffers.insert(buffer_id) {
10428                    self.fold_buffer(buffer_id, cx);
10429                }
10430            }
10431        }
10432    }
10433
10434    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10435        if !self.buffer.read(cx).is_singleton() {
10436            return;
10437        }
10438
10439        let fold_at_level = fold_at.level;
10440        let snapshot = self.buffer.read(cx).snapshot(cx);
10441        let mut to_fold = Vec::new();
10442        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10443
10444        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10445            while start_row < end_row {
10446                match self
10447                    .snapshot(cx)
10448                    .crease_for_buffer_row(MultiBufferRow(start_row))
10449                {
10450                    Some(crease) => {
10451                        let nested_start_row = crease.range().start.row + 1;
10452                        let nested_end_row = crease.range().end.row;
10453
10454                        if current_level < fold_at_level {
10455                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10456                        } else if current_level == fold_at_level {
10457                            to_fold.push(crease);
10458                        }
10459
10460                        start_row = nested_end_row + 1;
10461                    }
10462                    None => start_row += 1,
10463                }
10464            }
10465        }
10466
10467        self.fold_creases(to_fold, true, cx);
10468    }
10469
10470    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10471        if self.buffer.read(cx).is_singleton() {
10472            let mut fold_ranges = Vec::new();
10473            let snapshot = self.buffer.read(cx).snapshot(cx);
10474
10475            for row in 0..snapshot.max_row().0 {
10476                if let Some(foldable_range) =
10477                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10478                {
10479                    fold_ranges.push(foldable_range);
10480                }
10481            }
10482
10483            self.fold_creases(fold_ranges, true, cx);
10484        } else {
10485            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10486                editor
10487                    .update(&mut cx, |editor, cx| {
10488                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10489                            editor.fold_buffer(buffer_id, cx);
10490                        }
10491                    })
10492                    .ok();
10493            });
10494        }
10495    }
10496
10497    pub fn fold_function_bodies(
10498        &mut self,
10499        _: &actions::FoldFunctionBodies,
10500        cx: &mut ViewContext<Self>,
10501    ) {
10502        let snapshot = self.buffer.read(cx).snapshot(cx);
10503        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10504            return;
10505        };
10506        let creases = buffer
10507            .function_body_fold_ranges(0..buffer.len())
10508            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10509            .collect();
10510
10511        self.fold_creases(creases, true, cx);
10512    }
10513
10514    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10515        let mut to_fold = Vec::new();
10516        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10517        let selections = self.selections.all_adjusted(cx);
10518
10519        for selection in selections {
10520            let range = selection.range().sorted();
10521            let buffer_start_row = range.start.row;
10522
10523            if range.start.row != range.end.row {
10524                let mut found = false;
10525                for row in range.start.row..=range.end.row {
10526                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10527                        found = true;
10528                        to_fold.push(crease);
10529                    }
10530                }
10531                if found {
10532                    continue;
10533                }
10534            }
10535
10536            for row in (0..=range.start.row).rev() {
10537                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10538                    if crease.range().end.row >= buffer_start_row {
10539                        to_fold.push(crease);
10540                    } else {
10541                        break;
10542                    }
10543                }
10544            }
10545        }
10546
10547        self.fold_creases(to_fold, true, cx);
10548    }
10549
10550    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10551        let buffer_row = fold_at.buffer_row;
10552        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10553
10554        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10555            let autoscroll = self
10556                .selections
10557                .all::<Point>(cx)
10558                .iter()
10559                .any(|selection| crease.range().overlaps(&selection.range()));
10560
10561            self.fold_creases(vec![crease], autoscroll, cx);
10562        }
10563    }
10564
10565    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10566        if self.is_singleton(cx) {
10567            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10568            let buffer = &display_map.buffer_snapshot;
10569            let selections = self.selections.all::<Point>(cx);
10570            let ranges = selections
10571                .iter()
10572                .map(|s| {
10573                    let range = s.display_range(&display_map).sorted();
10574                    let mut start = range.start.to_point(&display_map);
10575                    let mut end = range.end.to_point(&display_map);
10576                    start.column = 0;
10577                    end.column = buffer.line_len(MultiBufferRow(end.row));
10578                    start..end
10579                })
10580                .collect::<Vec<_>>();
10581
10582            self.unfold_ranges(&ranges, true, true, cx);
10583        } else {
10584            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10585            let mut unfolded_buffers = HashSet::default();
10586            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10587                self.selections
10588                    .disjoint_anchors()
10589                    .into_iter()
10590                    .map(|selection| selection.range()),
10591            ) {
10592                let buffer_id = buffer_snapshot.remote_id();
10593                if unfolded_buffers.insert(buffer_id) {
10594                    self.unfold_buffer(buffer_id, cx);
10595                }
10596            }
10597        }
10598    }
10599
10600    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10601        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10602        let selections = self.selections.all::<Point>(cx);
10603        let ranges = selections
10604            .iter()
10605            .map(|s| {
10606                let mut range = s.display_range(&display_map).sorted();
10607                *range.start.column_mut() = 0;
10608                *range.end.column_mut() = display_map.line_len(range.end.row());
10609                let start = range.start.to_point(&display_map);
10610                let end = range.end.to_point(&display_map);
10611                start..end
10612            })
10613            .collect::<Vec<_>>();
10614
10615        self.unfold_ranges(&ranges, true, true, cx);
10616    }
10617
10618    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10619        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10620
10621        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10622            ..Point::new(
10623                unfold_at.buffer_row.0,
10624                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10625            );
10626
10627        let autoscroll = self
10628            .selections
10629            .all::<Point>(cx)
10630            .iter()
10631            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10632
10633        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10634    }
10635
10636    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10637        if self.buffer.read(cx).is_singleton() {
10638            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10639            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10640        } else {
10641            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10642                editor
10643                    .update(&mut cx, |editor, cx| {
10644                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10645                            editor.unfold_buffer(buffer_id, cx);
10646                        }
10647                    })
10648                    .ok();
10649            });
10650        }
10651    }
10652
10653    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10654        let selections = self.selections.all::<Point>(cx);
10655        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10656        let line_mode = self.selections.line_mode;
10657        let ranges = selections
10658            .into_iter()
10659            .map(|s| {
10660                if line_mode {
10661                    let start = Point::new(s.start.row, 0);
10662                    let end = Point::new(
10663                        s.end.row,
10664                        display_map
10665                            .buffer_snapshot
10666                            .line_len(MultiBufferRow(s.end.row)),
10667                    );
10668                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10669                } else {
10670                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10671                }
10672            })
10673            .collect::<Vec<_>>();
10674        self.fold_creases(ranges, true, cx);
10675    }
10676
10677    pub fn fold_creases<T: ToOffset + Clone>(
10678        &mut self,
10679        creases: Vec<Crease<T>>,
10680        auto_scroll: bool,
10681        cx: &mut ViewContext<Self>,
10682    ) {
10683        if creases.is_empty() {
10684            return;
10685        }
10686
10687        let mut buffers_affected = HashSet::default();
10688        let multi_buffer = self.buffer().read(cx);
10689        for crease in &creases {
10690            if let Some((_, buffer, _)) =
10691                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10692            {
10693                buffers_affected.insert(buffer.read(cx).remote_id());
10694            };
10695        }
10696
10697        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10698
10699        if auto_scroll {
10700            self.request_autoscroll(Autoscroll::fit(), cx);
10701        }
10702
10703        for buffer_id in buffers_affected {
10704            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10705        }
10706
10707        cx.notify();
10708
10709        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10710            // Clear diagnostics block when folding a range that contains it.
10711            let snapshot = self.snapshot(cx);
10712            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10713                drop(snapshot);
10714                self.active_diagnostics = Some(active_diagnostics);
10715                self.dismiss_diagnostics(cx);
10716            } else {
10717                self.active_diagnostics = Some(active_diagnostics);
10718            }
10719        }
10720
10721        self.scrollbar_marker_state.dirty = true;
10722    }
10723
10724    /// Removes any folds whose ranges intersect any of the given ranges.
10725    pub fn unfold_ranges<T: ToOffset + Clone>(
10726        &mut self,
10727        ranges: &[Range<T>],
10728        inclusive: bool,
10729        auto_scroll: bool,
10730        cx: &mut ViewContext<Self>,
10731    ) {
10732        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10733            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10734        });
10735    }
10736
10737    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10738        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10739            return;
10740        }
10741        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10742            return;
10743        };
10744        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10745        self.display_map
10746            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10747        cx.emit(EditorEvent::BufferFoldToggled {
10748            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10749            folded: true,
10750        });
10751        cx.notify();
10752    }
10753
10754    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10755        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10756            return;
10757        }
10758        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10759            return;
10760        };
10761        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10762        self.display_map.update(cx, |display_map, cx| {
10763            display_map.unfold_buffer(buffer_id, cx);
10764        });
10765        cx.emit(EditorEvent::BufferFoldToggled {
10766            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10767            folded: false,
10768        });
10769        cx.notify();
10770    }
10771
10772    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10773        self.display_map.read(cx).buffer_folded(buffer)
10774    }
10775
10776    /// Removes any folds with the given ranges.
10777    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10778        &mut self,
10779        ranges: &[Range<T>],
10780        type_id: TypeId,
10781        auto_scroll: bool,
10782        cx: &mut ViewContext<Self>,
10783    ) {
10784        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10785            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10786        });
10787    }
10788
10789    fn remove_folds_with<T: ToOffset + Clone>(
10790        &mut self,
10791        ranges: &[Range<T>],
10792        auto_scroll: bool,
10793        cx: &mut ViewContext<Self>,
10794        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10795    ) {
10796        if ranges.is_empty() {
10797            return;
10798        }
10799
10800        let mut buffers_affected = HashSet::default();
10801        let multi_buffer = self.buffer().read(cx);
10802        for range in ranges {
10803            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10804                buffers_affected.insert(buffer.read(cx).remote_id());
10805            };
10806        }
10807
10808        self.display_map.update(cx, update);
10809
10810        if auto_scroll {
10811            self.request_autoscroll(Autoscroll::fit(), cx);
10812        }
10813
10814        for buffer_id in buffers_affected {
10815            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10816        }
10817
10818        cx.notify();
10819        self.scrollbar_marker_state.dirty = true;
10820        self.active_indent_guides_state.dirty = true;
10821    }
10822
10823    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10824        self.display_map.read(cx).fold_placeholder.clone()
10825    }
10826
10827    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10828        if hovered != self.gutter_hovered {
10829            self.gutter_hovered = hovered;
10830            cx.notify();
10831        }
10832    }
10833
10834    pub fn insert_blocks(
10835        &mut self,
10836        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10837        autoscroll: Option<Autoscroll>,
10838        cx: &mut ViewContext<Self>,
10839    ) -> Vec<CustomBlockId> {
10840        let blocks = self
10841            .display_map
10842            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10843        if let Some(autoscroll) = autoscroll {
10844            self.request_autoscroll(autoscroll, cx);
10845        }
10846        cx.notify();
10847        blocks
10848    }
10849
10850    pub fn resize_blocks(
10851        &mut self,
10852        heights: HashMap<CustomBlockId, u32>,
10853        autoscroll: Option<Autoscroll>,
10854        cx: &mut ViewContext<Self>,
10855    ) {
10856        self.display_map
10857            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10858        if let Some(autoscroll) = autoscroll {
10859            self.request_autoscroll(autoscroll, cx);
10860        }
10861        cx.notify();
10862    }
10863
10864    pub fn replace_blocks(
10865        &mut self,
10866        renderers: HashMap<CustomBlockId, RenderBlock>,
10867        autoscroll: Option<Autoscroll>,
10868        cx: &mut ViewContext<Self>,
10869    ) {
10870        self.display_map
10871            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10872        if let Some(autoscroll) = autoscroll {
10873            self.request_autoscroll(autoscroll, cx);
10874        }
10875        cx.notify();
10876    }
10877
10878    pub fn remove_blocks(
10879        &mut self,
10880        block_ids: HashSet<CustomBlockId>,
10881        autoscroll: Option<Autoscroll>,
10882        cx: &mut ViewContext<Self>,
10883    ) {
10884        self.display_map.update(cx, |display_map, cx| {
10885            display_map.remove_blocks(block_ids, cx)
10886        });
10887        if let Some(autoscroll) = autoscroll {
10888            self.request_autoscroll(autoscroll, cx);
10889        }
10890        cx.notify();
10891    }
10892
10893    pub fn row_for_block(
10894        &self,
10895        block_id: CustomBlockId,
10896        cx: &mut ViewContext<Self>,
10897    ) -> Option<DisplayRow> {
10898        self.display_map
10899            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10900    }
10901
10902    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10903        self.focused_block = Some(focused_block);
10904    }
10905
10906    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10907        self.focused_block.take()
10908    }
10909
10910    pub fn insert_creases(
10911        &mut self,
10912        creases: impl IntoIterator<Item = Crease<Anchor>>,
10913        cx: &mut ViewContext<Self>,
10914    ) -> Vec<CreaseId> {
10915        self.display_map
10916            .update(cx, |map, cx| map.insert_creases(creases, cx))
10917    }
10918
10919    pub fn remove_creases(
10920        &mut self,
10921        ids: impl IntoIterator<Item = CreaseId>,
10922        cx: &mut ViewContext<Self>,
10923    ) {
10924        self.display_map
10925            .update(cx, |map, cx| map.remove_creases(ids, cx));
10926    }
10927
10928    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10929        self.display_map
10930            .update(cx, |map, cx| map.snapshot(cx))
10931            .longest_row()
10932    }
10933
10934    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10935        self.display_map
10936            .update(cx, |map, cx| map.snapshot(cx))
10937            .max_point()
10938    }
10939
10940    pub fn text(&self, cx: &AppContext) -> String {
10941        self.buffer.read(cx).read(cx).text()
10942    }
10943
10944    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10945        let text = self.text(cx);
10946        let text = text.trim();
10947
10948        if text.is_empty() {
10949            return None;
10950        }
10951
10952        Some(text.to_string())
10953    }
10954
10955    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10956        self.transact(cx, |this, cx| {
10957            this.buffer
10958                .read(cx)
10959                .as_singleton()
10960                .expect("you can only call set_text on editors for singleton buffers")
10961                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10962        });
10963    }
10964
10965    pub fn display_text(&self, cx: &mut AppContext) -> String {
10966        self.display_map
10967            .update(cx, |map, cx| map.snapshot(cx))
10968            .text()
10969    }
10970
10971    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10972        let mut wrap_guides = smallvec::smallvec![];
10973
10974        if self.show_wrap_guides == Some(false) {
10975            return wrap_guides;
10976        }
10977
10978        let settings = self.buffer.read(cx).settings_at(0, cx);
10979        if settings.show_wrap_guides {
10980            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10981                wrap_guides.push((soft_wrap as usize, true));
10982            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10983                wrap_guides.push((soft_wrap as usize, true));
10984            }
10985            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10986        }
10987
10988        wrap_guides
10989    }
10990
10991    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10992        let settings = self.buffer.read(cx).settings_at(0, cx);
10993        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10994        match mode {
10995            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
10996                SoftWrap::None
10997            }
10998            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10999            language_settings::SoftWrap::PreferredLineLength => {
11000                SoftWrap::Column(settings.preferred_line_length)
11001            }
11002            language_settings::SoftWrap::Bounded => {
11003                SoftWrap::Bounded(settings.preferred_line_length)
11004            }
11005        }
11006    }
11007
11008    pub fn set_soft_wrap_mode(
11009        &mut self,
11010        mode: language_settings::SoftWrap,
11011        cx: &mut ViewContext<Self>,
11012    ) {
11013        self.soft_wrap_mode_override = Some(mode);
11014        cx.notify();
11015    }
11016
11017    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11018        self.text_style_refinement = Some(style);
11019    }
11020
11021    /// called by the Element so we know what style we were most recently rendered with.
11022    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11023        let rem_size = cx.rem_size();
11024        self.display_map.update(cx, |map, cx| {
11025            map.set_font(
11026                style.text.font(),
11027                style.text.font_size.to_pixels(rem_size),
11028                cx,
11029            )
11030        });
11031        self.style = Some(style);
11032    }
11033
11034    pub fn style(&self) -> Option<&EditorStyle> {
11035        self.style.as_ref()
11036    }
11037
11038    // Called by the element. This method is not designed to be called outside of the editor
11039    // element's layout code because it does not notify when rewrapping is computed synchronously.
11040    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11041        self.display_map
11042            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11043    }
11044
11045    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11046        if self.soft_wrap_mode_override.is_some() {
11047            self.soft_wrap_mode_override.take();
11048        } else {
11049            let soft_wrap = match self.soft_wrap_mode(cx) {
11050                SoftWrap::GitDiff => return,
11051                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11052                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11053                    language_settings::SoftWrap::None
11054                }
11055            };
11056            self.soft_wrap_mode_override = Some(soft_wrap);
11057        }
11058        cx.notify();
11059    }
11060
11061    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11062        let Some(workspace) = self.workspace() else {
11063            return;
11064        };
11065        let fs = workspace.read(cx).app_state().fs.clone();
11066        let current_show = TabBarSettings::get_global(cx).show;
11067        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11068            setting.show = Some(!current_show);
11069        });
11070    }
11071
11072    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11073        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11074            self.buffer
11075                .read(cx)
11076                .settings_at(0, cx)
11077                .indent_guides
11078                .enabled
11079        });
11080        self.show_indent_guides = Some(!currently_enabled);
11081        cx.notify();
11082    }
11083
11084    fn should_show_indent_guides(&self) -> Option<bool> {
11085        self.show_indent_guides
11086    }
11087
11088    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11089        let mut editor_settings = EditorSettings::get_global(cx).clone();
11090        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11091        EditorSettings::override_global(editor_settings, cx);
11092    }
11093
11094    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11095        self.use_relative_line_numbers
11096            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11097    }
11098
11099    pub fn toggle_relative_line_numbers(
11100        &mut self,
11101        _: &ToggleRelativeLineNumbers,
11102        cx: &mut ViewContext<Self>,
11103    ) {
11104        let is_relative = self.should_use_relative_line_numbers(cx);
11105        self.set_relative_line_number(Some(!is_relative), cx)
11106    }
11107
11108    pub fn set_relative_line_number(
11109        &mut self,
11110        is_relative: Option<bool>,
11111        cx: &mut ViewContext<Self>,
11112    ) {
11113        self.use_relative_line_numbers = is_relative;
11114        cx.notify();
11115    }
11116
11117    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11118        self.show_gutter = show_gutter;
11119        cx.notify();
11120    }
11121
11122    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11123        self.show_line_numbers = Some(show_line_numbers);
11124        cx.notify();
11125    }
11126
11127    pub fn set_show_git_diff_gutter(
11128        &mut self,
11129        show_git_diff_gutter: bool,
11130        cx: &mut ViewContext<Self>,
11131    ) {
11132        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11133        cx.notify();
11134    }
11135
11136    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11137        self.show_code_actions = Some(show_code_actions);
11138        cx.notify();
11139    }
11140
11141    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11142        self.show_runnables = Some(show_runnables);
11143        cx.notify();
11144    }
11145
11146    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11147        if self.display_map.read(cx).masked != masked {
11148            self.display_map.update(cx, |map, _| map.masked = masked);
11149        }
11150        cx.notify()
11151    }
11152
11153    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11154        self.show_wrap_guides = Some(show_wrap_guides);
11155        cx.notify();
11156    }
11157
11158    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11159        self.show_indent_guides = Some(show_indent_guides);
11160        cx.notify();
11161    }
11162
11163    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11164        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11165            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11166                if let Some(dir) = file.abs_path(cx).parent() {
11167                    return Some(dir.to_owned());
11168                }
11169            }
11170
11171            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11172                return Some(project_path.path.to_path_buf());
11173            }
11174        }
11175
11176        None
11177    }
11178
11179    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11180        self.active_excerpt(cx)?
11181            .1
11182            .read(cx)
11183            .file()
11184            .and_then(|f| f.as_local())
11185    }
11186
11187    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11188        if let Some(target) = self.target_file(cx) {
11189            cx.reveal_path(&target.abs_path(cx));
11190        }
11191    }
11192
11193    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11194        if let Some(file) = self.target_file(cx) {
11195            if let Some(path) = file.abs_path(cx).to_str() {
11196                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11197            }
11198        }
11199    }
11200
11201    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11202        if let Some(file) = self.target_file(cx) {
11203            if let Some(path) = file.path().to_str() {
11204                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11205            }
11206        }
11207    }
11208
11209    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11210        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11211
11212        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11213            self.start_git_blame(true, cx);
11214        }
11215
11216        cx.notify();
11217    }
11218
11219    pub fn toggle_git_blame_inline(
11220        &mut self,
11221        _: &ToggleGitBlameInline,
11222        cx: &mut ViewContext<Self>,
11223    ) {
11224        self.toggle_git_blame_inline_internal(true, cx);
11225        cx.notify();
11226    }
11227
11228    pub fn git_blame_inline_enabled(&self) -> bool {
11229        self.git_blame_inline_enabled
11230    }
11231
11232    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11233        self.show_selection_menu = self
11234            .show_selection_menu
11235            .map(|show_selections_menu| !show_selections_menu)
11236            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11237
11238        cx.notify();
11239    }
11240
11241    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11242        self.show_selection_menu
11243            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11244    }
11245
11246    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11247        if let Some(project) = self.project.as_ref() {
11248            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11249                return;
11250            };
11251
11252            if buffer.read(cx).file().is_none() {
11253                return;
11254            }
11255
11256            let focused = self.focus_handle(cx).contains_focused(cx);
11257
11258            let project = project.clone();
11259            let blame =
11260                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11261            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11262            self.blame = Some(blame);
11263        }
11264    }
11265
11266    fn toggle_git_blame_inline_internal(
11267        &mut self,
11268        user_triggered: bool,
11269        cx: &mut ViewContext<Self>,
11270    ) {
11271        if self.git_blame_inline_enabled {
11272            self.git_blame_inline_enabled = false;
11273            self.show_git_blame_inline = false;
11274            self.show_git_blame_inline_delay_task.take();
11275        } else {
11276            self.git_blame_inline_enabled = true;
11277            self.start_git_blame_inline(user_triggered, cx);
11278        }
11279
11280        cx.notify();
11281    }
11282
11283    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11284        self.start_git_blame(user_triggered, cx);
11285
11286        if ProjectSettings::get_global(cx)
11287            .git
11288            .inline_blame_delay()
11289            .is_some()
11290        {
11291            self.start_inline_blame_timer(cx);
11292        } else {
11293            self.show_git_blame_inline = true
11294        }
11295    }
11296
11297    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11298        self.blame.as_ref()
11299    }
11300
11301    pub fn show_git_blame_gutter(&self) -> bool {
11302        self.show_git_blame_gutter
11303    }
11304
11305    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11306        self.show_git_blame_gutter && self.has_blame_entries(cx)
11307    }
11308
11309    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11310        self.show_git_blame_inline
11311            && self.focus_handle.is_focused(cx)
11312            && !self.newest_selection_head_on_empty_line(cx)
11313            && self.has_blame_entries(cx)
11314    }
11315
11316    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11317        self.blame()
11318            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11319    }
11320
11321    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11322        let cursor_anchor = self.selections.newest_anchor().head();
11323
11324        let snapshot = self.buffer.read(cx).snapshot(cx);
11325        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11326
11327        snapshot.line_len(buffer_row) == 0
11328    }
11329
11330    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11331        let buffer_and_selection = maybe!({
11332            let selection = self.selections.newest::<Point>(cx);
11333            let selection_range = selection.range();
11334
11335            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11336                (buffer, selection_range.start.row..selection_range.end.row)
11337            } else {
11338                let buffer_ranges = self
11339                    .buffer()
11340                    .read(cx)
11341                    .range_to_buffer_ranges(selection_range, cx);
11342
11343                let (buffer, range, _) = if selection.reversed {
11344                    buffer_ranges.first()
11345                } else {
11346                    buffer_ranges.last()
11347                }?;
11348
11349                let snapshot = buffer.read(cx).snapshot();
11350                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11351                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11352                (buffer.clone(), selection)
11353            };
11354
11355            Some((buffer, selection))
11356        });
11357
11358        let Some((buffer, selection)) = buffer_and_selection else {
11359            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11360        };
11361
11362        let Some(project) = self.project.as_ref() else {
11363            return Task::ready(Err(anyhow!("editor does not have project")));
11364        };
11365
11366        project.update(cx, |project, cx| {
11367            project.get_permalink_to_line(&buffer, selection, cx)
11368        })
11369    }
11370
11371    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11372        let permalink_task = self.get_permalink_to_line(cx);
11373        let workspace = self.workspace();
11374
11375        cx.spawn(|_, mut cx| async move {
11376            match permalink_task.await {
11377                Ok(permalink) => {
11378                    cx.update(|cx| {
11379                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11380                    })
11381                    .ok();
11382                }
11383                Err(err) => {
11384                    let message = format!("Failed to copy permalink: {err}");
11385
11386                    Err::<(), anyhow::Error>(err).log_err();
11387
11388                    if let Some(workspace) = workspace {
11389                        workspace
11390                            .update(&mut cx, |workspace, cx| {
11391                                struct CopyPermalinkToLine;
11392
11393                                workspace.show_toast(
11394                                    Toast::new(
11395                                        NotificationId::unique::<CopyPermalinkToLine>(),
11396                                        message,
11397                                    ),
11398                                    cx,
11399                                )
11400                            })
11401                            .ok();
11402                    }
11403                }
11404            }
11405        })
11406        .detach();
11407    }
11408
11409    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11410        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11411        if let Some(file) = self.target_file(cx) {
11412            if let Some(path) = file.path().to_str() {
11413                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11414            }
11415        }
11416    }
11417
11418    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11419        let permalink_task = self.get_permalink_to_line(cx);
11420        let workspace = self.workspace();
11421
11422        cx.spawn(|_, mut cx| async move {
11423            match permalink_task.await {
11424                Ok(permalink) => {
11425                    cx.update(|cx| {
11426                        cx.open_url(permalink.as_ref());
11427                    })
11428                    .ok();
11429                }
11430                Err(err) => {
11431                    let message = format!("Failed to open permalink: {err}");
11432
11433                    Err::<(), anyhow::Error>(err).log_err();
11434
11435                    if let Some(workspace) = workspace {
11436                        workspace
11437                            .update(&mut cx, |workspace, cx| {
11438                                struct OpenPermalinkToLine;
11439
11440                                workspace.show_toast(
11441                                    Toast::new(
11442                                        NotificationId::unique::<OpenPermalinkToLine>(),
11443                                        message,
11444                                    ),
11445                                    cx,
11446                                )
11447                            })
11448                            .ok();
11449                    }
11450                }
11451            }
11452        })
11453        .detach();
11454    }
11455
11456    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11457        self.insert_uuid(UuidVersion::V4, cx);
11458    }
11459
11460    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11461        self.insert_uuid(UuidVersion::V7, cx);
11462    }
11463
11464    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11465        self.transact(cx, |this, cx| {
11466            let edits = this
11467                .selections
11468                .all::<Point>(cx)
11469                .into_iter()
11470                .map(|selection| {
11471                    let uuid = match version {
11472                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11473                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11474                    };
11475
11476                    (selection.range(), uuid.to_string())
11477                });
11478            this.edit(edits, cx);
11479            this.refresh_inline_completion(true, false, cx);
11480        });
11481    }
11482
11483    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11484    /// last highlight added will be used.
11485    ///
11486    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11487    pub fn highlight_rows<T: 'static>(
11488        &mut self,
11489        range: Range<Anchor>,
11490        color: Hsla,
11491        should_autoscroll: bool,
11492        cx: &mut ViewContext<Self>,
11493    ) {
11494        let snapshot = self.buffer().read(cx).snapshot(cx);
11495        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11496        let ix = row_highlights.binary_search_by(|highlight| {
11497            Ordering::Equal
11498                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11499                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11500        });
11501
11502        if let Err(mut ix) = ix {
11503            let index = post_inc(&mut self.highlight_order);
11504
11505            // If this range intersects with the preceding highlight, then merge it with
11506            // the preceding highlight. Otherwise insert a new highlight.
11507            let mut merged = false;
11508            if ix > 0 {
11509                let prev_highlight = &mut row_highlights[ix - 1];
11510                if prev_highlight
11511                    .range
11512                    .end
11513                    .cmp(&range.start, &snapshot)
11514                    .is_ge()
11515                {
11516                    ix -= 1;
11517                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11518                        prev_highlight.range.end = range.end;
11519                    }
11520                    merged = true;
11521                    prev_highlight.index = index;
11522                    prev_highlight.color = color;
11523                    prev_highlight.should_autoscroll = should_autoscroll;
11524                }
11525            }
11526
11527            if !merged {
11528                row_highlights.insert(
11529                    ix,
11530                    RowHighlight {
11531                        range: range.clone(),
11532                        index,
11533                        color,
11534                        should_autoscroll,
11535                    },
11536                );
11537            }
11538
11539            // If any of the following highlights intersect with this one, merge them.
11540            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11541                let highlight = &row_highlights[ix];
11542                if next_highlight
11543                    .range
11544                    .start
11545                    .cmp(&highlight.range.end, &snapshot)
11546                    .is_le()
11547                {
11548                    if next_highlight
11549                        .range
11550                        .end
11551                        .cmp(&highlight.range.end, &snapshot)
11552                        .is_gt()
11553                    {
11554                        row_highlights[ix].range.end = next_highlight.range.end;
11555                    }
11556                    row_highlights.remove(ix + 1);
11557                } else {
11558                    break;
11559                }
11560            }
11561        }
11562    }
11563
11564    /// Remove any highlighted row ranges of the given type that intersect the
11565    /// given ranges.
11566    pub fn remove_highlighted_rows<T: 'static>(
11567        &mut self,
11568        ranges_to_remove: Vec<Range<Anchor>>,
11569        cx: &mut ViewContext<Self>,
11570    ) {
11571        let snapshot = self.buffer().read(cx).snapshot(cx);
11572        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11573        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11574        row_highlights.retain(|highlight| {
11575            while let Some(range_to_remove) = ranges_to_remove.peek() {
11576                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11577                    Ordering::Less | Ordering::Equal => {
11578                        ranges_to_remove.next();
11579                    }
11580                    Ordering::Greater => {
11581                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11582                            Ordering::Less | Ordering::Equal => {
11583                                return false;
11584                            }
11585                            Ordering::Greater => break,
11586                        }
11587                    }
11588                }
11589            }
11590
11591            true
11592        })
11593    }
11594
11595    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11596    pub fn clear_row_highlights<T: 'static>(&mut self) {
11597        self.highlighted_rows.remove(&TypeId::of::<T>());
11598    }
11599
11600    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11601    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11602        self.highlighted_rows
11603            .get(&TypeId::of::<T>())
11604            .map_or(&[] as &[_], |vec| vec.as_slice())
11605            .iter()
11606            .map(|highlight| (highlight.range.clone(), highlight.color))
11607    }
11608
11609    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11610    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11611    /// Allows to ignore certain kinds of highlights.
11612    pub fn highlighted_display_rows(
11613        &mut self,
11614        cx: &mut WindowContext,
11615    ) -> BTreeMap<DisplayRow, Hsla> {
11616        let snapshot = self.snapshot(cx);
11617        let mut used_highlight_orders = HashMap::default();
11618        self.highlighted_rows
11619            .iter()
11620            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11621            .fold(
11622                BTreeMap::<DisplayRow, Hsla>::new(),
11623                |mut unique_rows, highlight| {
11624                    let start = highlight.range.start.to_display_point(&snapshot);
11625                    let end = highlight.range.end.to_display_point(&snapshot);
11626                    let start_row = start.row().0;
11627                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11628                        && end.column() == 0
11629                    {
11630                        end.row().0.saturating_sub(1)
11631                    } else {
11632                        end.row().0
11633                    };
11634                    for row in start_row..=end_row {
11635                        let used_index =
11636                            used_highlight_orders.entry(row).or_insert(highlight.index);
11637                        if highlight.index >= *used_index {
11638                            *used_index = highlight.index;
11639                            unique_rows.insert(DisplayRow(row), highlight.color);
11640                        }
11641                    }
11642                    unique_rows
11643                },
11644            )
11645    }
11646
11647    pub fn highlighted_display_row_for_autoscroll(
11648        &self,
11649        snapshot: &DisplaySnapshot,
11650    ) -> Option<DisplayRow> {
11651        self.highlighted_rows
11652            .values()
11653            .flat_map(|highlighted_rows| highlighted_rows.iter())
11654            .filter_map(|highlight| {
11655                if highlight.should_autoscroll {
11656                    Some(highlight.range.start.to_display_point(snapshot).row())
11657                } else {
11658                    None
11659                }
11660            })
11661            .min()
11662    }
11663
11664    pub fn set_search_within_ranges(
11665        &mut self,
11666        ranges: &[Range<Anchor>],
11667        cx: &mut ViewContext<Self>,
11668    ) {
11669        self.highlight_background::<SearchWithinRange>(
11670            ranges,
11671            |colors| colors.editor_document_highlight_read_background,
11672            cx,
11673        )
11674    }
11675
11676    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11677        self.breadcrumb_header = Some(new_header);
11678    }
11679
11680    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11681        self.clear_background_highlights::<SearchWithinRange>(cx);
11682    }
11683
11684    pub fn highlight_background<T: 'static>(
11685        &mut self,
11686        ranges: &[Range<Anchor>],
11687        color_fetcher: fn(&ThemeColors) -> Hsla,
11688        cx: &mut ViewContext<Self>,
11689    ) {
11690        self.background_highlights
11691            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11692        self.scrollbar_marker_state.dirty = true;
11693        cx.notify();
11694    }
11695
11696    pub fn clear_background_highlights<T: 'static>(
11697        &mut self,
11698        cx: &mut ViewContext<Self>,
11699    ) -> Option<BackgroundHighlight> {
11700        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11701        if !text_highlights.1.is_empty() {
11702            self.scrollbar_marker_state.dirty = true;
11703            cx.notify();
11704        }
11705        Some(text_highlights)
11706    }
11707
11708    pub fn highlight_gutter<T: 'static>(
11709        &mut self,
11710        ranges: &[Range<Anchor>],
11711        color_fetcher: fn(&AppContext) -> Hsla,
11712        cx: &mut ViewContext<Self>,
11713    ) {
11714        self.gutter_highlights
11715            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11716        cx.notify();
11717    }
11718
11719    pub fn clear_gutter_highlights<T: 'static>(
11720        &mut self,
11721        cx: &mut ViewContext<Self>,
11722    ) -> Option<GutterHighlight> {
11723        cx.notify();
11724        self.gutter_highlights.remove(&TypeId::of::<T>())
11725    }
11726
11727    #[cfg(feature = "test-support")]
11728    pub fn all_text_background_highlights(
11729        &mut self,
11730        cx: &mut ViewContext<Self>,
11731    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11732        let snapshot = self.snapshot(cx);
11733        let buffer = &snapshot.buffer_snapshot;
11734        let start = buffer.anchor_before(0);
11735        let end = buffer.anchor_after(buffer.len());
11736        let theme = cx.theme().colors();
11737        self.background_highlights_in_range(start..end, &snapshot, theme)
11738    }
11739
11740    #[cfg(feature = "test-support")]
11741    pub fn search_background_highlights(
11742        &mut self,
11743        cx: &mut ViewContext<Self>,
11744    ) -> Vec<Range<Point>> {
11745        let snapshot = self.buffer().read(cx).snapshot(cx);
11746
11747        let highlights = self
11748            .background_highlights
11749            .get(&TypeId::of::<items::BufferSearchHighlights>());
11750
11751        if let Some((_color, ranges)) = highlights {
11752            ranges
11753                .iter()
11754                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11755                .collect_vec()
11756        } else {
11757            vec![]
11758        }
11759    }
11760
11761    fn document_highlights_for_position<'a>(
11762        &'a self,
11763        position: Anchor,
11764        buffer: &'a MultiBufferSnapshot,
11765    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11766        let read_highlights = self
11767            .background_highlights
11768            .get(&TypeId::of::<DocumentHighlightRead>())
11769            .map(|h| &h.1);
11770        let write_highlights = self
11771            .background_highlights
11772            .get(&TypeId::of::<DocumentHighlightWrite>())
11773            .map(|h| &h.1);
11774        let left_position = position.bias_left(buffer);
11775        let right_position = position.bias_right(buffer);
11776        read_highlights
11777            .into_iter()
11778            .chain(write_highlights)
11779            .flat_map(move |ranges| {
11780                let start_ix = match ranges.binary_search_by(|probe| {
11781                    let cmp = probe.end.cmp(&left_position, buffer);
11782                    if cmp.is_ge() {
11783                        Ordering::Greater
11784                    } else {
11785                        Ordering::Less
11786                    }
11787                }) {
11788                    Ok(i) | Err(i) => i,
11789                };
11790
11791                ranges[start_ix..]
11792                    .iter()
11793                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11794            })
11795    }
11796
11797    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11798        self.background_highlights
11799            .get(&TypeId::of::<T>())
11800            .map_or(false, |(_, highlights)| !highlights.is_empty())
11801    }
11802
11803    pub fn background_highlights_in_range(
11804        &self,
11805        search_range: Range<Anchor>,
11806        display_snapshot: &DisplaySnapshot,
11807        theme: &ThemeColors,
11808    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11809        let mut results = Vec::new();
11810        for (color_fetcher, ranges) in self.background_highlights.values() {
11811            let color = color_fetcher(theme);
11812            let start_ix = match ranges.binary_search_by(|probe| {
11813                let cmp = probe
11814                    .end
11815                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11816                if cmp.is_gt() {
11817                    Ordering::Greater
11818                } else {
11819                    Ordering::Less
11820                }
11821            }) {
11822                Ok(i) | Err(i) => i,
11823            };
11824            for range in &ranges[start_ix..] {
11825                if range
11826                    .start
11827                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11828                    .is_ge()
11829                {
11830                    break;
11831                }
11832
11833                let start = range.start.to_display_point(display_snapshot);
11834                let end = range.end.to_display_point(display_snapshot);
11835                results.push((start..end, color))
11836            }
11837        }
11838        results
11839    }
11840
11841    pub fn background_highlight_row_ranges<T: 'static>(
11842        &self,
11843        search_range: Range<Anchor>,
11844        display_snapshot: &DisplaySnapshot,
11845        count: usize,
11846    ) -> Vec<RangeInclusive<DisplayPoint>> {
11847        let mut results = Vec::new();
11848        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11849            return vec![];
11850        };
11851
11852        let start_ix = match ranges.binary_search_by(|probe| {
11853            let cmp = probe
11854                .end
11855                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11856            if cmp.is_gt() {
11857                Ordering::Greater
11858            } else {
11859                Ordering::Less
11860            }
11861        }) {
11862            Ok(i) | Err(i) => i,
11863        };
11864        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11865            if let (Some(start_display), Some(end_display)) = (start, end) {
11866                results.push(
11867                    start_display.to_display_point(display_snapshot)
11868                        ..=end_display.to_display_point(display_snapshot),
11869                );
11870            }
11871        };
11872        let mut start_row: Option<Point> = None;
11873        let mut end_row: Option<Point> = None;
11874        if ranges.len() > count {
11875            return Vec::new();
11876        }
11877        for range in &ranges[start_ix..] {
11878            if range
11879                .start
11880                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11881                .is_ge()
11882            {
11883                break;
11884            }
11885            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11886            if let Some(current_row) = &end_row {
11887                if end.row == current_row.row {
11888                    continue;
11889                }
11890            }
11891            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11892            if start_row.is_none() {
11893                assert_eq!(end_row, None);
11894                start_row = Some(start);
11895                end_row = Some(end);
11896                continue;
11897            }
11898            if let Some(current_end) = end_row.as_mut() {
11899                if start.row > current_end.row + 1 {
11900                    push_region(start_row, end_row);
11901                    start_row = Some(start);
11902                    end_row = Some(end);
11903                } else {
11904                    // Merge two hunks.
11905                    *current_end = end;
11906                }
11907            } else {
11908                unreachable!();
11909            }
11910        }
11911        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11912        push_region(start_row, end_row);
11913        results
11914    }
11915
11916    pub fn gutter_highlights_in_range(
11917        &self,
11918        search_range: Range<Anchor>,
11919        display_snapshot: &DisplaySnapshot,
11920        cx: &AppContext,
11921    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11922        let mut results = Vec::new();
11923        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11924            let color = color_fetcher(cx);
11925            let start_ix = match ranges.binary_search_by(|probe| {
11926                let cmp = probe
11927                    .end
11928                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11929                if cmp.is_gt() {
11930                    Ordering::Greater
11931                } else {
11932                    Ordering::Less
11933                }
11934            }) {
11935                Ok(i) | Err(i) => i,
11936            };
11937            for range in &ranges[start_ix..] {
11938                if range
11939                    .start
11940                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11941                    .is_ge()
11942                {
11943                    break;
11944                }
11945
11946                let start = range.start.to_display_point(display_snapshot);
11947                let end = range.end.to_display_point(display_snapshot);
11948                results.push((start..end, color))
11949            }
11950        }
11951        results
11952    }
11953
11954    /// Get the text ranges corresponding to the redaction query
11955    pub fn redacted_ranges(
11956        &self,
11957        search_range: Range<Anchor>,
11958        display_snapshot: &DisplaySnapshot,
11959        cx: &WindowContext,
11960    ) -> Vec<Range<DisplayPoint>> {
11961        display_snapshot
11962            .buffer_snapshot
11963            .redacted_ranges(search_range, |file| {
11964                if let Some(file) = file {
11965                    file.is_private()
11966                        && EditorSettings::get(
11967                            Some(SettingsLocation {
11968                                worktree_id: file.worktree_id(cx),
11969                                path: file.path().as_ref(),
11970                            }),
11971                            cx,
11972                        )
11973                        .redact_private_values
11974                } else {
11975                    false
11976                }
11977            })
11978            .map(|range| {
11979                range.start.to_display_point(display_snapshot)
11980                    ..range.end.to_display_point(display_snapshot)
11981            })
11982            .collect()
11983    }
11984
11985    pub fn highlight_text<T: 'static>(
11986        &mut self,
11987        ranges: Vec<Range<Anchor>>,
11988        style: HighlightStyle,
11989        cx: &mut ViewContext<Self>,
11990    ) {
11991        self.display_map.update(cx, |map, _| {
11992            map.highlight_text(TypeId::of::<T>(), ranges, style)
11993        });
11994        cx.notify();
11995    }
11996
11997    pub(crate) fn highlight_inlays<T: 'static>(
11998        &mut self,
11999        highlights: Vec<InlayHighlight>,
12000        style: HighlightStyle,
12001        cx: &mut ViewContext<Self>,
12002    ) {
12003        self.display_map.update(cx, |map, _| {
12004            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12005        });
12006        cx.notify();
12007    }
12008
12009    pub fn text_highlights<'a, T: 'static>(
12010        &'a self,
12011        cx: &'a AppContext,
12012    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12013        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12014    }
12015
12016    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12017        let cleared = self
12018            .display_map
12019            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12020        if cleared {
12021            cx.notify();
12022        }
12023    }
12024
12025    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12026        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12027            && self.focus_handle.is_focused(cx)
12028    }
12029
12030    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12031        self.show_cursor_when_unfocused = is_enabled;
12032        cx.notify();
12033    }
12034
12035    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12036        self.project
12037            .as_ref()
12038            .map(|project| project.read(cx).lsp_store())
12039    }
12040
12041    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12042        cx.notify();
12043    }
12044
12045    fn on_buffer_event(
12046        &mut self,
12047        multibuffer: Model<MultiBuffer>,
12048        event: &multi_buffer::Event,
12049        cx: &mut ViewContext<Self>,
12050    ) {
12051        match event {
12052            multi_buffer::Event::Edited {
12053                singleton_buffer_edited,
12054                edited_buffer: buffer_edited,
12055            } => {
12056                self.scrollbar_marker_state.dirty = true;
12057                self.active_indent_guides_state.dirty = true;
12058                self.refresh_active_diagnostics(cx);
12059                self.refresh_code_actions(cx);
12060                if self.has_active_inline_completion() {
12061                    self.update_visible_inline_completion(cx);
12062                }
12063                if let Some(buffer) = buffer_edited {
12064                    let buffer_id = buffer.read(cx).remote_id();
12065                    if !self.registered_buffers.contains_key(&buffer_id) {
12066                        if let Some(lsp_store) = self.lsp_store(cx) {
12067                            lsp_store.update(cx, |lsp_store, cx| {
12068                                self.registered_buffers.insert(
12069                                    buffer_id,
12070                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12071                                );
12072                            })
12073                        }
12074                    }
12075                }
12076                cx.emit(EditorEvent::BufferEdited);
12077                cx.emit(SearchEvent::MatchesInvalidated);
12078                if *singleton_buffer_edited {
12079                    if let Some(project) = &self.project {
12080                        let project = project.read(cx);
12081                        #[allow(clippy::mutable_key_type)]
12082                        let languages_affected = multibuffer
12083                            .read(cx)
12084                            .all_buffers()
12085                            .into_iter()
12086                            .filter_map(|buffer| {
12087                                let buffer = buffer.read(cx);
12088                                let language = buffer.language()?;
12089                                if project.is_local()
12090                                    && project
12091                                        .language_servers_for_local_buffer(buffer, cx)
12092                                        .count()
12093                                        == 0
12094                                {
12095                                    None
12096                                } else {
12097                                    Some(language)
12098                                }
12099                            })
12100                            .cloned()
12101                            .collect::<HashSet<_>>();
12102                        if !languages_affected.is_empty() {
12103                            self.refresh_inlay_hints(
12104                                InlayHintRefreshReason::BufferEdited(languages_affected),
12105                                cx,
12106                            );
12107                        }
12108                    }
12109                }
12110
12111                let Some(project) = &self.project else { return };
12112                let (telemetry, is_via_ssh) = {
12113                    let project = project.read(cx);
12114                    let telemetry = project.client().telemetry().clone();
12115                    let is_via_ssh = project.is_via_ssh();
12116                    (telemetry, is_via_ssh)
12117                };
12118                refresh_linked_ranges(self, cx);
12119                telemetry.log_edit_event("editor", is_via_ssh);
12120            }
12121            multi_buffer::Event::ExcerptsAdded {
12122                buffer,
12123                predecessor,
12124                excerpts,
12125            } => {
12126                self.tasks_update_task = Some(self.refresh_runnables(cx));
12127                let buffer_id = buffer.read(cx).remote_id();
12128                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12129                    if let Some(project) = &self.project {
12130                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12131                    }
12132                }
12133                cx.emit(EditorEvent::ExcerptsAdded {
12134                    buffer: buffer.clone(),
12135                    predecessor: *predecessor,
12136                    excerpts: excerpts.clone(),
12137                });
12138                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12139            }
12140            multi_buffer::Event::ExcerptsRemoved { ids } => {
12141                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12142                let buffer = self.buffer.read(cx);
12143                self.registered_buffers
12144                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12145                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12146            }
12147            multi_buffer::Event::ExcerptsEdited { ids } => {
12148                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12149            }
12150            multi_buffer::Event::ExcerptsExpanded { ids } => {
12151                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12152            }
12153            multi_buffer::Event::Reparsed(buffer_id) => {
12154                self.tasks_update_task = Some(self.refresh_runnables(cx));
12155
12156                cx.emit(EditorEvent::Reparsed(*buffer_id));
12157            }
12158            multi_buffer::Event::LanguageChanged(buffer_id) => {
12159                linked_editing_ranges::refresh_linked_ranges(self, cx);
12160                cx.emit(EditorEvent::Reparsed(*buffer_id));
12161                cx.notify();
12162            }
12163            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12164            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12165            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12166                cx.emit(EditorEvent::TitleChanged)
12167            }
12168            // multi_buffer::Event::DiffBaseChanged => {
12169            //     self.scrollbar_marker_state.dirty = true;
12170            //     cx.emit(EditorEvent::DiffBaseChanged);
12171            //     cx.notify();
12172            // }
12173            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12174            multi_buffer::Event::DiagnosticsUpdated => {
12175                self.refresh_active_diagnostics(cx);
12176                self.scrollbar_marker_state.dirty = true;
12177                cx.notify();
12178            }
12179            _ => {}
12180        };
12181    }
12182
12183    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12184        cx.notify();
12185    }
12186
12187    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12188        self.tasks_update_task = Some(self.refresh_runnables(cx));
12189        self.refresh_inline_completion(true, false, cx);
12190        self.refresh_inlay_hints(
12191            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12192                self.selections.newest_anchor().head(),
12193                &self.buffer.read(cx).snapshot(cx),
12194                cx,
12195            )),
12196            cx,
12197        );
12198
12199        let old_cursor_shape = self.cursor_shape;
12200
12201        {
12202            let editor_settings = EditorSettings::get_global(cx);
12203            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12204            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12205            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12206        }
12207
12208        if old_cursor_shape != self.cursor_shape {
12209            cx.emit(EditorEvent::CursorShapeChanged);
12210        }
12211
12212        let project_settings = ProjectSettings::get_global(cx);
12213        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12214
12215        if self.mode == EditorMode::Full {
12216            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12217            if self.git_blame_inline_enabled != inline_blame_enabled {
12218                self.toggle_git_blame_inline_internal(false, cx);
12219            }
12220        }
12221
12222        cx.notify();
12223    }
12224
12225    pub fn set_searchable(&mut self, searchable: bool) {
12226        self.searchable = searchable;
12227    }
12228
12229    pub fn searchable(&self) -> bool {
12230        self.searchable
12231    }
12232
12233    fn open_proposed_changes_editor(
12234        &mut self,
12235        _: &OpenProposedChangesEditor,
12236        cx: &mut ViewContext<Self>,
12237    ) {
12238        let Some(workspace) = self.workspace() else {
12239            cx.propagate();
12240            return;
12241        };
12242
12243        let selections = self.selections.all::<usize>(cx);
12244        let buffer = self.buffer.read(cx);
12245        let mut new_selections_by_buffer = HashMap::default();
12246        for selection in selections {
12247            for (buffer, range, _) in
12248                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12249            {
12250                let mut range = range.to_point(buffer.read(cx));
12251                range.start.column = 0;
12252                range.end.column = buffer.read(cx).line_len(range.end.row);
12253                new_selections_by_buffer
12254                    .entry(buffer)
12255                    .or_insert(Vec::new())
12256                    .push(range)
12257            }
12258        }
12259
12260        let proposed_changes_buffers = new_selections_by_buffer
12261            .into_iter()
12262            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12263            .collect::<Vec<_>>();
12264        let proposed_changes_editor = cx.new_view(|cx| {
12265            ProposedChangesEditor::new(
12266                "Proposed changes",
12267                proposed_changes_buffers,
12268                self.project.clone(),
12269                cx,
12270            )
12271        });
12272
12273        cx.window_context().defer(move |cx| {
12274            workspace.update(cx, |workspace, cx| {
12275                workspace.active_pane().update(cx, |pane, cx| {
12276                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12277                });
12278            });
12279        });
12280    }
12281
12282    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12283        self.open_excerpts_common(None, true, cx)
12284    }
12285
12286    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12287        self.open_excerpts_common(None, false, cx)
12288    }
12289
12290    fn open_excerpts_common(
12291        &mut self,
12292        jump_data: Option<JumpData>,
12293        split: bool,
12294        cx: &mut ViewContext<Self>,
12295    ) {
12296        let Some(workspace) = self.workspace() else {
12297            cx.propagate();
12298            return;
12299        };
12300
12301        if self.buffer.read(cx).is_singleton() {
12302            cx.propagate();
12303            return;
12304        }
12305
12306        let mut new_selections_by_buffer = HashMap::default();
12307        match &jump_data {
12308            Some(jump_data) => {
12309                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12310                if let Some(buffer) = multi_buffer_snapshot
12311                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12312                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12313                {
12314                    let buffer_snapshot = buffer.read(cx).snapshot();
12315                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12316                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12317                    } else {
12318                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12319                    };
12320                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12321                    new_selections_by_buffer.insert(
12322                        buffer,
12323                        (
12324                            vec![jump_to_offset..jump_to_offset],
12325                            Some(jump_data.line_offset_from_top),
12326                        ),
12327                    );
12328                }
12329            }
12330            None => {
12331                let selections = self.selections.all::<usize>(cx);
12332                let buffer = self.buffer.read(cx);
12333                for selection in selections {
12334                    for (mut buffer_handle, mut range, _) in
12335                        buffer.range_to_buffer_ranges(selection.range(), cx)
12336                    {
12337                        // When editing branch buffers, jump to the corresponding location
12338                        // in their base buffer.
12339                        let buffer = buffer_handle.read(cx);
12340                        if let Some(base_buffer) = buffer.base_buffer() {
12341                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12342                            buffer_handle = base_buffer;
12343                        }
12344
12345                        if selection.reversed {
12346                            mem::swap(&mut range.start, &mut range.end);
12347                        }
12348                        new_selections_by_buffer
12349                            .entry(buffer_handle)
12350                            .or_insert((Vec::new(), None))
12351                            .0
12352                            .push(range)
12353                    }
12354                }
12355            }
12356        }
12357
12358        if new_selections_by_buffer.is_empty() {
12359            return;
12360        }
12361
12362        // We defer the pane interaction because we ourselves are a workspace item
12363        // and activating a new item causes the pane to call a method on us reentrantly,
12364        // which panics if we're on the stack.
12365        cx.window_context().defer(move |cx| {
12366            workspace.update(cx, |workspace, cx| {
12367                let pane = if split {
12368                    workspace.adjacent_pane(cx)
12369                } else {
12370                    workspace.active_pane().clone()
12371                };
12372
12373                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12374                    let editor = buffer
12375                        .read(cx)
12376                        .file()
12377                        .is_none()
12378                        .then(|| {
12379                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12380                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12381                            // Instead, we try to activate the existing editor in the pane first.
12382                            let (editor, pane_item_index) =
12383                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12384                                    let editor = item.downcast::<Editor>()?;
12385                                    let singleton_buffer =
12386                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12387                                    if singleton_buffer == buffer {
12388                                        Some((editor, i))
12389                                    } else {
12390                                        None
12391                                    }
12392                                })?;
12393                            pane.update(cx, |pane, cx| {
12394                                pane.activate_item(pane_item_index, true, true, cx)
12395                            });
12396                            Some(editor)
12397                        })
12398                        .flatten()
12399                        .unwrap_or_else(|| {
12400                            workspace.open_project_item::<Self>(
12401                                pane.clone(),
12402                                buffer,
12403                                true,
12404                                true,
12405                                cx,
12406                            )
12407                        });
12408
12409                    editor.update(cx, |editor, cx| {
12410                        let autoscroll = match scroll_offset {
12411                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12412                            None => Autoscroll::newest(),
12413                        };
12414                        let nav_history = editor.nav_history.take();
12415                        editor.change_selections(Some(autoscroll), cx, |s| {
12416                            s.select_ranges(ranges);
12417                        });
12418                        editor.nav_history = nav_history;
12419                    });
12420                }
12421            })
12422        });
12423    }
12424
12425    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12426        let snapshot = self.buffer.read(cx).read(cx);
12427        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12428        Some(
12429            ranges
12430                .iter()
12431                .map(move |range| {
12432                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12433                })
12434                .collect(),
12435        )
12436    }
12437
12438    fn selection_replacement_ranges(
12439        &self,
12440        range: Range<OffsetUtf16>,
12441        cx: &mut AppContext,
12442    ) -> Vec<Range<OffsetUtf16>> {
12443        let selections = self.selections.all::<OffsetUtf16>(cx);
12444        let newest_selection = selections
12445            .iter()
12446            .max_by_key(|selection| selection.id)
12447            .unwrap();
12448        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12449        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12450        let snapshot = self.buffer.read(cx).read(cx);
12451        selections
12452            .into_iter()
12453            .map(|mut selection| {
12454                selection.start.0 =
12455                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12456                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12457                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12458                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12459            })
12460            .collect()
12461    }
12462
12463    fn report_editor_event(
12464        &self,
12465        operation: &'static str,
12466        file_extension: Option<String>,
12467        cx: &AppContext,
12468    ) {
12469        if cfg!(any(test, feature = "test-support")) {
12470            return;
12471        }
12472
12473        let Some(project) = &self.project else { return };
12474
12475        // If None, we are in a file without an extension
12476        let file = self
12477            .buffer
12478            .read(cx)
12479            .as_singleton()
12480            .and_then(|b| b.read(cx).file());
12481        let file_extension = file_extension.or(file
12482            .as_ref()
12483            .and_then(|file| Path::new(file.file_name(cx)).extension())
12484            .and_then(|e| e.to_str())
12485            .map(|a| a.to_string()));
12486
12487        let vim_mode = cx
12488            .global::<SettingsStore>()
12489            .raw_user_settings()
12490            .get("vim_mode")
12491            == Some(&serde_json::Value::Bool(true));
12492
12493        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12494            == language::language_settings::InlineCompletionProvider::Copilot;
12495        let copilot_enabled_for_language = self
12496            .buffer
12497            .read(cx)
12498            .settings_at(0, cx)
12499            .show_inline_completions;
12500
12501        let project = project.read(cx);
12502        let telemetry = project.client().telemetry().clone();
12503        telemetry.report_editor_event(
12504            file_extension,
12505            vim_mode,
12506            operation,
12507            copilot_enabled,
12508            copilot_enabled_for_language,
12509            project.is_via_ssh(),
12510        )
12511    }
12512
12513    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12514    /// with each line being an array of {text, highlight} objects.
12515    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12516        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12517            return;
12518        };
12519
12520        #[derive(Serialize)]
12521        struct Chunk<'a> {
12522            text: String,
12523            highlight: Option<&'a str>,
12524        }
12525
12526        let snapshot = buffer.read(cx).snapshot();
12527        let range = self
12528            .selected_text_range(false, cx)
12529            .and_then(|selection| {
12530                if selection.range.is_empty() {
12531                    None
12532                } else {
12533                    Some(selection.range)
12534                }
12535            })
12536            .unwrap_or_else(|| 0..snapshot.len());
12537
12538        let chunks = snapshot.chunks(range, true);
12539        let mut lines = Vec::new();
12540        let mut line: VecDeque<Chunk> = VecDeque::new();
12541
12542        let Some(style) = self.style.as_ref() else {
12543            return;
12544        };
12545
12546        for chunk in chunks {
12547            let highlight = chunk
12548                .syntax_highlight_id
12549                .and_then(|id| id.name(&style.syntax));
12550            let mut chunk_lines = chunk.text.split('\n').peekable();
12551            while let Some(text) = chunk_lines.next() {
12552                let mut merged_with_last_token = false;
12553                if let Some(last_token) = line.back_mut() {
12554                    if last_token.highlight == highlight {
12555                        last_token.text.push_str(text);
12556                        merged_with_last_token = true;
12557                    }
12558                }
12559
12560                if !merged_with_last_token {
12561                    line.push_back(Chunk {
12562                        text: text.into(),
12563                        highlight,
12564                    });
12565                }
12566
12567                if chunk_lines.peek().is_some() {
12568                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12569                        line.pop_front();
12570                    }
12571                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12572                        line.pop_back();
12573                    }
12574
12575                    lines.push(mem::take(&mut line));
12576                }
12577            }
12578        }
12579
12580        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12581            return;
12582        };
12583        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12584    }
12585
12586    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12587        self.request_autoscroll(Autoscroll::newest(), cx);
12588        let position = self.selections.newest_display(cx).start;
12589        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12590    }
12591
12592    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12593        &self.inlay_hint_cache
12594    }
12595
12596    pub fn replay_insert_event(
12597        &mut self,
12598        text: &str,
12599        relative_utf16_range: Option<Range<isize>>,
12600        cx: &mut ViewContext<Self>,
12601    ) {
12602        if !self.input_enabled {
12603            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12604            return;
12605        }
12606        if let Some(relative_utf16_range) = relative_utf16_range {
12607            let selections = self.selections.all::<OffsetUtf16>(cx);
12608            self.change_selections(None, cx, |s| {
12609                let new_ranges = selections.into_iter().map(|range| {
12610                    let start = OffsetUtf16(
12611                        range
12612                            .head()
12613                            .0
12614                            .saturating_add_signed(relative_utf16_range.start),
12615                    );
12616                    let end = OffsetUtf16(
12617                        range
12618                            .head()
12619                            .0
12620                            .saturating_add_signed(relative_utf16_range.end),
12621                    );
12622                    start..end
12623                });
12624                s.select_ranges(new_ranges);
12625            });
12626        }
12627
12628        self.handle_input(text, cx);
12629    }
12630
12631    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12632        let Some(provider) = self.semantics_provider.as_ref() else {
12633            return false;
12634        };
12635
12636        let mut supports = false;
12637        self.buffer().read(cx).for_each_buffer(|buffer| {
12638            supports |= provider.supports_inlay_hints(buffer, cx);
12639        });
12640        supports
12641    }
12642
12643    pub fn focus(&self, cx: &mut WindowContext) {
12644        cx.focus(&self.focus_handle)
12645    }
12646
12647    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12648        self.focus_handle.is_focused(cx)
12649    }
12650
12651    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12652        cx.emit(EditorEvent::Focused);
12653
12654        if let Some(descendant) = self
12655            .last_focused_descendant
12656            .take()
12657            .and_then(|descendant| descendant.upgrade())
12658        {
12659            cx.focus(&descendant);
12660        } else {
12661            if let Some(blame) = self.blame.as_ref() {
12662                blame.update(cx, GitBlame::focus)
12663            }
12664
12665            self.blink_manager.update(cx, BlinkManager::enable);
12666            self.show_cursor_names(cx);
12667            self.buffer.update(cx, |buffer, cx| {
12668                buffer.finalize_last_transaction(cx);
12669                if self.leader_peer_id.is_none() {
12670                    buffer.set_active_selections(
12671                        &self.selections.disjoint_anchors(),
12672                        self.selections.line_mode,
12673                        self.cursor_shape,
12674                        cx,
12675                    );
12676                }
12677            });
12678        }
12679    }
12680
12681    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12682        cx.emit(EditorEvent::FocusedIn)
12683    }
12684
12685    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12686        if event.blurred != self.focus_handle {
12687            self.last_focused_descendant = Some(event.blurred);
12688        }
12689    }
12690
12691    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12692        self.blink_manager.update(cx, BlinkManager::disable);
12693        self.buffer
12694            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12695
12696        if let Some(blame) = self.blame.as_ref() {
12697            blame.update(cx, GitBlame::blur)
12698        }
12699        if !self.hover_state.focused(cx) {
12700            hide_hover(self, cx);
12701        }
12702
12703        self.hide_context_menu(cx);
12704        cx.emit(EditorEvent::Blurred);
12705        cx.notify();
12706    }
12707
12708    pub fn register_action<A: Action>(
12709        &mut self,
12710        listener: impl Fn(&A, &mut WindowContext) + 'static,
12711    ) -> Subscription {
12712        let id = self.next_editor_action_id.post_inc();
12713        let listener = Arc::new(listener);
12714        self.editor_actions.borrow_mut().insert(
12715            id,
12716            Box::new(move |cx| {
12717                let cx = cx.window_context();
12718                let listener = listener.clone();
12719                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12720                    let action = action.downcast_ref().unwrap();
12721                    if phase == DispatchPhase::Bubble {
12722                        listener(action, cx)
12723                    }
12724                })
12725            }),
12726        );
12727
12728        let editor_actions = self.editor_actions.clone();
12729        Subscription::new(move || {
12730            editor_actions.borrow_mut().remove(&id);
12731        })
12732    }
12733
12734    pub fn file_header_size(&self) -> u32 {
12735        FILE_HEADER_HEIGHT
12736    }
12737
12738    pub fn revert(
12739        &mut self,
12740        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12741        cx: &mut ViewContext<Self>,
12742    ) {
12743        self.buffer().update(cx, |multi_buffer, cx| {
12744            for (buffer_id, changes) in revert_changes {
12745                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12746                    buffer.update(cx, |buffer, cx| {
12747                        buffer.edit(
12748                            changes.into_iter().map(|(range, text)| {
12749                                (range, text.to_string().map(Arc::<str>::from))
12750                            }),
12751                            None,
12752                            cx,
12753                        );
12754                    });
12755                }
12756            }
12757        });
12758        self.change_selections(None, cx, |selections| selections.refresh());
12759    }
12760
12761    pub fn to_pixel_point(
12762        &mut self,
12763        source: multi_buffer::Anchor,
12764        editor_snapshot: &EditorSnapshot,
12765        cx: &mut ViewContext<Self>,
12766    ) -> Option<gpui::Point<Pixels>> {
12767        let source_point = source.to_display_point(editor_snapshot);
12768        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12769    }
12770
12771    pub fn display_to_pixel_point(
12772        &self,
12773        source: DisplayPoint,
12774        editor_snapshot: &EditorSnapshot,
12775        cx: &WindowContext,
12776    ) -> Option<gpui::Point<Pixels>> {
12777        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12778        let text_layout_details = self.text_layout_details(cx);
12779        let scroll_top = text_layout_details
12780            .scroll_anchor
12781            .scroll_position(editor_snapshot)
12782            .y;
12783
12784        if source.row().as_f32() < scroll_top.floor() {
12785            return None;
12786        }
12787        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12788        let source_y = line_height * (source.row().as_f32() - scroll_top);
12789        Some(gpui::Point::new(source_x, source_y))
12790    }
12791
12792    pub fn has_active_completions_menu(&self) -> bool {
12793        self.context_menu.borrow().as_ref().map_or(false, |menu| {
12794            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12795        })
12796    }
12797
12798    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12799        self.addons
12800            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12801    }
12802
12803    pub fn unregister_addon<T: Addon>(&mut self) {
12804        self.addons.remove(&std::any::TypeId::of::<T>());
12805    }
12806
12807    pub fn addon<T: Addon>(&self) -> Option<&T> {
12808        let type_id = std::any::TypeId::of::<T>();
12809        self.addons
12810            .get(&type_id)
12811            .and_then(|item| item.to_any().downcast_ref::<T>())
12812    }
12813
12814    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12815        let text_layout_details = self.text_layout_details(cx);
12816        let style = &text_layout_details.editor_style;
12817        let font_id = cx.text_system().resolve_font(&style.text.font());
12818        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12819        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12820
12821        let em_width = cx
12822            .text_system()
12823            .typographic_bounds(font_id, font_size, 'm')
12824            .unwrap()
12825            .size
12826            .width;
12827
12828        gpui::Point::new(em_width, line_height)
12829    }
12830}
12831
12832fn get_unstaged_changes_for_buffers(
12833    project: &Model<Project>,
12834    buffers: impl IntoIterator<Item = Model<Buffer>>,
12835    cx: &mut ViewContext<Editor>,
12836) {
12837    let mut tasks = Vec::new();
12838    project.update(cx, |project, cx| {
12839        for buffer in buffers {
12840            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12841        }
12842    });
12843    cx.spawn(|this, mut cx| async move {
12844        let change_sets = futures::future::join_all(tasks).await;
12845        this.update(&mut cx, |this, cx| {
12846            for change_set in change_sets {
12847                if let Some(change_set) = change_set.log_err() {
12848                    this.diff_map.add_change_set(change_set, cx);
12849                }
12850            }
12851        })
12852        .ok();
12853    })
12854    .detach();
12855}
12856
12857fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12858    let tab_size = tab_size.get() as usize;
12859    let mut width = offset;
12860
12861    for ch in text.chars() {
12862        width += if ch == '\t' {
12863            tab_size - (width % tab_size)
12864        } else {
12865            1
12866        };
12867    }
12868
12869    width - offset
12870}
12871
12872#[cfg(test)]
12873mod tests {
12874    use super::*;
12875
12876    #[test]
12877    fn test_string_size_with_expanded_tabs() {
12878        let nz = |val| NonZeroU32::new(val).unwrap();
12879        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12880        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12881        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12882        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12883        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12884        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12885        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12886        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12887    }
12888}
12889
12890/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12891struct WordBreakingTokenizer<'a> {
12892    input: &'a str,
12893}
12894
12895impl<'a> WordBreakingTokenizer<'a> {
12896    fn new(input: &'a str) -> Self {
12897        Self { input }
12898    }
12899}
12900
12901fn is_char_ideographic(ch: char) -> bool {
12902    use unicode_script::Script::*;
12903    use unicode_script::UnicodeScript;
12904    matches!(ch.script(), Han | Tangut | Yi)
12905}
12906
12907fn is_grapheme_ideographic(text: &str) -> bool {
12908    text.chars().any(is_char_ideographic)
12909}
12910
12911fn is_grapheme_whitespace(text: &str) -> bool {
12912    text.chars().any(|x| x.is_whitespace())
12913}
12914
12915fn should_stay_with_preceding_ideograph(text: &str) -> bool {
12916    text.chars().next().map_or(false, |ch| {
12917        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
12918    })
12919}
12920
12921#[derive(PartialEq, Eq, Debug, Clone, Copy)]
12922struct WordBreakToken<'a> {
12923    token: &'a str,
12924    grapheme_len: usize,
12925    is_whitespace: bool,
12926}
12927
12928impl<'a> Iterator for WordBreakingTokenizer<'a> {
12929    /// Yields a span, the count of graphemes in the token, and whether it was
12930    /// whitespace. Note that it also breaks at word boundaries.
12931    type Item = WordBreakToken<'a>;
12932
12933    fn next(&mut self) -> Option<Self::Item> {
12934        use unicode_segmentation::UnicodeSegmentation;
12935        if self.input.is_empty() {
12936            return None;
12937        }
12938
12939        let mut iter = self.input.graphemes(true).peekable();
12940        let mut offset = 0;
12941        let mut graphemes = 0;
12942        if let Some(first_grapheme) = iter.next() {
12943            let is_whitespace = is_grapheme_whitespace(first_grapheme);
12944            offset += first_grapheme.len();
12945            graphemes += 1;
12946            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
12947                if let Some(grapheme) = iter.peek().copied() {
12948                    if should_stay_with_preceding_ideograph(grapheme) {
12949                        offset += grapheme.len();
12950                        graphemes += 1;
12951                    }
12952                }
12953            } else {
12954                let mut words = self.input[offset..].split_word_bound_indices().peekable();
12955                let mut next_word_bound = words.peek().copied();
12956                if next_word_bound.map_or(false, |(i, _)| i == 0) {
12957                    next_word_bound = words.next();
12958                }
12959                while let Some(grapheme) = iter.peek().copied() {
12960                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
12961                        break;
12962                    };
12963                    if is_grapheme_whitespace(grapheme) != is_whitespace {
12964                        break;
12965                    };
12966                    offset += grapheme.len();
12967                    graphemes += 1;
12968                    iter.next();
12969                }
12970            }
12971            let token = &self.input[..offset];
12972            self.input = &self.input[offset..];
12973            if is_whitespace {
12974                Some(WordBreakToken {
12975                    token: " ",
12976                    grapheme_len: 1,
12977                    is_whitespace: true,
12978                })
12979            } else {
12980                Some(WordBreakToken {
12981                    token,
12982                    grapheme_len: graphemes,
12983                    is_whitespace: false,
12984                })
12985            }
12986        } else {
12987            None
12988        }
12989    }
12990}
12991
12992#[test]
12993fn test_word_breaking_tokenizer() {
12994    let tests: &[(&str, &[(&str, usize, bool)])] = &[
12995        ("", &[]),
12996        ("  ", &[(" ", 1, true)]),
12997        ("Ʒ", &[("Ʒ", 1, false)]),
12998        ("Ǽ", &[("Ǽ", 1, false)]),
12999        ("", &[("", 1, false)]),
13000        ("⋑⋑", &[("⋑⋑", 2, false)]),
13001        (
13002            "原理,进而",
13003            &[
13004                ("", 1, false),
13005                ("理,", 2, false),
13006                ("", 1, false),
13007                ("", 1, false),
13008            ],
13009        ),
13010        (
13011            "hello world",
13012            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13013        ),
13014        (
13015            "hello, world",
13016            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13017        ),
13018        (
13019            "  hello world",
13020            &[
13021                (" ", 1, true),
13022                ("hello", 5, false),
13023                (" ", 1, true),
13024                ("world", 5, false),
13025            ],
13026        ),
13027        (
13028            "这是什么 \n 钢笔",
13029            &[
13030                ("", 1, false),
13031                ("", 1, false),
13032                ("", 1, false),
13033                ("", 1, false),
13034                (" ", 1, true),
13035                ("", 1, false),
13036                ("", 1, false),
13037            ],
13038        ),
13039        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13040    ];
13041
13042    for (input, result) in tests {
13043        assert_eq!(
13044            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13045            result
13046                .iter()
13047                .copied()
13048                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13049                    token,
13050                    grapheme_len,
13051                    is_whitespace,
13052                })
13053                .collect::<Vec<_>>()
13054        );
13055    }
13056}
13057
13058fn wrap_with_prefix(
13059    line_prefix: String,
13060    unwrapped_text: String,
13061    wrap_column: usize,
13062    tab_size: NonZeroU32,
13063) -> String {
13064    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13065    let mut wrapped_text = String::new();
13066    let mut current_line = line_prefix.clone();
13067
13068    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13069    let mut current_line_len = line_prefix_len;
13070    for WordBreakToken {
13071        token,
13072        grapheme_len,
13073        is_whitespace,
13074    } in tokenizer
13075    {
13076        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13077            wrapped_text.push_str(current_line.trim_end());
13078            wrapped_text.push('\n');
13079            current_line.truncate(line_prefix.len());
13080            current_line_len = line_prefix_len;
13081            if !is_whitespace {
13082                current_line.push_str(token);
13083                current_line_len += grapheme_len;
13084            }
13085        } else if !is_whitespace {
13086            current_line.push_str(token);
13087            current_line_len += grapheme_len;
13088        } else if current_line_len != line_prefix_len {
13089            current_line.push(' ');
13090            current_line_len += 1;
13091        }
13092    }
13093
13094    if !current_line.is_empty() {
13095        wrapped_text.push_str(&current_line);
13096    }
13097    wrapped_text
13098}
13099
13100#[test]
13101fn test_wrap_with_prefix() {
13102    assert_eq!(
13103        wrap_with_prefix(
13104            "# ".to_string(),
13105            "abcdefg".to_string(),
13106            4,
13107            NonZeroU32::new(4).unwrap()
13108        ),
13109        "# abcdefg"
13110    );
13111    assert_eq!(
13112        wrap_with_prefix(
13113            "".to_string(),
13114            "\thello world".to_string(),
13115            8,
13116            NonZeroU32::new(4).unwrap()
13117        ),
13118        "hello\nworld"
13119    );
13120    assert_eq!(
13121        wrap_with_prefix(
13122            "// ".to_string(),
13123            "xx \nyy zz aa bb cc".to_string(),
13124            12,
13125            NonZeroU32::new(4).unwrap()
13126        ),
13127        "// xx yy zz\n// aa bb cc"
13128    );
13129    assert_eq!(
13130        wrap_with_prefix(
13131            String::new(),
13132            "这是什么 \n 钢笔".to_string(),
13133            3,
13134            NonZeroU32::new(4).unwrap()
13135        ),
13136        "这是什\n么 钢\n"
13137    );
13138}
13139
13140fn hunks_for_selections(
13141    snapshot: &EditorSnapshot,
13142    selections: &[Selection<Point>],
13143) -> Vec<MultiBufferDiffHunk> {
13144    hunks_for_ranges(
13145        selections.iter().map(|selection| selection.range()),
13146        snapshot,
13147    )
13148}
13149
13150pub fn hunks_for_ranges(
13151    ranges: impl Iterator<Item = Range<Point>>,
13152    snapshot: &EditorSnapshot,
13153) -> Vec<MultiBufferDiffHunk> {
13154    let mut hunks = Vec::new();
13155    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13156        HashMap::default();
13157    for query_range in ranges {
13158        let query_rows =
13159            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13160        for hunk in snapshot.diff_map.diff_hunks_in_range(
13161            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13162            &snapshot.buffer_snapshot,
13163        ) {
13164            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13165            // when the caret is just above or just below the deleted hunk.
13166            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13167            let related_to_selection = if allow_adjacent {
13168                hunk.row_range.overlaps(&query_rows)
13169                    || hunk.row_range.start == query_rows.end
13170                    || hunk.row_range.end == query_rows.start
13171            } else {
13172                hunk.row_range.overlaps(&query_rows)
13173            };
13174            if related_to_selection {
13175                if !processed_buffer_rows
13176                    .entry(hunk.buffer_id)
13177                    .or_default()
13178                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13179                {
13180                    continue;
13181                }
13182                hunks.push(hunk);
13183            }
13184        }
13185    }
13186
13187    hunks
13188}
13189
13190pub trait CollaborationHub {
13191    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13192    fn user_participant_indices<'a>(
13193        &self,
13194        cx: &'a AppContext,
13195    ) -> &'a HashMap<u64, ParticipantIndex>;
13196    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13197}
13198
13199impl CollaborationHub for Model<Project> {
13200    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13201        self.read(cx).collaborators()
13202    }
13203
13204    fn user_participant_indices<'a>(
13205        &self,
13206        cx: &'a AppContext,
13207    ) -> &'a HashMap<u64, ParticipantIndex> {
13208        self.read(cx).user_store().read(cx).participant_indices()
13209    }
13210
13211    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13212        let this = self.read(cx);
13213        let user_ids = this.collaborators().values().map(|c| c.user_id);
13214        this.user_store().read_with(cx, |user_store, cx| {
13215            user_store.participant_names(user_ids, cx)
13216        })
13217    }
13218}
13219
13220pub trait SemanticsProvider {
13221    fn hover(
13222        &self,
13223        buffer: &Model<Buffer>,
13224        position: text::Anchor,
13225        cx: &mut AppContext,
13226    ) -> Option<Task<Vec<project::Hover>>>;
13227
13228    fn inlay_hints(
13229        &self,
13230        buffer_handle: Model<Buffer>,
13231        range: Range<text::Anchor>,
13232        cx: &mut AppContext,
13233    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13234
13235    fn resolve_inlay_hint(
13236        &self,
13237        hint: InlayHint,
13238        buffer_handle: Model<Buffer>,
13239        server_id: LanguageServerId,
13240        cx: &mut AppContext,
13241    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13242
13243    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13244
13245    fn document_highlights(
13246        &self,
13247        buffer: &Model<Buffer>,
13248        position: text::Anchor,
13249        cx: &mut AppContext,
13250    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13251
13252    fn definitions(
13253        &self,
13254        buffer: &Model<Buffer>,
13255        position: text::Anchor,
13256        kind: GotoDefinitionKind,
13257        cx: &mut AppContext,
13258    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13259
13260    fn range_for_rename(
13261        &self,
13262        buffer: &Model<Buffer>,
13263        position: text::Anchor,
13264        cx: &mut AppContext,
13265    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13266
13267    fn perform_rename(
13268        &self,
13269        buffer: &Model<Buffer>,
13270        position: text::Anchor,
13271        new_name: String,
13272        cx: &mut AppContext,
13273    ) -> Option<Task<Result<ProjectTransaction>>>;
13274}
13275
13276pub trait CompletionProvider {
13277    fn completions(
13278        &self,
13279        buffer: &Model<Buffer>,
13280        buffer_position: text::Anchor,
13281        trigger: CompletionContext,
13282        cx: &mut ViewContext<Editor>,
13283    ) -> Task<Result<Vec<Completion>>>;
13284
13285    fn resolve_completions(
13286        &self,
13287        buffer: Model<Buffer>,
13288        completion_indices: Vec<usize>,
13289        completions: Rc<RefCell<Box<[Completion]>>>,
13290        cx: &mut ViewContext<Editor>,
13291    ) -> Task<Result<bool>>;
13292
13293    fn apply_additional_edits_for_completion(
13294        &self,
13295        buffer: Model<Buffer>,
13296        completion: Completion,
13297        push_to_history: bool,
13298        cx: &mut ViewContext<Editor>,
13299    ) -> Task<Result<Option<language::Transaction>>>;
13300
13301    fn is_completion_trigger(
13302        &self,
13303        buffer: &Model<Buffer>,
13304        position: language::Anchor,
13305        text: &str,
13306        trigger_in_words: bool,
13307        cx: &mut ViewContext<Editor>,
13308    ) -> bool;
13309
13310    fn sort_completions(&self) -> bool {
13311        true
13312    }
13313}
13314
13315pub trait CodeActionProvider {
13316    fn code_actions(
13317        &self,
13318        buffer: &Model<Buffer>,
13319        range: Range<text::Anchor>,
13320        cx: &mut WindowContext,
13321    ) -> Task<Result<Vec<CodeAction>>>;
13322
13323    fn apply_code_action(
13324        &self,
13325        buffer_handle: Model<Buffer>,
13326        action: CodeAction,
13327        excerpt_id: ExcerptId,
13328        push_to_history: bool,
13329        cx: &mut WindowContext,
13330    ) -> Task<Result<ProjectTransaction>>;
13331}
13332
13333impl CodeActionProvider for Model<Project> {
13334    fn code_actions(
13335        &self,
13336        buffer: &Model<Buffer>,
13337        range: Range<text::Anchor>,
13338        cx: &mut WindowContext,
13339    ) -> Task<Result<Vec<CodeAction>>> {
13340        self.update(cx, |project, cx| {
13341            project.code_actions(buffer, range, None, cx)
13342        })
13343    }
13344
13345    fn apply_code_action(
13346        &self,
13347        buffer_handle: Model<Buffer>,
13348        action: CodeAction,
13349        _excerpt_id: ExcerptId,
13350        push_to_history: bool,
13351        cx: &mut WindowContext,
13352    ) -> Task<Result<ProjectTransaction>> {
13353        self.update(cx, |project, cx| {
13354            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13355        })
13356    }
13357}
13358
13359fn snippet_completions(
13360    project: &Project,
13361    buffer: &Model<Buffer>,
13362    buffer_position: text::Anchor,
13363    cx: &mut AppContext,
13364) -> Task<Result<Vec<Completion>>> {
13365    let language = buffer.read(cx).language_at(buffer_position);
13366    let language_name = language.as_ref().map(|language| language.lsp_id());
13367    let snippet_store = project.snippets().read(cx);
13368    let snippets = snippet_store.snippets_for(language_name, cx);
13369
13370    if snippets.is_empty() {
13371        return Task::ready(Ok(vec![]));
13372    }
13373    let snapshot = buffer.read(cx).text_snapshot();
13374    let chars: String = snapshot
13375        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13376        .collect();
13377
13378    let scope = language.map(|language| language.default_scope());
13379    let executor = cx.background_executor().clone();
13380
13381    cx.background_executor().spawn(async move {
13382        let classifier = CharClassifier::new(scope).for_completion(true);
13383        let mut last_word = chars
13384            .chars()
13385            .take_while(|c| classifier.is_word(*c))
13386            .collect::<String>();
13387        last_word = last_word.chars().rev().collect();
13388
13389        if last_word.is_empty() {
13390            return Ok(vec![]);
13391        }
13392
13393        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13394        let to_lsp = |point: &text::Anchor| {
13395            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13396            point_to_lsp(end)
13397        };
13398        let lsp_end = to_lsp(&buffer_position);
13399
13400        let candidates = snippets
13401            .iter()
13402            .enumerate()
13403            .flat_map(|(ix, snippet)| {
13404                snippet
13405                    .prefix
13406                    .iter()
13407                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13408            })
13409            .collect::<Vec<StringMatchCandidate>>();
13410
13411        let mut matches = fuzzy::match_strings(
13412            &candidates,
13413            &last_word,
13414            last_word.chars().any(|c| c.is_uppercase()),
13415            100,
13416            &Default::default(),
13417            executor,
13418        )
13419        .await;
13420
13421        // Remove all candidates where the query's start does not match the start of any word in the candidate
13422        if let Some(query_start) = last_word.chars().next() {
13423            matches.retain(|string_match| {
13424                split_words(&string_match.string).any(|word| {
13425                    // Check that the first codepoint of the word as lowercase matches the first
13426                    // codepoint of the query as lowercase
13427                    word.chars()
13428                        .flat_map(|codepoint| codepoint.to_lowercase())
13429                        .zip(query_start.to_lowercase())
13430                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13431                })
13432            });
13433        }
13434
13435        let matched_strings = matches
13436            .into_iter()
13437            .map(|m| m.string)
13438            .collect::<HashSet<_>>();
13439
13440        let result: Vec<Completion> = snippets
13441            .into_iter()
13442            .filter_map(|snippet| {
13443                let matching_prefix = snippet
13444                    .prefix
13445                    .iter()
13446                    .find(|prefix| matched_strings.contains(*prefix))?;
13447                let start = as_offset - last_word.len();
13448                let start = snapshot.anchor_before(start);
13449                let range = start..buffer_position;
13450                let lsp_start = to_lsp(&start);
13451                let lsp_range = lsp::Range {
13452                    start: lsp_start,
13453                    end: lsp_end,
13454                };
13455                Some(Completion {
13456                    old_range: range,
13457                    new_text: snippet.body.clone(),
13458                    label: CodeLabel {
13459                        text: matching_prefix.clone(),
13460                        runs: vec![],
13461                        filter_range: 0..matching_prefix.len(),
13462                    },
13463                    server_id: LanguageServerId(usize::MAX),
13464                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13465                    lsp_completion: lsp::CompletionItem {
13466                        label: snippet.prefix.first().unwrap().clone(),
13467                        kind: Some(CompletionItemKind::SNIPPET),
13468                        label_details: snippet.description.as_ref().map(|description| {
13469                            lsp::CompletionItemLabelDetails {
13470                                detail: Some(description.clone()),
13471                                description: None,
13472                            }
13473                        }),
13474                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13475                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13476                            lsp::InsertReplaceEdit {
13477                                new_text: snippet.body.clone(),
13478                                insert: lsp_range,
13479                                replace: lsp_range,
13480                            },
13481                        )),
13482                        filter_text: Some(snippet.body.clone()),
13483                        sort_text: Some(char::MAX.to_string()),
13484                        ..Default::default()
13485                    },
13486                    confirm: None,
13487                })
13488            })
13489            .collect();
13490
13491        Ok(result)
13492    })
13493}
13494
13495impl CompletionProvider for Model<Project> {
13496    fn completions(
13497        &self,
13498        buffer: &Model<Buffer>,
13499        buffer_position: text::Anchor,
13500        options: CompletionContext,
13501        cx: &mut ViewContext<Editor>,
13502    ) -> Task<Result<Vec<Completion>>> {
13503        self.update(cx, |project, cx| {
13504            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13505            let project_completions = project.completions(buffer, buffer_position, options, cx);
13506            cx.background_executor().spawn(async move {
13507                let mut completions = project_completions.await?;
13508                let snippets_completions = snippets.await?;
13509                completions.extend(snippets_completions);
13510                Ok(completions)
13511            })
13512        })
13513    }
13514
13515    fn resolve_completions(
13516        &self,
13517        buffer: Model<Buffer>,
13518        completion_indices: Vec<usize>,
13519        completions: Rc<RefCell<Box<[Completion]>>>,
13520        cx: &mut ViewContext<Editor>,
13521    ) -> Task<Result<bool>> {
13522        self.update(cx, |project, cx| {
13523            project.resolve_completions(buffer, completion_indices, completions, cx)
13524        })
13525    }
13526
13527    fn apply_additional_edits_for_completion(
13528        &self,
13529        buffer: Model<Buffer>,
13530        completion: Completion,
13531        push_to_history: bool,
13532        cx: &mut ViewContext<Editor>,
13533    ) -> Task<Result<Option<language::Transaction>>> {
13534        self.update(cx, |project, cx| {
13535            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13536        })
13537    }
13538
13539    fn is_completion_trigger(
13540        &self,
13541        buffer: &Model<Buffer>,
13542        position: language::Anchor,
13543        text: &str,
13544        trigger_in_words: bool,
13545        cx: &mut ViewContext<Editor>,
13546    ) -> bool {
13547        let mut chars = text.chars();
13548        let char = if let Some(char) = chars.next() {
13549            char
13550        } else {
13551            return false;
13552        };
13553        if chars.next().is_some() {
13554            return false;
13555        }
13556
13557        let buffer = buffer.read(cx);
13558        let snapshot = buffer.snapshot();
13559        if !snapshot.settings_at(position, cx).show_completions_on_input {
13560            return false;
13561        }
13562        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13563        if trigger_in_words && classifier.is_word(char) {
13564            return true;
13565        }
13566
13567        buffer.completion_triggers().contains(text)
13568    }
13569}
13570
13571impl SemanticsProvider for Model<Project> {
13572    fn hover(
13573        &self,
13574        buffer: &Model<Buffer>,
13575        position: text::Anchor,
13576        cx: &mut AppContext,
13577    ) -> Option<Task<Vec<project::Hover>>> {
13578        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13579    }
13580
13581    fn document_highlights(
13582        &self,
13583        buffer: &Model<Buffer>,
13584        position: text::Anchor,
13585        cx: &mut AppContext,
13586    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13587        Some(self.update(cx, |project, cx| {
13588            project.document_highlights(buffer, position, cx)
13589        }))
13590    }
13591
13592    fn definitions(
13593        &self,
13594        buffer: &Model<Buffer>,
13595        position: text::Anchor,
13596        kind: GotoDefinitionKind,
13597        cx: &mut AppContext,
13598    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13599        Some(self.update(cx, |project, cx| match kind {
13600            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13601            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13602            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13603            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13604        }))
13605    }
13606
13607    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13608        // TODO: make this work for remote projects
13609        self.read(cx)
13610            .language_servers_for_local_buffer(buffer.read(cx), cx)
13611            .any(
13612                |(_, server)| match server.capabilities().inlay_hint_provider {
13613                    Some(lsp::OneOf::Left(enabled)) => enabled,
13614                    Some(lsp::OneOf::Right(_)) => true,
13615                    None => false,
13616                },
13617            )
13618    }
13619
13620    fn inlay_hints(
13621        &self,
13622        buffer_handle: Model<Buffer>,
13623        range: Range<text::Anchor>,
13624        cx: &mut AppContext,
13625    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13626        Some(self.update(cx, |project, cx| {
13627            project.inlay_hints(buffer_handle, range, cx)
13628        }))
13629    }
13630
13631    fn resolve_inlay_hint(
13632        &self,
13633        hint: InlayHint,
13634        buffer_handle: Model<Buffer>,
13635        server_id: LanguageServerId,
13636        cx: &mut AppContext,
13637    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13638        Some(self.update(cx, |project, cx| {
13639            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13640        }))
13641    }
13642
13643    fn range_for_rename(
13644        &self,
13645        buffer: &Model<Buffer>,
13646        position: text::Anchor,
13647        cx: &mut AppContext,
13648    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13649        Some(self.update(cx, |project, cx| {
13650            project.prepare_rename(buffer.clone(), position, cx)
13651        }))
13652    }
13653
13654    fn perform_rename(
13655        &self,
13656        buffer: &Model<Buffer>,
13657        position: text::Anchor,
13658        new_name: String,
13659        cx: &mut AppContext,
13660    ) -> Option<Task<Result<ProjectTransaction>>> {
13661        Some(self.update(cx, |project, cx| {
13662            project.perform_rename(buffer.clone(), position, new_name, cx)
13663        }))
13664    }
13665}
13666
13667fn inlay_hint_settings(
13668    location: Anchor,
13669    snapshot: &MultiBufferSnapshot,
13670    cx: &mut ViewContext<'_, Editor>,
13671) -> InlayHintSettings {
13672    let file = snapshot.file_at(location);
13673    let language = snapshot.language_at(location).map(|l| l.name());
13674    language_settings(language, file, cx).inlay_hints
13675}
13676
13677fn consume_contiguous_rows(
13678    contiguous_row_selections: &mut Vec<Selection<Point>>,
13679    selection: &Selection<Point>,
13680    display_map: &DisplaySnapshot,
13681    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13682) -> (MultiBufferRow, MultiBufferRow) {
13683    contiguous_row_selections.push(selection.clone());
13684    let start_row = MultiBufferRow(selection.start.row);
13685    let mut end_row = ending_row(selection, display_map);
13686
13687    while let Some(next_selection) = selections.peek() {
13688        if next_selection.start.row <= end_row.0 {
13689            end_row = ending_row(next_selection, display_map);
13690            contiguous_row_selections.push(selections.next().unwrap().clone());
13691        } else {
13692            break;
13693        }
13694    }
13695    (start_row, end_row)
13696}
13697
13698fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13699    if next_selection.end.column > 0 || next_selection.is_empty() {
13700        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13701    } else {
13702        MultiBufferRow(next_selection.end.row)
13703    }
13704}
13705
13706impl EditorSnapshot {
13707    pub fn remote_selections_in_range<'a>(
13708        &'a self,
13709        range: &'a Range<Anchor>,
13710        collaboration_hub: &dyn CollaborationHub,
13711        cx: &'a AppContext,
13712    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13713        let participant_names = collaboration_hub.user_names(cx);
13714        let participant_indices = collaboration_hub.user_participant_indices(cx);
13715        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13716        let collaborators_by_replica_id = collaborators_by_peer_id
13717            .iter()
13718            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13719            .collect::<HashMap<_, _>>();
13720        self.buffer_snapshot
13721            .selections_in_range(range, false)
13722            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13723                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13724                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13725                let user_name = participant_names.get(&collaborator.user_id).cloned();
13726                Some(RemoteSelection {
13727                    replica_id,
13728                    selection,
13729                    cursor_shape,
13730                    line_mode,
13731                    participant_index,
13732                    peer_id: collaborator.peer_id,
13733                    user_name,
13734                })
13735            })
13736    }
13737
13738    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13739        self.display_snapshot.buffer_snapshot.language_at(position)
13740    }
13741
13742    pub fn is_focused(&self) -> bool {
13743        self.is_focused
13744    }
13745
13746    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13747        self.placeholder_text.as_ref()
13748    }
13749
13750    pub fn scroll_position(&self) -> gpui::Point<f32> {
13751        self.scroll_anchor.scroll_position(&self.display_snapshot)
13752    }
13753
13754    fn gutter_dimensions(
13755        &self,
13756        font_id: FontId,
13757        font_size: Pixels,
13758        em_width: Pixels,
13759        em_advance: Pixels,
13760        max_line_number_width: Pixels,
13761        cx: &AppContext,
13762    ) -> GutterDimensions {
13763        if !self.show_gutter {
13764            return GutterDimensions::default();
13765        }
13766        let descent = cx.text_system().descent(font_id, font_size);
13767
13768        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13769            matches!(
13770                ProjectSettings::get_global(cx).git.git_gutter,
13771                Some(GitGutterSetting::TrackedFiles)
13772            )
13773        });
13774        let gutter_settings = EditorSettings::get_global(cx).gutter;
13775        let show_line_numbers = self
13776            .show_line_numbers
13777            .unwrap_or(gutter_settings.line_numbers);
13778        let line_gutter_width = if show_line_numbers {
13779            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13780            let min_width_for_number_on_gutter = em_advance * 4.0;
13781            max_line_number_width.max(min_width_for_number_on_gutter)
13782        } else {
13783            0.0.into()
13784        };
13785
13786        let show_code_actions = self
13787            .show_code_actions
13788            .unwrap_or(gutter_settings.code_actions);
13789
13790        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13791
13792        let git_blame_entries_width =
13793            self.git_blame_gutter_max_author_length
13794                .map(|max_author_length| {
13795                    // Length of the author name, but also space for the commit hash,
13796                    // the spacing and the timestamp.
13797                    let max_char_count = max_author_length
13798                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13799                        + 7 // length of commit sha
13800                        + 14 // length of max relative timestamp ("60 minutes ago")
13801                        + 4; // gaps and margins
13802
13803                    em_advance * max_char_count
13804                });
13805
13806        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13807        left_padding += if show_code_actions || show_runnables {
13808            em_width * 3.0
13809        } else if show_git_gutter && show_line_numbers {
13810            em_width * 2.0
13811        } else if show_git_gutter || show_line_numbers {
13812            em_width
13813        } else {
13814            px(0.)
13815        };
13816
13817        let right_padding = if gutter_settings.folds && show_line_numbers {
13818            em_width * 4.0
13819        } else if gutter_settings.folds {
13820            em_width * 3.0
13821        } else if show_line_numbers {
13822            em_width
13823        } else {
13824            px(0.)
13825        };
13826
13827        GutterDimensions {
13828            left_padding,
13829            right_padding,
13830            width: line_gutter_width + left_padding + right_padding,
13831            margin: -descent,
13832            git_blame_entries_width,
13833        }
13834    }
13835
13836    pub fn render_crease_toggle(
13837        &self,
13838        buffer_row: MultiBufferRow,
13839        row_contains_cursor: bool,
13840        editor: View<Editor>,
13841        cx: &mut WindowContext,
13842    ) -> Option<AnyElement> {
13843        let folded = self.is_line_folded(buffer_row);
13844        let mut is_foldable = false;
13845
13846        if let Some(crease) = self
13847            .crease_snapshot
13848            .query_row(buffer_row, &self.buffer_snapshot)
13849        {
13850            is_foldable = true;
13851            match crease {
13852                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13853                    if let Some(render_toggle) = render_toggle {
13854                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13855                            if folded {
13856                                editor.update(cx, |editor, cx| {
13857                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13858                                });
13859                            } else {
13860                                editor.update(cx, |editor, cx| {
13861                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13862                                });
13863                            }
13864                        });
13865                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13866                    }
13867                }
13868            }
13869        }
13870
13871        is_foldable |= self.starts_indent(buffer_row);
13872
13873        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13874            Some(
13875                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13876                    .toggle_state(folded)
13877                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13878                        if folded {
13879                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13880                        } else {
13881                            this.fold_at(&FoldAt { buffer_row }, cx);
13882                        }
13883                    }))
13884                    .into_any_element(),
13885            )
13886        } else {
13887            None
13888        }
13889    }
13890
13891    pub fn render_crease_trailer(
13892        &self,
13893        buffer_row: MultiBufferRow,
13894        cx: &mut WindowContext,
13895    ) -> Option<AnyElement> {
13896        let folded = self.is_line_folded(buffer_row);
13897        if let Crease::Inline { render_trailer, .. } = self
13898            .crease_snapshot
13899            .query_row(buffer_row, &self.buffer_snapshot)?
13900        {
13901            let render_trailer = render_trailer.as_ref()?;
13902            Some(render_trailer(buffer_row, folded, cx))
13903        } else {
13904            None
13905        }
13906    }
13907}
13908
13909impl Deref for EditorSnapshot {
13910    type Target = DisplaySnapshot;
13911
13912    fn deref(&self) -> &Self::Target {
13913        &self.display_snapshot
13914    }
13915}
13916
13917#[derive(Clone, Debug, PartialEq, Eq)]
13918pub enum EditorEvent {
13919    InputIgnored {
13920        text: Arc<str>,
13921    },
13922    InputHandled {
13923        utf16_range_to_replace: Option<Range<isize>>,
13924        text: Arc<str>,
13925    },
13926    ExcerptsAdded {
13927        buffer: Model<Buffer>,
13928        predecessor: ExcerptId,
13929        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13930    },
13931    ExcerptsRemoved {
13932        ids: Vec<ExcerptId>,
13933    },
13934    BufferFoldToggled {
13935        ids: Vec<ExcerptId>,
13936        folded: bool,
13937    },
13938    ExcerptsEdited {
13939        ids: Vec<ExcerptId>,
13940    },
13941    ExcerptsExpanded {
13942        ids: Vec<ExcerptId>,
13943    },
13944    BufferEdited,
13945    Edited {
13946        transaction_id: clock::Lamport,
13947    },
13948    Reparsed(BufferId),
13949    Focused,
13950    FocusedIn,
13951    Blurred,
13952    DirtyChanged,
13953    Saved,
13954    TitleChanged,
13955    DiffBaseChanged,
13956    SelectionsChanged {
13957        local: bool,
13958    },
13959    ScrollPositionChanged {
13960        local: bool,
13961        autoscroll: bool,
13962    },
13963    Closed,
13964    TransactionUndone {
13965        transaction_id: clock::Lamport,
13966    },
13967    TransactionBegun {
13968        transaction_id: clock::Lamport,
13969    },
13970    Reloaded,
13971    CursorShapeChanged,
13972}
13973
13974impl EventEmitter<EditorEvent> for Editor {}
13975
13976impl FocusableView for Editor {
13977    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13978        self.focus_handle.clone()
13979    }
13980}
13981
13982impl Render for Editor {
13983    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13984        let settings = ThemeSettings::get_global(cx);
13985
13986        let mut text_style = match self.mode {
13987            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13988                color: cx.theme().colors().editor_foreground,
13989                font_family: settings.ui_font.family.clone(),
13990                font_features: settings.ui_font.features.clone(),
13991                font_fallbacks: settings.ui_font.fallbacks.clone(),
13992                font_size: rems(0.875).into(),
13993                font_weight: settings.ui_font.weight,
13994                line_height: relative(settings.buffer_line_height.value()),
13995                ..Default::default()
13996            },
13997            EditorMode::Full => TextStyle {
13998                color: cx.theme().colors().editor_foreground,
13999                font_family: settings.buffer_font.family.clone(),
14000                font_features: settings.buffer_font.features.clone(),
14001                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14002                font_size: settings.buffer_font_size(cx).into(),
14003                font_weight: settings.buffer_font.weight,
14004                line_height: relative(settings.buffer_line_height.value()),
14005                ..Default::default()
14006            },
14007        };
14008        if let Some(text_style_refinement) = &self.text_style_refinement {
14009            text_style.refine(text_style_refinement)
14010        }
14011
14012        let background = match self.mode {
14013            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14014            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14015            EditorMode::Full => cx.theme().colors().editor_background,
14016        };
14017
14018        EditorElement::new(
14019            cx.view(),
14020            EditorStyle {
14021                background,
14022                local_player: cx.theme().players().local(),
14023                text: text_style,
14024                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14025                syntax: cx.theme().syntax().clone(),
14026                status: cx.theme().status().clone(),
14027                inlay_hints_style: make_inlay_hints_style(cx),
14028                inline_completion_styles: make_suggestion_styles(cx),
14029                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14030            },
14031        )
14032    }
14033}
14034
14035impl ViewInputHandler for Editor {
14036    fn text_for_range(
14037        &mut self,
14038        range_utf16: Range<usize>,
14039        adjusted_range: &mut Option<Range<usize>>,
14040        cx: &mut ViewContext<Self>,
14041    ) -> Option<String> {
14042        let snapshot = self.buffer.read(cx).read(cx);
14043        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14044        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14045        if (start.0..end.0) != range_utf16 {
14046            adjusted_range.replace(start.0..end.0);
14047        }
14048        Some(snapshot.text_for_range(start..end).collect())
14049    }
14050
14051    fn selected_text_range(
14052        &mut self,
14053        ignore_disabled_input: bool,
14054        cx: &mut ViewContext<Self>,
14055    ) -> Option<UTF16Selection> {
14056        // Prevent the IME menu from appearing when holding down an alphabetic key
14057        // while input is disabled.
14058        if !ignore_disabled_input && !self.input_enabled {
14059            return None;
14060        }
14061
14062        let selection = self.selections.newest::<OffsetUtf16>(cx);
14063        let range = selection.range();
14064
14065        Some(UTF16Selection {
14066            range: range.start.0..range.end.0,
14067            reversed: selection.reversed,
14068        })
14069    }
14070
14071    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14072        let snapshot = self.buffer.read(cx).read(cx);
14073        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14074        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14075    }
14076
14077    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14078        self.clear_highlights::<InputComposition>(cx);
14079        self.ime_transaction.take();
14080    }
14081
14082    fn replace_text_in_range(
14083        &mut self,
14084        range_utf16: Option<Range<usize>>,
14085        text: &str,
14086        cx: &mut ViewContext<Self>,
14087    ) {
14088        if !self.input_enabled {
14089            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14090            return;
14091        }
14092
14093        self.transact(cx, |this, cx| {
14094            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14095                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14096                Some(this.selection_replacement_ranges(range_utf16, cx))
14097            } else {
14098                this.marked_text_ranges(cx)
14099            };
14100
14101            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14102                let newest_selection_id = this.selections.newest_anchor().id;
14103                this.selections
14104                    .all::<OffsetUtf16>(cx)
14105                    .iter()
14106                    .zip(ranges_to_replace.iter())
14107                    .find_map(|(selection, range)| {
14108                        if selection.id == newest_selection_id {
14109                            Some(
14110                                (range.start.0 as isize - selection.head().0 as isize)
14111                                    ..(range.end.0 as isize - selection.head().0 as isize),
14112                            )
14113                        } else {
14114                            None
14115                        }
14116                    })
14117            });
14118
14119            cx.emit(EditorEvent::InputHandled {
14120                utf16_range_to_replace: range_to_replace,
14121                text: text.into(),
14122            });
14123
14124            if let Some(new_selected_ranges) = new_selected_ranges {
14125                this.change_selections(None, cx, |selections| {
14126                    selections.select_ranges(new_selected_ranges)
14127                });
14128                this.backspace(&Default::default(), cx);
14129            }
14130
14131            this.handle_input(text, cx);
14132        });
14133
14134        if let Some(transaction) = self.ime_transaction {
14135            self.buffer.update(cx, |buffer, cx| {
14136                buffer.group_until_transaction(transaction, cx);
14137            });
14138        }
14139
14140        self.unmark_text(cx);
14141    }
14142
14143    fn replace_and_mark_text_in_range(
14144        &mut self,
14145        range_utf16: Option<Range<usize>>,
14146        text: &str,
14147        new_selected_range_utf16: Option<Range<usize>>,
14148        cx: &mut ViewContext<Self>,
14149    ) {
14150        if !self.input_enabled {
14151            return;
14152        }
14153
14154        let transaction = self.transact(cx, |this, cx| {
14155            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14156                let snapshot = this.buffer.read(cx).read(cx);
14157                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14158                    for marked_range in &mut marked_ranges {
14159                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14160                        marked_range.start.0 += relative_range_utf16.start;
14161                        marked_range.start =
14162                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14163                        marked_range.end =
14164                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14165                    }
14166                }
14167                Some(marked_ranges)
14168            } else if let Some(range_utf16) = range_utf16 {
14169                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14170                Some(this.selection_replacement_ranges(range_utf16, cx))
14171            } else {
14172                None
14173            };
14174
14175            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14176                let newest_selection_id = this.selections.newest_anchor().id;
14177                this.selections
14178                    .all::<OffsetUtf16>(cx)
14179                    .iter()
14180                    .zip(ranges_to_replace.iter())
14181                    .find_map(|(selection, range)| {
14182                        if selection.id == newest_selection_id {
14183                            Some(
14184                                (range.start.0 as isize - selection.head().0 as isize)
14185                                    ..(range.end.0 as isize - selection.head().0 as isize),
14186                            )
14187                        } else {
14188                            None
14189                        }
14190                    })
14191            });
14192
14193            cx.emit(EditorEvent::InputHandled {
14194                utf16_range_to_replace: range_to_replace,
14195                text: text.into(),
14196            });
14197
14198            if let Some(ranges) = ranges_to_replace {
14199                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14200            }
14201
14202            let marked_ranges = {
14203                let snapshot = this.buffer.read(cx).read(cx);
14204                this.selections
14205                    .disjoint_anchors()
14206                    .iter()
14207                    .map(|selection| {
14208                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14209                    })
14210                    .collect::<Vec<_>>()
14211            };
14212
14213            if text.is_empty() {
14214                this.unmark_text(cx);
14215            } else {
14216                this.highlight_text::<InputComposition>(
14217                    marked_ranges.clone(),
14218                    HighlightStyle {
14219                        underline: Some(UnderlineStyle {
14220                            thickness: px(1.),
14221                            color: None,
14222                            wavy: false,
14223                        }),
14224                        ..Default::default()
14225                    },
14226                    cx,
14227                );
14228            }
14229
14230            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14231            let use_autoclose = this.use_autoclose;
14232            let use_auto_surround = this.use_auto_surround;
14233            this.set_use_autoclose(false);
14234            this.set_use_auto_surround(false);
14235            this.handle_input(text, cx);
14236            this.set_use_autoclose(use_autoclose);
14237            this.set_use_auto_surround(use_auto_surround);
14238
14239            if let Some(new_selected_range) = new_selected_range_utf16 {
14240                let snapshot = this.buffer.read(cx).read(cx);
14241                let new_selected_ranges = marked_ranges
14242                    .into_iter()
14243                    .map(|marked_range| {
14244                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14245                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14246                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14247                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14248                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14249                    })
14250                    .collect::<Vec<_>>();
14251
14252                drop(snapshot);
14253                this.change_selections(None, cx, |selections| {
14254                    selections.select_ranges(new_selected_ranges)
14255                });
14256            }
14257        });
14258
14259        self.ime_transaction = self.ime_transaction.or(transaction);
14260        if let Some(transaction) = self.ime_transaction {
14261            self.buffer.update(cx, |buffer, cx| {
14262                buffer.group_until_transaction(transaction, cx);
14263            });
14264        }
14265
14266        if self.text_highlights::<InputComposition>(cx).is_none() {
14267            self.ime_transaction.take();
14268        }
14269    }
14270
14271    fn bounds_for_range(
14272        &mut self,
14273        range_utf16: Range<usize>,
14274        element_bounds: gpui::Bounds<Pixels>,
14275        cx: &mut ViewContext<Self>,
14276    ) -> Option<gpui::Bounds<Pixels>> {
14277        let text_layout_details = self.text_layout_details(cx);
14278        let gpui::Point {
14279            x: em_width,
14280            y: line_height,
14281        } = self.character_size(cx);
14282
14283        let snapshot = self.snapshot(cx);
14284        let scroll_position = snapshot.scroll_position();
14285        let scroll_left = scroll_position.x * em_width;
14286
14287        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14288        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14289            + self.gutter_dimensions.width
14290            + self.gutter_dimensions.margin;
14291        let y = line_height * (start.row().as_f32() - scroll_position.y);
14292
14293        Some(Bounds {
14294            origin: element_bounds.origin + point(x, y),
14295            size: size(em_width, line_height),
14296        })
14297    }
14298}
14299
14300trait SelectionExt {
14301    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14302    fn spanned_rows(
14303        &self,
14304        include_end_if_at_line_start: bool,
14305        map: &DisplaySnapshot,
14306    ) -> Range<MultiBufferRow>;
14307}
14308
14309impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14310    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14311        let start = self
14312            .start
14313            .to_point(&map.buffer_snapshot)
14314            .to_display_point(map);
14315        let end = self
14316            .end
14317            .to_point(&map.buffer_snapshot)
14318            .to_display_point(map);
14319        if self.reversed {
14320            end..start
14321        } else {
14322            start..end
14323        }
14324    }
14325
14326    fn spanned_rows(
14327        &self,
14328        include_end_if_at_line_start: bool,
14329        map: &DisplaySnapshot,
14330    ) -> Range<MultiBufferRow> {
14331        let start = self.start.to_point(&map.buffer_snapshot);
14332        let mut end = self.end.to_point(&map.buffer_snapshot);
14333        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14334            end.row -= 1;
14335        }
14336
14337        let buffer_start = map.prev_line_boundary(start).0;
14338        let buffer_end = map.next_line_boundary(end).0;
14339        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14340    }
14341}
14342
14343impl<T: InvalidationRegion> InvalidationStack<T> {
14344    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14345    where
14346        S: Clone + ToOffset,
14347    {
14348        while let Some(region) = self.last() {
14349            let all_selections_inside_invalidation_ranges =
14350                if selections.len() == region.ranges().len() {
14351                    selections
14352                        .iter()
14353                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14354                        .all(|(selection, invalidation_range)| {
14355                            let head = selection.head().to_offset(buffer);
14356                            invalidation_range.start <= head && invalidation_range.end >= head
14357                        })
14358                } else {
14359                    false
14360                };
14361
14362            if all_selections_inside_invalidation_ranges {
14363                break;
14364            } else {
14365                self.pop();
14366            }
14367        }
14368    }
14369}
14370
14371impl<T> Default for InvalidationStack<T> {
14372    fn default() -> Self {
14373        Self(Default::default())
14374    }
14375}
14376
14377impl<T> Deref for InvalidationStack<T> {
14378    type Target = Vec<T>;
14379
14380    fn deref(&self) -> &Self::Target {
14381        &self.0
14382    }
14383}
14384
14385impl<T> DerefMut for InvalidationStack<T> {
14386    fn deref_mut(&mut self) -> &mut Self::Target {
14387        &mut self.0
14388    }
14389}
14390
14391impl InvalidationRegion for SnippetState {
14392    fn ranges(&self) -> &[Range<Anchor>] {
14393        &self.ranges[self.active_index]
14394    }
14395}
14396
14397pub fn diagnostic_block_renderer(
14398    diagnostic: Diagnostic,
14399    max_message_rows: Option<u8>,
14400    allow_closing: bool,
14401    _is_valid: bool,
14402) -> RenderBlock {
14403    let (text_without_backticks, code_ranges) =
14404        highlight_diagnostic_message(&diagnostic, max_message_rows);
14405
14406    Arc::new(move |cx: &mut BlockContext| {
14407        let group_id: SharedString = cx.block_id.to_string().into();
14408
14409        let mut text_style = cx.text_style().clone();
14410        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14411        let theme_settings = ThemeSettings::get_global(cx);
14412        text_style.font_family = theme_settings.buffer_font.family.clone();
14413        text_style.font_style = theme_settings.buffer_font.style;
14414        text_style.font_features = theme_settings.buffer_font.features.clone();
14415        text_style.font_weight = theme_settings.buffer_font.weight;
14416
14417        let multi_line_diagnostic = diagnostic.message.contains('\n');
14418
14419        let buttons = |diagnostic: &Diagnostic| {
14420            if multi_line_diagnostic {
14421                v_flex()
14422            } else {
14423                h_flex()
14424            }
14425            .when(allow_closing, |div| {
14426                div.children(diagnostic.is_primary.then(|| {
14427                    IconButton::new("close-block", IconName::XCircle)
14428                        .icon_color(Color::Muted)
14429                        .size(ButtonSize::Compact)
14430                        .style(ButtonStyle::Transparent)
14431                        .visible_on_hover(group_id.clone())
14432                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14433                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14434                }))
14435            })
14436            .child(
14437                IconButton::new("copy-block", IconName::Copy)
14438                    .icon_color(Color::Muted)
14439                    .size(ButtonSize::Compact)
14440                    .style(ButtonStyle::Transparent)
14441                    .visible_on_hover(group_id.clone())
14442                    .on_click({
14443                        let message = diagnostic.message.clone();
14444                        move |_click, cx| {
14445                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14446                        }
14447                    })
14448                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14449            )
14450        };
14451
14452        let icon_size = buttons(&diagnostic)
14453            .into_any_element()
14454            .layout_as_root(AvailableSpace::min_size(), cx);
14455
14456        h_flex()
14457            .id(cx.block_id)
14458            .group(group_id.clone())
14459            .relative()
14460            .size_full()
14461            .block_mouse_down()
14462            .pl(cx.gutter_dimensions.width)
14463            .w(cx.max_width - cx.gutter_dimensions.full_width())
14464            .child(
14465                div()
14466                    .flex()
14467                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14468                    .flex_shrink(),
14469            )
14470            .child(buttons(&diagnostic))
14471            .child(div().flex().flex_shrink_0().child(
14472                StyledText::new(text_without_backticks.clone()).with_highlights(
14473                    &text_style,
14474                    code_ranges.iter().map(|range| {
14475                        (
14476                            range.clone(),
14477                            HighlightStyle {
14478                                font_weight: Some(FontWeight::BOLD),
14479                                ..Default::default()
14480                            },
14481                        )
14482                    }),
14483                ),
14484            ))
14485            .into_any_element()
14486    })
14487}
14488
14489pub fn highlight_diagnostic_message(
14490    diagnostic: &Diagnostic,
14491    mut max_message_rows: Option<u8>,
14492) -> (SharedString, Vec<Range<usize>>) {
14493    let mut text_without_backticks = String::new();
14494    let mut code_ranges = Vec::new();
14495
14496    if let Some(source) = &diagnostic.source {
14497        text_without_backticks.push_str(source);
14498        code_ranges.push(0..source.len());
14499        text_without_backticks.push_str(": ");
14500    }
14501
14502    let mut prev_offset = 0;
14503    let mut in_code_block = false;
14504    let has_row_limit = max_message_rows.is_some();
14505    let mut newline_indices = diagnostic
14506        .message
14507        .match_indices('\n')
14508        .filter(|_| has_row_limit)
14509        .map(|(ix, _)| ix)
14510        .fuse()
14511        .peekable();
14512
14513    for (quote_ix, _) in diagnostic
14514        .message
14515        .match_indices('`')
14516        .chain([(diagnostic.message.len(), "")])
14517    {
14518        let mut first_newline_ix = None;
14519        let mut last_newline_ix = None;
14520        while let Some(newline_ix) = newline_indices.peek() {
14521            if *newline_ix < quote_ix {
14522                if first_newline_ix.is_none() {
14523                    first_newline_ix = Some(*newline_ix);
14524                }
14525                last_newline_ix = Some(*newline_ix);
14526
14527                if let Some(rows_left) = &mut max_message_rows {
14528                    if *rows_left == 0 {
14529                        break;
14530                    } else {
14531                        *rows_left -= 1;
14532                    }
14533                }
14534                let _ = newline_indices.next();
14535            } else {
14536                break;
14537            }
14538        }
14539        let prev_len = text_without_backticks.len();
14540        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14541        text_without_backticks.push_str(new_text);
14542        if in_code_block {
14543            code_ranges.push(prev_len..text_without_backticks.len());
14544        }
14545        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14546        in_code_block = !in_code_block;
14547        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14548            text_without_backticks.push_str("...");
14549            break;
14550        }
14551    }
14552
14553    (text_without_backticks.into(), code_ranges)
14554}
14555
14556fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14557    match severity {
14558        DiagnosticSeverity::ERROR => colors.error,
14559        DiagnosticSeverity::WARNING => colors.warning,
14560        DiagnosticSeverity::INFORMATION => colors.info,
14561        DiagnosticSeverity::HINT => colors.info,
14562        _ => colors.ignored,
14563    }
14564}
14565
14566pub fn styled_runs_for_code_label<'a>(
14567    label: &'a CodeLabel,
14568    syntax_theme: &'a theme::SyntaxTheme,
14569) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14570    let fade_out = HighlightStyle {
14571        fade_out: Some(0.35),
14572        ..Default::default()
14573    };
14574
14575    let mut prev_end = label.filter_range.end;
14576    label
14577        .runs
14578        .iter()
14579        .enumerate()
14580        .flat_map(move |(ix, (range, highlight_id))| {
14581            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14582                style
14583            } else {
14584                return Default::default();
14585            };
14586            let mut muted_style = style;
14587            muted_style.highlight(fade_out);
14588
14589            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14590            if range.start >= label.filter_range.end {
14591                if range.start > prev_end {
14592                    runs.push((prev_end..range.start, fade_out));
14593                }
14594                runs.push((range.clone(), muted_style));
14595            } else if range.end <= label.filter_range.end {
14596                runs.push((range.clone(), style));
14597            } else {
14598                runs.push((range.start..label.filter_range.end, style));
14599                runs.push((label.filter_range.end..range.end, muted_style));
14600            }
14601            prev_end = cmp::max(prev_end, range.end);
14602
14603            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14604                runs.push((prev_end..label.text.len(), fade_out));
14605            }
14606
14607            runs
14608        })
14609}
14610
14611pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14612    let mut prev_index = 0;
14613    let mut prev_codepoint: Option<char> = None;
14614    text.char_indices()
14615        .chain([(text.len(), '\0')])
14616        .filter_map(move |(index, codepoint)| {
14617            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14618            let is_boundary = index == text.len()
14619                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14620                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14621            if is_boundary {
14622                let chunk = &text[prev_index..index];
14623                prev_index = index;
14624                Some(chunk)
14625            } else {
14626                None
14627            }
14628        })
14629}
14630
14631pub trait RangeToAnchorExt: Sized {
14632    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14633
14634    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14635        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14636        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14637    }
14638}
14639
14640impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14641    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14642        let start_offset = self.start.to_offset(snapshot);
14643        let end_offset = self.end.to_offset(snapshot);
14644        if start_offset == end_offset {
14645            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14646        } else {
14647            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14648        }
14649    }
14650}
14651
14652pub trait RowExt {
14653    fn as_f32(&self) -> f32;
14654
14655    fn next_row(&self) -> Self;
14656
14657    fn previous_row(&self) -> Self;
14658
14659    fn minus(&self, other: Self) -> u32;
14660}
14661
14662impl RowExt for DisplayRow {
14663    fn as_f32(&self) -> f32 {
14664        self.0 as f32
14665    }
14666
14667    fn next_row(&self) -> Self {
14668        Self(self.0 + 1)
14669    }
14670
14671    fn previous_row(&self) -> Self {
14672        Self(self.0.saturating_sub(1))
14673    }
14674
14675    fn minus(&self, other: Self) -> u32 {
14676        self.0 - other.0
14677    }
14678}
14679
14680impl RowExt for MultiBufferRow {
14681    fn as_f32(&self) -> f32 {
14682        self.0 as f32
14683    }
14684
14685    fn next_row(&self) -> Self {
14686        Self(self.0 + 1)
14687    }
14688
14689    fn previous_row(&self) -> Self {
14690        Self(self.0.saturating_sub(1))
14691    }
14692
14693    fn minus(&self, other: Self) -> u32 {
14694        self.0 - other.0
14695    }
14696}
14697
14698trait RowRangeExt {
14699    type Row;
14700
14701    fn len(&self) -> usize;
14702
14703    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14704}
14705
14706impl RowRangeExt for Range<MultiBufferRow> {
14707    type Row = MultiBufferRow;
14708
14709    fn len(&self) -> usize {
14710        (self.end.0 - self.start.0) as usize
14711    }
14712
14713    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14714        (self.start.0..self.end.0).map(MultiBufferRow)
14715    }
14716}
14717
14718impl RowRangeExt for Range<DisplayRow> {
14719    type Row = DisplayRow;
14720
14721    fn len(&self) -> usize {
14722        (self.end.0 - self.start.0) as usize
14723    }
14724
14725    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14726        (self.start.0..self.end.0).map(DisplayRow)
14727    }
14728}
14729
14730fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14731    if hunk.diff_base_byte_range.is_empty() {
14732        DiffHunkStatus::Added
14733    } else if hunk.row_range.is_empty() {
14734        DiffHunkStatus::Removed
14735    } else {
14736        DiffHunkStatus::Modified
14737    }
14738}
14739
14740/// If select range has more than one line, we
14741/// just point the cursor to range.start.
14742fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14743    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14744        range
14745    } else {
14746        range.start..range.start
14747    }
14748}
14749
14750pub struct KillRing(ClipboardItem);
14751impl Global for KillRing {}
14752
14753const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);