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 parking_lot::RwLock;
  131use project::{
  132    lsp_store::{FormatTarget, FormatTrigger},
  133    project_settings::{GitGutterSetting, ProjectSettings},
  134    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  135    Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  136};
  137use rand::prelude::*;
  138use rpc::{proto::*, ErrorExt};
  139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  140use selections_collection::{
  141    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  142};
  143use serde::{Deserialize, Serialize};
  144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  145use smallvec::SmallVec;
  146use snippet::Snippet;
  147use std::{
  148    any::TypeId,
  149    borrow::Cow,
  150    cell::RefCell,
  151    cmp::{self, Ordering, Reverse},
  152    mem,
  153    num::NonZeroU32,
  154    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  155    path::{Path, PathBuf},
  156    rc::Rc,
  157    sync::Arc,
  158    time::{Duration, Instant},
  159};
  160pub use sum_tree::Bias;
  161use sum_tree::TreeMap;
  162use text::{BufferId, OffsetUtf16, Rope};
  163use theme::{
  164    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  165    ThemeColors, ThemeSettings,
  166};
  167use ui::{
  168    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  169    PopoverMenuHandle, Tooltip,
  170};
  171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  172use workspace::item::{ItemHandle, PreviewTabsSettings};
  173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  174use workspace::{
  175    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  176};
  177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  178
  179use crate::hover_links::find_url;
  180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  181
  182pub const FILE_HEADER_HEIGHT: u32 = 2;
  183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  187const MAX_LINE_LEN: usize = 1024;
  188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  191#[doc(hidden)]
  192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  193#[doc(hidden)]
  194pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  195
  196pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  197pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  198
  199pub fn render_parsed_markdown(
  200    element_id: impl Into<ElementId>,
  201    parsed: &language::ParsedMarkdown,
  202    editor_style: &EditorStyle,
  203    workspace: Option<WeakView<Workspace>>,
  204    cx: &mut WindowContext,
  205) -> InteractiveText {
  206    let code_span_background_color = cx
  207        .theme()
  208        .colors()
  209        .editor_document_highlight_read_background;
  210
  211    let highlights = gpui::combine_highlights(
  212        parsed.highlights.iter().filter_map(|(range, highlight)| {
  213            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  214            Some((range.clone(), highlight))
  215        }),
  216        parsed
  217            .regions
  218            .iter()
  219            .zip(&parsed.region_ranges)
  220            .filter_map(|(region, range)| {
  221                if region.code {
  222                    Some((
  223                        range.clone(),
  224                        HighlightStyle {
  225                            background_color: Some(code_span_background_color),
  226                            ..Default::default()
  227                        },
  228                    ))
  229                } else {
  230                    None
  231                }
  232            }),
  233    );
  234
  235    let mut links = Vec::new();
  236    let mut link_ranges = Vec::new();
  237    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  238        if let Some(link) = region.link.clone() {
  239            links.push(link);
  240            link_ranges.push(range.clone());
  241        }
  242    }
  243
  244    InteractiveText::new(
  245        element_id,
  246        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  247    )
  248    .on_click(link_ranges, move |clicked_range_ix, cx| {
  249        match &links[clicked_range_ix] {
  250            markdown::Link::Web { url } => cx.open_url(url),
  251            markdown::Link::Path { path } => {
  252                if let Some(workspace) = &workspace {
  253                    _ = workspace.update(cx, |workspace, cx| {
  254                        workspace.open_abs_path(path.clone(), false, cx).detach();
  255                    });
  256                }
  257            }
  258        }
  259    })
  260}
  261
  262#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  263pub(crate) enum InlayId {
  264    Suggestion(usize),
  265    Hint(usize),
  266}
  267
  268impl InlayId {
  269    fn id(&self) -> usize {
  270        match self {
  271            Self::Suggestion(id) => *id,
  272            Self::Hint(id) => *id,
  273        }
  274    }
  275}
  276
  277enum DiffRowHighlight {}
  278enum DocumentHighlightRead {}
  279enum DocumentHighlightWrite {}
  280enum InputComposition {}
  281
  282#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  283pub enum Navigated {
  284    Yes,
  285    No,
  286}
  287
  288impl Navigated {
  289    pub fn from_bool(yes: bool) -> Navigated {
  290        if yes {
  291            Navigated::Yes
  292        } else {
  293            Navigated::No
  294        }
  295    }
  296}
  297
  298pub fn init_settings(cx: &mut AppContext) {
  299    EditorSettings::register(cx);
  300}
  301
  302pub fn init(cx: &mut AppContext) {
  303    init_settings(cx);
  304
  305    workspace::register_project_item::<Editor>(cx);
  306    workspace::FollowableViewRegistry::register::<Editor>(cx);
  307    workspace::register_serializable_item::<Editor>(cx);
  308
  309    cx.observe_new_views(
  310        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  311            workspace.register_action(Editor::new_file);
  312            workspace.register_action(Editor::new_file_vertical);
  313            workspace.register_action(Editor::new_file_horizontal);
  314        },
  315    )
  316    .detach();
  317
  318    cx.on_action(move |_: &workspace::NewFile, cx| {
  319        let app_state = workspace::AppState::global(cx);
  320        if let Some(app_state) = app_state.upgrade() {
  321            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  322                Editor::new_file(workspace, &Default::default(), cx)
  323            })
  324            .detach();
  325        }
  326    });
  327    cx.on_action(move |_: &workspace::NewWindow, cx| {
  328        let app_state = workspace::AppState::global(cx);
  329        if let Some(app_state) = app_state.upgrade() {
  330            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  331                Editor::new_file(workspace, &Default::default(), cx)
  332            })
  333            .detach();
  334        }
  335    });
  336    git::project_diff::init(cx);
  337}
  338
  339pub struct SearchWithinRange;
  340
  341trait InvalidationRegion {
  342    fn ranges(&self) -> &[Range<Anchor>];
  343}
  344
  345#[derive(Clone, Debug, PartialEq)]
  346pub enum SelectPhase {
  347    Begin {
  348        position: DisplayPoint,
  349        add: bool,
  350        click_count: usize,
  351    },
  352    BeginColumnar {
  353        position: DisplayPoint,
  354        reset: bool,
  355        goal_column: u32,
  356    },
  357    Extend {
  358        position: DisplayPoint,
  359        click_count: usize,
  360    },
  361    Update {
  362        position: DisplayPoint,
  363        goal_column: u32,
  364        scroll_delta: gpui::Point<f32>,
  365    },
  366    End,
  367}
  368
  369#[derive(Clone, Debug)]
  370pub enum SelectMode {
  371    Character,
  372    Word(Range<Anchor>),
  373    Line(Range<Anchor>),
  374    All,
  375}
  376
  377#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  378pub enum EditorMode {
  379    SingleLine { auto_width: bool },
  380    AutoHeight { max_lines: usize },
  381    Full,
  382}
  383
  384#[derive(Copy, Clone, Debug)]
  385pub enum SoftWrap {
  386    /// Prefer not to wrap at all.
  387    ///
  388    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  389    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  390    GitDiff,
  391    /// Prefer a single line generally, unless an overly long line is encountered.
  392    None,
  393    /// Soft wrap lines that exceed the editor width.
  394    EditorWidth,
  395    /// Soft wrap lines at the preferred line length.
  396    Column(u32),
  397    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  398    Bounded(u32),
  399}
  400
  401#[derive(Clone)]
  402pub struct EditorStyle {
  403    pub background: Hsla,
  404    pub local_player: PlayerColor,
  405    pub text: TextStyle,
  406    pub scrollbar_width: Pixels,
  407    pub syntax: Arc<SyntaxTheme>,
  408    pub status: StatusColors,
  409    pub inlay_hints_style: HighlightStyle,
  410    pub suggestions_style: HighlightStyle,
  411    pub unnecessary_code_fade: f32,
  412}
  413
  414impl Default for EditorStyle {
  415    fn default() -> Self {
  416        Self {
  417            background: Hsla::default(),
  418            local_player: PlayerColor::default(),
  419            text: TextStyle::default(),
  420            scrollbar_width: Pixels::default(),
  421            syntax: Default::default(),
  422            // HACK: Status colors don't have a real default.
  423            // We should look into removing the status colors from the editor
  424            // style and retrieve them directly from the theme.
  425            status: StatusColors::dark(),
  426            inlay_hints_style: HighlightStyle::default(),
  427            suggestions_style: HighlightStyle::default(),
  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
  445type CompletionId = usize;
  446
  447enum InlineCompletion {
  448    Edit(Vec<(Range<Anchor>, String)>),
  449    Move(Anchor),
  450}
  451
  452struct InlineCompletionState {
  453    inlay_ids: Vec<InlayId>,
  454    completion: InlineCompletion,
  455    invalidation_range: Range<Anchor>,
  456}
  457
  458enum InlineCompletionHighlight {}
  459
  460#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  461struct EditorActionId(usize);
  462
  463impl EditorActionId {
  464    pub fn post_inc(&mut self) -> Self {
  465        let answer = self.0;
  466
  467        *self = Self(answer + 1);
  468
  469        Self(answer)
  470    }
  471}
  472
  473// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  474// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  475
  476type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  477type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  478
  479#[derive(Default)]
  480struct ScrollbarMarkerState {
  481    scrollbar_size: Size<Pixels>,
  482    dirty: bool,
  483    markers: Arc<[PaintQuad]>,
  484    pending_refresh: Option<Task<Result<()>>>,
  485}
  486
  487impl ScrollbarMarkerState {
  488    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  489        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  490    }
  491}
  492
  493#[derive(Clone, Debug)]
  494struct RunnableTasks {
  495    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  496    offset: MultiBufferOffset,
  497    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  498    column: u32,
  499    // Values of all named captures, including those starting with '_'
  500    extra_variables: HashMap<String, String>,
  501    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  502    context_range: Range<BufferOffset>,
  503}
  504
  505impl RunnableTasks {
  506    fn resolve<'a>(
  507        &'a self,
  508        cx: &'a task::TaskContext,
  509    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  510        self.templates.iter().filter_map(|(kind, template)| {
  511            template
  512                .resolve_task(&kind.to_id_base(), cx)
  513                .map(|task| (kind.clone(), task))
  514        })
  515    }
  516}
  517
  518#[derive(Clone)]
  519struct ResolvedTasks {
  520    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  521    position: Anchor,
  522}
  523#[derive(Copy, Clone, Debug)]
  524struct MultiBufferOffset(usize);
  525#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  526struct BufferOffset(usize);
  527
  528// Addons allow storing per-editor state in other crates (e.g. Vim)
  529pub trait Addon: 'static {
  530    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  531
  532    fn to_any(&self) -> &dyn std::any::Any;
  533}
  534
  535#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  536pub enum IsVimMode {
  537    Yes,
  538    No,
  539}
  540
  541/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  542///
  543/// See the [module level documentation](self) for more information.
  544pub struct Editor {
  545    focus_handle: FocusHandle,
  546    last_focused_descendant: Option<WeakFocusHandle>,
  547    /// The text buffer being edited
  548    buffer: Model<MultiBuffer>,
  549    /// Map of how text in the buffer should be displayed.
  550    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  551    pub display_map: Model<DisplayMap>,
  552    pub selections: SelectionsCollection,
  553    pub scroll_manager: ScrollManager,
  554    /// When inline assist editors are linked, they all render cursors because
  555    /// typing enters text into each of them, even the ones that aren't focused.
  556    pub(crate) show_cursor_when_unfocused: bool,
  557    columnar_selection_tail: Option<Anchor>,
  558    add_selections_state: Option<AddSelectionsState>,
  559    select_next_state: Option<SelectNextState>,
  560    select_prev_state: Option<SelectNextState>,
  561    selection_history: SelectionHistory,
  562    autoclose_regions: Vec<AutocloseRegion>,
  563    snippet_stack: InvalidationStack<SnippetState>,
  564    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  565    ime_transaction: Option<TransactionId>,
  566    active_diagnostics: Option<ActiveDiagnosticGroup>,
  567    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  568
  569    project: Option<Model<Project>>,
  570    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  571    completion_provider: Option<Box<dyn CompletionProvider>>,
  572    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  573    blink_manager: Model<BlinkManager>,
  574    show_cursor_names: bool,
  575    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  576    pub show_local_selections: bool,
  577    mode: EditorMode,
  578    show_breadcrumbs: bool,
  579    show_gutter: bool,
  580    show_line_numbers: Option<bool>,
  581    use_relative_line_numbers: Option<bool>,
  582    show_git_diff_gutter: Option<bool>,
  583    show_code_actions: Option<bool>,
  584    show_runnables: Option<bool>,
  585    show_wrap_guides: Option<bool>,
  586    show_indent_guides: Option<bool>,
  587    placeholder_text: Option<Arc<str>>,
  588    highlight_order: usize,
  589    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  590    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  591    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  592    scrollbar_marker_state: ScrollbarMarkerState,
  593    active_indent_guides_state: ActiveIndentGuidesState,
  594    nav_history: Option<ItemNavHistory>,
  595    context_menu: RwLock<Option<CodeContextMenu>>,
  596    mouse_context_menu: Option<MouseContextMenu>,
  597    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  598    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  599    signature_help_state: SignatureHelpState,
  600    auto_signature_help: Option<bool>,
  601    find_all_references_task_sources: Vec<Anchor>,
  602    next_completion_id: CompletionId,
  603    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  604    code_actions_task: Option<Task<Result<()>>>,
  605    document_highlights_task: Option<Task<()>>,
  606    linked_editing_range_task: Option<Task<Option<()>>>,
  607    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  608    pending_rename: Option<RenameState>,
  609    searchable: bool,
  610    cursor_shape: CursorShape,
  611    current_line_highlight: Option<CurrentLineHighlight>,
  612    collapse_matches: bool,
  613    autoindent_mode: Option<AutoindentMode>,
  614    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  615    input_enabled: bool,
  616    use_modal_editing: bool,
  617    read_only: bool,
  618    leader_peer_id: Option<PeerId>,
  619    remote_id: Option<ViewId>,
  620    hover_state: HoverState,
  621    gutter_hovered: bool,
  622    hovered_link_state: Option<HoveredLinkState>,
  623    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  624    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  625    active_inline_completion: Option<InlineCompletionState>,
  626    // enable_inline_completions is a switch that Vim can use to disable
  627    // inline completions based on its mode.
  628    enable_inline_completions: bool,
  629    show_inline_completions_override: Option<bool>,
  630    inlay_hint_cache: InlayHintCache,
  631    diff_map: DiffMap,
  632    next_inlay_id: usize,
  633    _subscriptions: Vec<Subscription>,
  634    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  635    gutter_dimensions: GutterDimensions,
  636    style: Option<EditorStyle>,
  637    text_style_refinement: Option<TextStyleRefinement>,
  638    next_editor_action_id: EditorActionId,
  639    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  640    use_autoclose: bool,
  641    use_auto_surround: bool,
  642    auto_replace_emoji_shortcode: bool,
  643    show_git_blame_gutter: bool,
  644    show_git_blame_inline: bool,
  645    show_git_blame_inline_delay_task: Option<Task<()>>,
  646    git_blame_inline_enabled: bool,
  647    serialize_dirty_buffers: bool,
  648    show_selection_menu: Option<bool>,
  649    blame: Option<Model<GitBlame>>,
  650    blame_subscription: Option<Subscription>,
  651    custom_context_menu: Option<
  652        Box<
  653            dyn 'static
  654                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  655        >,
  656    >,
  657    last_bounds: Option<Bounds<Pixels>>,
  658    expect_bounds_change: Option<Bounds<Pixels>>,
  659    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  660    tasks_update_task: Option<Task<()>>,
  661    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  662    breadcrumb_header: Option<String>,
  663    focused_block: Option<FocusedBlock>,
  664    next_scroll_position: NextScrollCursorCenterTopBottom,
  665    addons: HashMap<TypeId, Box<dyn Addon>>,
  666    _scroll_cursor_center_top_bottom_task: Task<()>,
  667}
  668
  669#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  670enum NextScrollCursorCenterTopBottom {
  671    #[default]
  672    Center,
  673    Top,
  674    Bottom,
  675}
  676
  677impl NextScrollCursorCenterTopBottom {
  678    fn next(&self) -> Self {
  679        match self {
  680            Self::Center => Self::Top,
  681            Self::Top => Self::Bottom,
  682            Self::Bottom => Self::Center,
  683        }
  684    }
  685}
  686
  687#[derive(Clone)]
  688pub struct EditorSnapshot {
  689    pub mode: EditorMode,
  690    show_gutter: bool,
  691    show_line_numbers: Option<bool>,
  692    show_git_diff_gutter: Option<bool>,
  693    show_code_actions: Option<bool>,
  694    show_runnables: Option<bool>,
  695    git_blame_gutter_max_author_length: Option<usize>,
  696    pub display_snapshot: DisplaySnapshot,
  697    pub placeholder_text: Option<Arc<str>>,
  698    diff_map: DiffMapSnapshot,
  699    is_focused: bool,
  700    scroll_anchor: ScrollAnchor,
  701    ongoing_scroll: OngoingScroll,
  702    current_line_highlight: CurrentLineHighlight,
  703    gutter_hovered: bool,
  704}
  705
  706const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  707
  708#[derive(Default, Debug, Clone, Copy)]
  709pub struct GutterDimensions {
  710    pub left_padding: Pixels,
  711    pub right_padding: Pixels,
  712    pub width: Pixels,
  713    pub margin: Pixels,
  714    pub git_blame_entries_width: Option<Pixels>,
  715}
  716
  717impl GutterDimensions {
  718    /// The full width of the space taken up by the gutter.
  719    pub fn full_width(&self) -> Pixels {
  720        self.margin + self.width
  721    }
  722
  723    /// The width of the space reserved for the fold indicators,
  724    /// use alongside 'justify_end' and `gutter_width` to
  725    /// right align content with the line numbers
  726    pub fn fold_area_width(&self) -> Pixels {
  727        self.margin + self.right_padding
  728    }
  729}
  730
  731#[derive(Debug)]
  732pub struct RemoteSelection {
  733    pub replica_id: ReplicaId,
  734    pub selection: Selection<Anchor>,
  735    pub cursor_shape: CursorShape,
  736    pub peer_id: PeerId,
  737    pub line_mode: bool,
  738    pub participant_index: Option<ParticipantIndex>,
  739    pub user_name: Option<SharedString>,
  740}
  741
  742#[derive(Clone, Debug)]
  743struct SelectionHistoryEntry {
  744    selections: Arc<[Selection<Anchor>]>,
  745    select_next_state: Option<SelectNextState>,
  746    select_prev_state: Option<SelectNextState>,
  747    add_selections_state: Option<AddSelectionsState>,
  748}
  749
  750enum SelectionHistoryMode {
  751    Normal,
  752    Undoing,
  753    Redoing,
  754}
  755
  756#[derive(Clone, PartialEq, Eq, Hash)]
  757struct HoveredCursor {
  758    replica_id: u16,
  759    selection_id: usize,
  760}
  761
  762impl Default for SelectionHistoryMode {
  763    fn default() -> Self {
  764        Self::Normal
  765    }
  766}
  767
  768#[derive(Default)]
  769struct SelectionHistory {
  770    #[allow(clippy::type_complexity)]
  771    selections_by_transaction:
  772        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  773    mode: SelectionHistoryMode,
  774    undo_stack: VecDeque<SelectionHistoryEntry>,
  775    redo_stack: VecDeque<SelectionHistoryEntry>,
  776}
  777
  778impl SelectionHistory {
  779    fn insert_transaction(
  780        &mut self,
  781        transaction_id: TransactionId,
  782        selections: Arc<[Selection<Anchor>]>,
  783    ) {
  784        self.selections_by_transaction
  785            .insert(transaction_id, (selections, None));
  786    }
  787
  788    #[allow(clippy::type_complexity)]
  789    fn transaction(
  790        &self,
  791        transaction_id: TransactionId,
  792    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  793        self.selections_by_transaction.get(&transaction_id)
  794    }
  795
  796    #[allow(clippy::type_complexity)]
  797    fn transaction_mut(
  798        &mut self,
  799        transaction_id: TransactionId,
  800    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  801        self.selections_by_transaction.get_mut(&transaction_id)
  802    }
  803
  804    fn push(&mut self, entry: SelectionHistoryEntry) {
  805        if !entry.selections.is_empty() {
  806            match self.mode {
  807                SelectionHistoryMode::Normal => {
  808                    self.push_undo(entry);
  809                    self.redo_stack.clear();
  810                }
  811                SelectionHistoryMode::Undoing => self.push_redo(entry),
  812                SelectionHistoryMode::Redoing => self.push_undo(entry),
  813            }
  814        }
  815    }
  816
  817    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  818        if self
  819            .undo_stack
  820            .back()
  821            .map_or(true, |e| e.selections != entry.selections)
  822        {
  823            self.undo_stack.push_back(entry);
  824            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  825                self.undo_stack.pop_front();
  826            }
  827        }
  828    }
  829
  830    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  831        if self
  832            .redo_stack
  833            .back()
  834            .map_or(true, |e| e.selections != entry.selections)
  835        {
  836            self.redo_stack.push_back(entry);
  837            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  838                self.redo_stack.pop_front();
  839            }
  840        }
  841    }
  842}
  843
  844struct RowHighlight {
  845    index: usize,
  846    range: Range<Anchor>,
  847    color: Hsla,
  848    should_autoscroll: bool,
  849}
  850
  851#[derive(Clone, Debug)]
  852struct AddSelectionsState {
  853    above: bool,
  854    stack: Vec<usize>,
  855}
  856
  857#[derive(Clone)]
  858struct SelectNextState {
  859    query: AhoCorasick,
  860    wordwise: bool,
  861    done: bool,
  862}
  863
  864impl std::fmt::Debug for SelectNextState {
  865    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  866        f.debug_struct(std::any::type_name::<Self>())
  867            .field("wordwise", &self.wordwise)
  868            .field("done", &self.done)
  869            .finish()
  870    }
  871}
  872
  873#[derive(Debug)]
  874struct AutocloseRegion {
  875    selection_id: usize,
  876    range: Range<Anchor>,
  877    pair: BracketPair,
  878}
  879
  880#[derive(Debug)]
  881struct SnippetState {
  882    ranges: Vec<Vec<Range<Anchor>>>,
  883    active_index: usize,
  884    choices: Vec<Option<Vec<String>>>,
  885}
  886
  887#[doc(hidden)]
  888pub struct RenameState {
  889    pub range: Range<Anchor>,
  890    pub old_name: Arc<str>,
  891    pub editor: View<Editor>,
  892    block_id: CustomBlockId,
  893}
  894
  895struct InvalidationStack<T>(Vec<T>);
  896
  897struct RegisteredInlineCompletionProvider {
  898    provider: Arc<dyn InlineCompletionProviderHandle>,
  899    _subscription: Subscription,
  900}
  901
  902#[derive(Debug)]
  903struct ActiveDiagnosticGroup {
  904    primary_range: Range<Anchor>,
  905    primary_message: String,
  906    group_id: usize,
  907    blocks: HashMap<CustomBlockId, Diagnostic>,
  908    is_valid: bool,
  909}
  910
  911#[derive(Serialize, Deserialize, Clone, Debug)]
  912pub struct ClipboardSelection {
  913    pub len: usize,
  914    pub is_entire_line: bool,
  915    pub first_line_indent: u32,
  916}
  917
  918#[derive(Debug)]
  919pub(crate) struct NavigationData {
  920    cursor_anchor: Anchor,
  921    cursor_position: Point,
  922    scroll_anchor: ScrollAnchor,
  923    scroll_top_row: u32,
  924}
  925
  926#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  927pub enum GotoDefinitionKind {
  928    Symbol,
  929    Declaration,
  930    Type,
  931    Implementation,
  932}
  933
  934#[derive(Debug, Clone)]
  935enum InlayHintRefreshReason {
  936    Toggle(bool),
  937    SettingsChange(InlayHintSettings),
  938    NewLinesShown,
  939    BufferEdited(HashSet<Arc<Language>>),
  940    RefreshRequested,
  941    ExcerptsRemoved(Vec<ExcerptId>),
  942}
  943
  944impl InlayHintRefreshReason {
  945    fn description(&self) -> &'static str {
  946        match self {
  947            Self::Toggle(_) => "toggle",
  948            Self::SettingsChange(_) => "settings change",
  949            Self::NewLinesShown => "new lines shown",
  950            Self::BufferEdited(_) => "buffer edited",
  951            Self::RefreshRequested => "refresh requested",
  952            Self::ExcerptsRemoved(_) => "excerpts removed",
  953        }
  954    }
  955}
  956
  957pub(crate) struct FocusedBlock {
  958    id: BlockId,
  959    focus_handle: WeakFocusHandle,
  960}
  961
  962#[derive(Clone)]
  963struct JumpData {
  964    excerpt_id: ExcerptId,
  965    position: Point,
  966    anchor: text::Anchor,
  967    path: Option<project::ProjectPath>,
  968    line_offset_from_top: u32,
  969}
  970
  971impl Editor {
  972    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
  973        let buffer = cx.new_model(|cx| Buffer::local("", cx));
  974        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
  975        Self::new(
  976            EditorMode::SingleLine { auto_width: false },
  977            buffer,
  978            None,
  979            false,
  980            cx,
  981        )
  982    }
  983
  984    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
  985        let buffer = cx.new_model(|cx| Buffer::local("", cx));
  986        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
  987        Self::new(EditorMode::Full, buffer, None, false, cx)
  988    }
  989
  990    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
  991        let buffer = cx.new_model(|cx| Buffer::local("", cx));
  992        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
  993        Self::new(
  994            EditorMode::SingleLine { auto_width: true },
  995            buffer,
  996            None,
  997            false,
  998            cx,
  999        )
 1000    }
 1001
 1002    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1003        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1004        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1005        Self::new(
 1006            EditorMode::AutoHeight { max_lines },
 1007            buffer,
 1008            None,
 1009            false,
 1010            cx,
 1011        )
 1012    }
 1013
 1014    pub fn for_buffer(
 1015        buffer: Model<Buffer>,
 1016        project: Option<Model<Project>>,
 1017        cx: &mut ViewContext<Self>,
 1018    ) -> Self {
 1019        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1020        Self::new(EditorMode::Full, buffer, project, false, cx)
 1021    }
 1022
 1023    pub fn for_multibuffer(
 1024        buffer: Model<MultiBuffer>,
 1025        project: Option<Model<Project>>,
 1026        show_excerpt_controls: bool,
 1027        cx: &mut ViewContext<Self>,
 1028    ) -> Self {
 1029        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1030    }
 1031
 1032    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1033        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1034        let mut clone = Self::new(
 1035            self.mode,
 1036            self.buffer.clone(),
 1037            self.project.clone(),
 1038            show_excerpt_controls,
 1039            cx,
 1040        );
 1041        self.display_map.update(cx, |display_map, cx| {
 1042            let snapshot = display_map.snapshot(cx);
 1043            clone.display_map.update(cx, |display_map, cx| {
 1044                display_map.set_state(&snapshot, cx);
 1045            });
 1046        });
 1047        clone.selections.clone_state(&self.selections);
 1048        clone.scroll_manager.clone_state(&self.scroll_manager);
 1049        clone.searchable = self.searchable;
 1050        clone
 1051    }
 1052
 1053    pub fn new(
 1054        mode: EditorMode,
 1055        buffer: Model<MultiBuffer>,
 1056        project: Option<Model<Project>>,
 1057        show_excerpt_controls: bool,
 1058        cx: &mut ViewContext<Self>,
 1059    ) -> Self {
 1060        let style = cx.text_style();
 1061        let font_size = style.font_size.to_pixels(cx.rem_size());
 1062        let editor = cx.view().downgrade();
 1063        let fold_placeholder = FoldPlaceholder {
 1064            constrain_width: true,
 1065            render: Arc::new(move |fold_id, fold_range, cx| {
 1066                let editor = editor.clone();
 1067                div()
 1068                    .id(fold_id)
 1069                    .bg(cx.theme().colors().ghost_element_background)
 1070                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1071                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1072                    .rounded_sm()
 1073                    .size_full()
 1074                    .cursor_pointer()
 1075                    .child("")
 1076                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1077                    .on_click(move |_, cx| {
 1078                        editor
 1079                            .update(cx, |editor, cx| {
 1080                                editor.unfold_ranges(
 1081                                    &[fold_range.start..fold_range.end],
 1082                                    true,
 1083                                    false,
 1084                                    cx,
 1085                                );
 1086                                cx.stop_propagation();
 1087                            })
 1088                            .ok();
 1089                    })
 1090                    .into_any()
 1091            }),
 1092            merge_adjacent: true,
 1093            ..Default::default()
 1094        };
 1095        let display_map = cx.new_model(|cx| {
 1096            DisplayMap::new(
 1097                buffer.clone(),
 1098                style.font(),
 1099                font_size,
 1100                None,
 1101                show_excerpt_controls,
 1102                FILE_HEADER_HEIGHT,
 1103                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1104                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1105                fold_placeholder,
 1106                cx,
 1107            )
 1108        });
 1109
 1110        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1111
 1112        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1113
 1114        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1115            .then(|| language_settings::SoftWrap::None);
 1116
 1117        let mut project_subscriptions = Vec::new();
 1118        if mode == EditorMode::Full {
 1119            if let Some(project) = project.as_ref() {
 1120                if buffer.read(cx).is_singleton() {
 1121                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1122                        cx.emit(EditorEvent::TitleChanged);
 1123                    }));
 1124                }
 1125                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1126                    if let project::Event::RefreshInlayHints = event {
 1127                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1128                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1129                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1130                            let focus_handle = editor.focus_handle(cx);
 1131                            if focus_handle.is_focused(cx) {
 1132                                let snapshot = buffer.read(cx).snapshot();
 1133                                for (range, snippet) in snippet_edits {
 1134                                    let editor_range =
 1135                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1136                                    editor
 1137                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1138                                        .ok();
 1139                                }
 1140                            }
 1141                        }
 1142                    }
 1143                }));
 1144                if let Some(task_inventory) = project
 1145                    .read(cx)
 1146                    .task_store()
 1147                    .read(cx)
 1148                    .task_inventory()
 1149                    .cloned()
 1150                {
 1151                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1152                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1153                    }));
 1154                }
 1155            }
 1156        }
 1157
 1158        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1159
 1160        let inlay_hint_settings =
 1161            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1162        let focus_handle = cx.focus_handle();
 1163        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1164        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1165            .detach();
 1166        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1167            .detach();
 1168        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1169
 1170        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1171            Some(false)
 1172        } else {
 1173            None
 1174        };
 1175
 1176        let mut code_action_providers = Vec::new();
 1177        if let Some(project) = project.clone() {
 1178            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1179            code_action_providers.push(Arc::new(project) as Arc<_>);
 1180        }
 1181
 1182        let mut this = Self {
 1183            focus_handle,
 1184            show_cursor_when_unfocused: false,
 1185            last_focused_descendant: None,
 1186            buffer: buffer.clone(),
 1187            display_map: display_map.clone(),
 1188            selections,
 1189            scroll_manager: ScrollManager::new(cx),
 1190            columnar_selection_tail: None,
 1191            add_selections_state: None,
 1192            select_next_state: None,
 1193            select_prev_state: None,
 1194            selection_history: Default::default(),
 1195            autoclose_regions: Default::default(),
 1196            snippet_stack: Default::default(),
 1197            select_larger_syntax_node_stack: Vec::new(),
 1198            ime_transaction: Default::default(),
 1199            active_diagnostics: None,
 1200            soft_wrap_mode_override,
 1201            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1202            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1203            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1204            project,
 1205            blink_manager: blink_manager.clone(),
 1206            show_local_selections: true,
 1207            mode,
 1208            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1209            show_gutter: mode == EditorMode::Full,
 1210            show_line_numbers: None,
 1211            use_relative_line_numbers: None,
 1212            show_git_diff_gutter: None,
 1213            show_code_actions: None,
 1214            show_runnables: None,
 1215            show_wrap_guides: None,
 1216            show_indent_guides,
 1217            placeholder_text: None,
 1218            highlight_order: 0,
 1219            highlighted_rows: HashMap::default(),
 1220            background_highlights: Default::default(),
 1221            gutter_highlights: TreeMap::default(),
 1222            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1223            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1224            nav_history: None,
 1225            context_menu: RwLock::new(None),
 1226            mouse_context_menu: None,
 1227            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1228            completion_tasks: Default::default(),
 1229            signature_help_state: SignatureHelpState::default(),
 1230            auto_signature_help: None,
 1231            find_all_references_task_sources: Vec::new(),
 1232            next_completion_id: 0,
 1233            next_inlay_id: 0,
 1234            code_action_providers,
 1235            available_code_actions: Default::default(),
 1236            code_actions_task: Default::default(),
 1237            document_highlights_task: Default::default(),
 1238            linked_editing_range_task: Default::default(),
 1239            pending_rename: Default::default(),
 1240            searchable: true,
 1241            cursor_shape: EditorSettings::get_global(cx)
 1242                .cursor_shape
 1243                .unwrap_or_default(),
 1244            current_line_highlight: None,
 1245            autoindent_mode: Some(AutoindentMode::EachLine),
 1246            collapse_matches: false,
 1247            workspace: None,
 1248            input_enabled: true,
 1249            use_modal_editing: mode == EditorMode::Full,
 1250            read_only: false,
 1251            use_autoclose: true,
 1252            use_auto_surround: true,
 1253            auto_replace_emoji_shortcode: false,
 1254            leader_peer_id: None,
 1255            remote_id: None,
 1256            hover_state: Default::default(),
 1257            hovered_link_state: Default::default(),
 1258            inline_completion_provider: None,
 1259            active_inline_completion: None,
 1260            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1261            diff_map: DiffMap::default(),
 1262            gutter_hovered: false,
 1263            pixel_position_of_newest_cursor: None,
 1264            last_bounds: None,
 1265            expect_bounds_change: None,
 1266            gutter_dimensions: GutterDimensions::default(),
 1267            style: None,
 1268            show_cursor_names: false,
 1269            hovered_cursors: Default::default(),
 1270            next_editor_action_id: EditorActionId::default(),
 1271            editor_actions: Rc::default(),
 1272            show_inline_completions_override: None,
 1273            enable_inline_completions: true,
 1274            custom_context_menu: None,
 1275            show_git_blame_gutter: false,
 1276            show_git_blame_inline: false,
 1277            show_selection_menu: None,
 1278            show_git_blame_inline_delay_task: None,
 1279            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1280            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1281                .session
 1282                .restore_unsaved_buffers,
 1283            blame: None,
 1284            blame_subscription: None,
 1285            tasks: Default::default(),
 1286            _subscriptions: vec![
 1287                cx.observe(&buffer, Self::on_buffer_changed),
 1288                cx.subscribe(&buffer, Self::on_buffer_event),
 1289                cx.observe(&display_map, Self::on_display_map_changed),
 1290                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1291                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1292                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1293                cx.observe_window_activation(|editor, cx| {
 1294                    let active = cx.is_window_active();
 1295                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1296                        if active {
 1297                            blink_manager.enable(cx);
 1298                        } else {
 1299                            blink_manager.disable(cx);
 1300                        }
 1301                    });
 1302                }),
 1303            ],
 1304            tasks_update_task: None,
 1305            linked_edit_ranges: Default::default(),
 1306            previous_search_ranges: None,
 1307            breadcrumb_header: None,
 1308            focused_block: None,
 1309            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1310            addons: HashMap::default(),
 1311            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1312            text_style_refinement: None,
 1313        };
 1314        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1315        this._subscriptions.extend(project_subscriptions);
 1316
 1317        this.end_selection(cx);
 1318        this.scroll_manager.show_scrollbar(cx);
 1319
 1320        if mode == EditorMode::Full {
 1321            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1322            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1323
 1324            if this.git_blame_inline_enabled {
 1325                this.git_blame_inline_enabled = true;
 1326                this.start_git_blame_inline(false, cx);
 1327            }
 1328        }
 1329
 1330        this.report_editor_event("open", None, cx);
 1331        this
 1332    }
 1333
 1334    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1335        self.mouse_context_menu
 1336            .as_ref()
 1337            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1338    }
 1339
 1340    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1341        let mut key_context = KeyContext::new_with_defaults();
 1342        key_context.add("Editor");
 1343        let mode = match self.mode {
 1344            EditorMode::SingleLine { .. } => "single_line",
 1345            EditorMode::AutoHeight { .. } => "auto_height",
 1346            EditorMode::Full => "full",
 1347        };
 1348
 1349        if EditorSettings::jupyter_enabled(cx) {
 1350            key_context.add("jupyter");
 1351        }
 1352
 1353        key_context.set("mode", mode);
 1354        if self.pending_rename.is_some() {
 1355            key_context.add("renaming");
 1356        }
 1357        if self.context_menu_visible() {
 1358            match self.context_menu.read().as_ref() {
 1359                Some(CodeContextMenu::Completions(_)) => {
 1360                    key_context.add("menu");
 1361                    key_context.add("showing_completions")
 1362                }
 1363                Some(CodeContextMenu::CodeActions(_)) => {
 1364                    key_context.add("menu");
 1365                    key_context.add("showing_code_actions")
 1366                }
 1367                None => {}
 1368            }
 1369        }
 1370
 1371        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1372        if !self.focus_handle(cx).contains_focused(cx)
 1373            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1374        {
 1375            for addon in self.addons.values() {
 1376                addon.extend_key_context(&mut key_context, cx)
 1377            }
 1378        }
 1379
 1380        if let Some(extension) = self
 1381            .buffer
 1382            .read(cx)
 1383            .as_singleton()
 1384            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1385        {
 1386            key_context.set("extension", extension.to_string());
 1387        }
 1388
 1389        if self.has_active_inline_completion() {
 1390            key_context.add("copilot_suggestion");
 1391            key_context.add("inline_completion");
 1392        }
 1393
 1394        key_context
 1395    }
 1396
 1397    pub fn new_file(
 1398        workspace: &mut Workspace,
 1399        _: &workspace::NewFile,
 1400        cx: &mut ViewContext<Workspace>,
 1401    ) {
 1402        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1403            "Failed to create buffer",
 1404            cx,
 1405            |e, _| match e.error_code() {
 1406                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1407                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1408                e.error_tag("required").unwrap_or("the latest version")
 1409            )),
 1410                _ => None,
 1411            },
 1412        );
 1413    }
 1414
 1415    pub fn new_in_workspace(
 1416        workspace: &mut Workspace,
 1417        cx: &mut ViewContext<Workspace>,
 1418    ) -> Task<Result<View<Editor>>> {
 1419        let project = workspace.project().clone();
 1420        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1421
 1422        cx.spawn(|workspace, mut cx| async move {
 1423            let buffer = create.await?;
 1424            workspace.update(&mut cx, |workspace, cx| {
 1425                let editor =
 1426                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1427                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1428                editor
 1429            })
 1430        })
 1431    }
 1432
 1433    fn new_file_vertical(
 1434        workspace: &mut Workspace,
 1435        _: &workspace::NewFileSplitVertical,
 1436        cx: &mut ViewContext<Workspace>,
 1437    ) {
 1438        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1439    }
 1440
 1441    fn new_file_horizontal(
 1442        workspace: &mut Workspace,
 1443        _: &workspace::NewFileSplitHorizontal,
 1444        cx: &mut ViewContext<Workspace>,
 1445    ) {
 1446        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1447    }
 1448
 1449    fn new_file_in_direction(
 1450        workspace: &mut Workspace,
 1451        direction: SplitDirection,
 1452        cx: &mut ViewContext<Workspace>,
 1453    ) {
 1454        let project = workspace.project().clone();
 1455        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1456
 1457        cx.spawn(|workspace, mut cx| async move {
 1458            let buffer = create.await?;
 1459            workspace.update(&mut cx, move |workspace, cx| {
 1460                workspace.split_item(
 1461                    direction,
 1462                    Box::new(
 1463                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1464                    ),
 1465                    cx,
 1466                )
 1467            })?;
 1468            anyhow::Ok(())
 1469        })
 1470        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1471            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1472                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1473                e.error_tag("required").unwrap_or("the latest version")
 1474            )),
 1475            _ => None,
 1476        });
 1477    }
 1478
 1479    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1480        self.leader_peer_id
 1481    }
 1482
 1483    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1484        &self.buffer
 1485    }
 1486
 1487    pub fn workspace(&self) -> Option<View<Workspace>> {
 1488        self.workspace.as_ref()?.0.upgrade()
 1489    }
 1490
 1491    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1492        self.buffer().read(cx).title(cx)
 1493    }
 1494
 1495    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1496        let git_blame_gutter_max_author_length = self
 1497            .render_git_blame_gutter(cx)
 1498            .then(|| {
 1499                if let Some(blame) = self.blame.as_ref() {
 1500                    let max_author_length =
 1501                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1502                    Some(max_author_length)
 1503                } else {
 1504                    None
 1505                }
 1506            })
 1507            .flatten();
 1508
 1509        EditorSnapshot {
 1510            mode: self.mode,
 1511            show_gutter: self.show_gutter,
 1512            show_line_numbers: self.show_line_numbers,
 1513            show_git_diff_gutter: self.show_git_diff_gutter,
 1514            show_code_actions: self.show_code_actions,
 1515            show_runnables: self.show_runnables,
 1516            git_blame_gutter_max_author_length,
 1517            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1518            scroll_anchor: self.scroll_manager.anchor(),
 1519            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1520            placeholder_text: self.placeholder_text.clone(),
 1521            diff_map: self.diff_map.snapshot(),
 1522            is_focused: self.focus_handle.is_focused(cx),
 1523            current_line_highlight: self
 1524                .current_line_highlight
 1525                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1526            gutter_hovered: self.gutter_hovered,
 1527        }
 1528    }
 1529
 1530    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1531        self.buffer.read(cx).language_at(point, cx)
 1532    }
 1533
 1534    pub fn file_at<T: ToOffset>(
 1535        &self,
 1536        point: T,
 1537        cx: &AppContext,
 1538    ) -> Option<Arc<dyn language::File>> {
 1539        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1540    }
 1541
 1542    pub fn active_excerpt(
 1543        &self,
 1544        cx: &AppContext,
 1545    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1546        self.buffer
 1547            .read(cx)
 1548            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1549    }
 1550
 1551    pub fn mode(&self) -> EditorMode {
 1552        self.mode
 1553    }
 1554
 1555    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1556        self.collaboration_hub.as_deref()
 1557    }
 1558
 1559    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1560        self.collaboration_hub = Some(hub);
 1561    }
 1562
 1563    pub fn set_custom_context_menu(
 1564        &mut self,
 1565        f: impl 'static
 1566            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1567    ) {
 1568        self.custom_context_menu = Some(Box::new(f))
 1569    }
 1570
 1571    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1572        self.completion_provider = provider;
 1573    }
 1574
 1575    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1576        self.semantics_provider.clone()
 1577    }
 1578
 1579    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1580        self.semantics_provider = provider;
 1581    }
 1582
 1583    pub fn set_inline_completion_provider<T>(
 1584        &mut self,
 1585        provider: Option<Model<T>>,
 1586        cx: &mut ViewContext<Self>,
 1587    ) where
 1588        T: InlineCompletionProvider,
 1589    {
 1590        self.inline_completion_provider =
 1591            provider.map(|provider| RegisteredInlineCompletionProvider {
 1592                _subscription: cx.observe(&provider, |this, _, cx| {
 1593                    if this.focus_handle.is_focused(cx) {
 1594                        this.update_visible_inline_completion(cx);
 1595                    }
 1596                }),
 1597                provider: Arc::new(provider),
 1598            });
 1599        self.refresh_inline_completion(false, false, cx);
 1600    }
 1601
 1602    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1603        self.placeholder_text.as_deref()
 1604    }
 1605
 1606    pub fn set_placeholder_text(
 1607        &mut self,
 1608        placeholder_text: impl Into<Arc<str>>,
 1609        cx: &mut ViewContext<Self>,
 1610    ) {
 1611        let placeholder_text = Some(placeholder_text.into());
 1612        if self.placeholder_text != placeholder_text {
 1613            self.placeholder_text = placeholder_text;
 1614            cx.notify();
 1615        }
 1616    }
 1617
 1618    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1619        self.cursor_shape = cursor_shape;
 1620
 1621        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1622        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1623
 1624        cx.notify();
 1625    }
 1626
 1627    pub fn set_current_line_highlight(
 1628        &mut self,
 1629        current_line_highlight: Option<CurrentLineHighlight>,
 1630    ) {
 1631        self.current_line_highlight = current_line_highlight;
 1632    }
 1633
 1634    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1635        self.collapse_matches = collapse_matches;
 1636    }
 1637
 1638    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1639        if self.collapse_matches {
 1640            return range.start..range.start;
 1641        }
 1642        range.clone()
 1643    }
 1644
 1645    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1646        if self.display_map.read(cx).clip_at_line_ends != clip {
 1647            self.display_map
 1648                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1649        }
 1650    }
 1651
 1652    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1653        self.input_enabled = input_enabled;
 1654    }
 1655
 1656    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1657        self.enable_inline_completions = enabled;
 1658    }
 1659
 1660    pub fn set_autoindent(&mut self, autoindent: bool) {
 1661        if autoindent {
 1662            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1663        } else {
 1664            self.autoindent_mode = None;
 1665        }
 1666    }
 1667
 1668    pub fn read_only(&self, cx: &AppContext) -> bool {
 1669        self.read_only || self.buffer.read(cx).read_only()
 1670    }
 1671
 1672    pub fn set_read_only(&mut self, read_only: bool) {
 1673        self.read_only = read_only;
 1674    }
 1675
 1676    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1677        self.use_autoclose = autoclose;
 1678    }
 1679
 1680    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1681        self.use_auto_surround = auto_surround;
 1682    }
 1683
 1684    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1685        self.auto_replace_emoji_shortcode = auto_replace;
 1686    }
 1687
 1688    pub fn toggle_inline_completions(
 1689        &mut self,
 1690        _: &ToggleInlineCompletions,
 1691        cx: &mut ViewContext<Self>,
 1692    ) {
 1693        if self.show_inline_completions_override.is_some() {
 1694            self.set_show_inline_completions(None, cx);
 1695        } else {
 1696            let cursor = self.selections.newest_anchor().head();
 1697            if let Some((buffer, cursor_buffer_position)) =
 1698                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1699            {
 1700                let show_inline_completions =
 1701                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1702                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1703            }
 1704        }
 1705    }
 1706
 1707    pub fn set_show_inline_completions(
 1708        &mut self,
 1709        show_inline_completions: Option<bool>,
 1710        cx: &mut ViewContext<Self>,
 1711    ) {
 1712        self.show_inline_completions_override = show_inline_completions;
 1713        self.refresh_inline_completion(false, true, cx);
 1714    }
 1715
 1716    fn should_show_inline_completions(
 1717        &self,
 1718        buffer: &Model<Buffer>,
 1719        buffer_position: language::Anchor,
 1720        cx: &AppContext,
 1721    ) -> bool {
 1722        if !self.snippet_stack.is_empty() {
 1723            return false;
 1724        }
 1725
 1726        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1727            return false;
 1728        }
 1729
 1730        if let Some(provider) = self.inline_completion_provider() {
 1731            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1732                show_inline_completions
 1733            } else {
 1734                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1735            }
 1736        } else {
 1737            false
 1738        }
 1739    }
 1740
 1741    fn inline_completions_disabled_in_scope(
 1742        &self,
 1743        buffer: &Model<Buffer>,
 1744        buffer_position: language::Anchor,
 1745        cx: &AppContext,
 1746    ) -> bool {
 1747        let snapshot = buffer.read(cx).snapshot();
 1748        let settings = snapshot.settings_at(buffer_position, cx);
 1749
 1750        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1751            return false;
 1752        };
 1753
 1754        scope.override_name().map_or(false, |scope_name| {
 1755            settings
 1756                .inline_completions_disabled_in
 1757                .iter()
 1758                .any(|s| s == scope_name)
 1759        })
 1760    }
 1761
 1762    pub fn set_use_modal_editing(&mut self, to: bool) {
 1763        self.use_modal_editing = to;
 1764    }
 1765
 1766    pub fn use_modal_editing(&self) -> bool {
 1767        self.use_modal_editing
 1768    }
 1769
 1770    fn selections_did_change(
 1771        &mut self,
 1772        local: bool,
 1773        old_cursor_position: &Anchor,
 1774        show_completions: bool,
 1775        cx: &mut ViewContext<Self>,
 1776    ) {
 1777        cx.invalidate_character_coordinates();
 1778
 1779        // Copy selections to primary selection buffer
 1780        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1781        if local {
 1782            let selections = self.selections.all::<usize>(cx);
 1783            let buffer_handle = self.buffer.read(cx).read(cx);
 1784
 1785            let mut text = String::new();
 1786            for (index, selection) in selections.iter().enumerate() {
 1787                let text_for_selection = buffer_handle
 1788                    .text_for_range(selection.start..selection.end)
 1789                    .collect::<String>();
 1790
 1791                text.push_str(&text_for_selection);
 1792                if index != selections.len() - 1 {
 1793                    text.push('\n');
 1794                }
 1795            }
 1796
 1797            if !text.is_empty() {
 1798                cx.write_to_primary(ClipboardItem::new_string(text));
 1799            }
 1800        }
 1801
 1802        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1803            self.buffer.update(cx, |buffer, cx| {
 1804                buffer.set_active_selections(
 1805                    &self.selections.disjoint_anchors(),
 1806                    self.selections.line_mode,
 1807                    self.cursor_shape,
 1808                    cx,
 1809                )
 1810            });
 1811        }
 1812        let display_map = self
 1813            .display_map
 1814            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1815        let buffer = &display_map.buffer_snapshot;
 1816        self.add_selections_state = None;
 1817        self.select_next_state = None;
 1818        self.select_prev_state = None;
 1819        self.select_larger_syntax_node_stack.clear();
 1820        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1821        self.snippet_stack
 1822            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1823        self.take_rename(false, cx);
 1824
 1825        let new_cursor_position = self.selections.newest_anchor().head();
 1826
 1827        self.push_to_nav_history(
 1828            *old_cursor_position,
 1829            Some(new_cursor_position.to_point(buffer)),
 1830            cx,
 1831        );
 1832
 1833        if local {
 1834            let new_cursor_position = self.selections.newest_anchor().head();
 1835            let mut context_menu = self.context_menu.write();
 1836            let completion_menu = match context_menu.as_ref() {
 1837                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1838
 1839                _ => {
 1840                    *context_menu = None;
 1841                    None
 1842                }
 1843            };
 1844
 1845            if let Some(completion_menu) = completion_menu {
 1846                let cursor_position = new_cursor_position.to_offset(buffer);
 1847                let (word_range, kind) =
 1848                    buffer.surrounding_word(completion_menu.initial_position, true);
 1849                if kind == Some(CharKind::Word)
 1850                    && word_range.to_inclusive().contains(&cursor_position)
 1851                {
 1852                    let mut completion_menu = completion_menu.clone();
 1853                    drop(context_menu);
 1854
 1855                    let query = Self::completion_query(buffer, cursor_position);
 1856                    cx.spawn(move |this, mut cx| async move {
 1857                        completion_menu
 1858                            .filter(query.as_deref(), cx.background_executor().clone())
 1859                            .await;
 1860
 1861                        this.update(&mut cx, |this, cx| {
 1862                            let mut context_menu = this.context_menu.write();
 1863                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1864                            else {
 1865                                return;
 1866                            };
 1867
 1868                            if menu.id > completion_menu.id {
 1869                                return;
 1870                            }
 1871
 1872                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1873                            drop(context_menu);
 1874                            cx.notify();
 1875                        })
 1876                    })
 1877                    .detach();
 1878
 1879                    if show_completions {
 1880                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1881                    }
 1882                } else {
 1883                    drop(context_menu);
 1884                    self.hide_context_menu(cx);
 1885                }
 1886            } else {
 1887                drop(context_menu);
 1888            }
 1889
 1890            hide_hover(self, cx);
 1891
 1892            if old_cursor_position.to_display_point(&display_map).row()
 1893                != new_cursor_position.to_display_point(&display_map).row()
 1894            {
 1895                self.available_code_actions.take();
 1896            }
 1897            self.refresh_code_actions(cx);
 1898            self.refresh_document_highlights(cx);
 1899            refresh_matching_bracket_highlights(self, cx);
 1900            self.update_visible_inline_completion(cx);
 1901            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1902            if self.git_blame_inline_enabled {
 1903                self.start_inline_blame_timer(cx);
 1904            }
 1905        }
 1906
 1907        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1908        cx.emit(EditorEvent::SelectionsChanged { local });
 1909
 1910        if self.selections.disjoint_anchors().len() == 1 {
 1911            cx.emit(SearchEvent::ActiveMatchChanged)
 1912        }
 1913        cx.notify();
 1914    }
 1915
 1916    pub fn change_selections<R>(
 1917        &mut self,
 1918        autoscroll: Option<Autoscroll>,
 1919        cx: &mut ViewContext<Self>,
 1920        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1921    ) -> R {
 1922        self.change_selections_inner(autoscroll, true, cx, change)
 1923    }
 1924
 1925    pub fn change_selections_inner<R>(
 1926        &mut self,
 1927        autoscroll: Option<Autoscroll>,
 1928        request_completions: bool,
 1929        cx: &mut ViewContext<Self>,
 1930        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1931    ) -> R {
 1932        let old_cursor_position = self.selections.newest_anchor().head();
 1933        self.push_to_selection_history();
 1934
 1935        let (changed, result) = self.selections.change_with(cx, change);
 1936
 1937        if changed {
 1938            if let Some(autoscroll) = autoscroll {
 1939                self.request_autoscroll(autoscroll, cx);
 1940            }
 1941            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 1942
 1943            if self.should_open_signature_help_automatically(
 1944                &old_cursor_position,
 1945                self.signature_help_state.backspace_pressed(),
 1946                cx,
 1947            ) {
 1948                self.show_signature_help(&ShowSignatureHelp, cx);
 1949            }
 1950            self.signature_help_state.set_backspace_pressed(false);
 1951        }
 1952
 1953        result
 1954    }
 1955
 1956    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 1957    where
 1958        I: IntoIterator<Item = (Range<S>, T)>,
 1959        S: ToOffset,
 1960        T: Into<Arc<str>>,
 1961    {
 1962        if self.read_only(cx) {
 1963            return;
 1964        }
 1965
 1966        self.buffer
 1967            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 1968    }
 1969
 1970    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 1971    where
 1972        I: IntoIterator<Item = (Range<S>, T)>,
 1973        S: ToOffset,
 1974        T: Into<Arc<str>>,
 1975    {
 1976        if self.read_only(cx) {
 1977            return;
 1978        }
 1979
 1980        self.buffer.update(cx, |buffer, cx| {
 1981            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 1982        });
 1983    }
 1984
 1985    pub fn edit_with_block_indent<I, S, T>(
 1986        &mut self,
 1987        edits: I,
 1988        original_indent_columns: Vec<u32>,
 1989        cx: &mut ViewContext<Self>,
 1990    ) where
 1991        I: IntoIterator<Item = (Range<S>, T)>,
 1992        S: ToOffset,
 1993        T: Into<Arc<str>>,
 1994    {
 1995        if self.read_only(cx) {
 1996            return;
 1997        }
 1998
 1999        self.buffer.update(cx, |buffer, cx| {
 2000            buffer.edit(
 2001                edits,
 2002                Some(AutoindentMode::Block {
 2003                    original_indent_columns,
 2004                }),
 2005                cx,
 2006            )
 2007        });
 2008    }
 2009
 2010    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2011        self.hide_context_menu(cx);
 2012
 2013        match phase {
 2014            SelectPhase::Begin {
 2015                position,
 2016                add,
 2017                click_count,
 2018            } => self.begin_selection(position, add, click_count, cx),
 2019            SelectPhase::BeginColumnar {
 2020                position,
 2021                goal_column,
 2022                reset,
 2023            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2024            SelectPhase::Extend {
 2025                position,
 2026                click_count,
 2027            } => self.extend_selection(position, click_count, cx),
 2028            SelectPhase::Update {
 2029                position,
 2030                goal_column,
 2031                scroll_delta,
 2032            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2033            SelectPhase::End => self.end_selection(cx),
 2034        }
 2035    }
 2036
 2037    fn extend_selection(
 2038        &mut self,
 2039        position: DisplayPoint,
 2040        click_count: usize,
 2041        cx: &mut ViewContext<Self>,
 2042    ) {
 2043        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2044        let tail = self.selections.newest::<usize>(cx).tail();
 2045        self.begin_selection(position, false, click_count, cx);
 2046
 2047        let position = position.to_offset(&display_map, Bias::Left);
 2048        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2049
 2050        let mut pending_selection = self
 2051            .selections
 2052            .pending_anchor()
 2053            .expect("extend_selection not called with pending selection");
 2054        if position >= tail {
 2055            pending_selection.start = tail_anchor;
 2056        } else {
 2057            pending_selection.end = tail_anchor;
 2058            pending_selection.reversed = true;
 2059        }
 2060
 2061        let mut pending_mode = self.selections.pending_mode().unwrap();
 2062        match &mut pending_mode {
 2063            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2064            _ => {}
 2065        }
 2066
 2067        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2068            s.set_pending(pending_selection, pending_mode)
 2069        });
 2070    }
 2071
 2072    fn begin_selection(
 2073        &mut self,
 2074        position: DisplayPoint,
 2075        add: bool,
 2076        click_count: usize,
 2077        cx: &mut ViewContext<Self>,
 2078    ) {
 2079        if !self.focus_handle.is_focused(cx) {
 2080            self.last_focused_descendant = None;
 2081            cx.focus(&self.focus_handle);
 2082        }
 2083
 2084        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2085        let buffer = &display_map.buffer_snapshot;
 2086        let newest_selection = self.selections.newest_anchor().clone();
 2087        let position = display_map.clip_point(position, Bias::Left);
 2088
 2089        let start;
 2090        let end;
 2091        let mode;
 2092        let mut auto_scroll;
 2093        match click_count {
 2094            1 => {
 2095                start = buffer.anchor_before(position.to_point(&display_map));
 2096                end = start;
 2097                mode = SelectMode::Character;
 2098                auto_scroll = true;
 2099            }
 2100            2 => {
 2101                let range = movement::surrounding_word(&display_map, position);
 2102                start = buffer.anchor_before(range.start.to_point(&display_map));
 2103                end = buffer.anchor_before(range.end.to_point(&display_map));
 2104                mode = SelectMode::Word(start..end);
 2105                auto_scroll = true;
 2106            }
 2107            3 => {
 2108                let position = display_map
 2109                    .clip_point(position, Bias::Left)
 2110                    .to_point(&display_map);
 2111                let line_start = display_map.prev_line_boundary(position).0;
 2112                let next_line_start = buffer.clip_point(
 2113                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2114                    Bias::Left,
 2115                );
 2116                start = buffer.anchor_before(line_start);
 2117                end = buffer.anchor_before(next_line_start);
 2118                mode = SelectMode::Line(start..end);
 2119                auto_scroll = true;
 2120            }
 2121            _ => {
 2122                start = buffer.anchor_before(0);
 2123                end = buffer.anchor_before(buffer.len());
 2124                mode = SelectMode::All;
 2125                auto_scroll = false;
 2126            }
 2127        }
 2128        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2129
 2130        let point_to_delete: Option<usize> = {
 2131            let selected_points: Vec<Selection<Point>> =
 2132                self.selections.disjoint_in_range(start..end, cx);
 2133
 2134            if !add || click_count > 1 {
 2135                None
 2136            } else if !selected_points.is_empty() {
 2137                Some(selected_points[0].id)
 2138            } else {
 2139                let clicked_point_already_selected =
 2140                    self.selections.disjoint.iter().find(|selection| {
 2141                        selection.start.to_point(buffer) == start.to_point(buffer)
 2142                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2143                    });
 2144
 2145                clicked_point_already_selected.map(|selection| selection.id)
 2146            }
 2147        };
 2148
 2149        let selections_count = self.selections.count();
 2150
 2151        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2152            if let Some(point_to_delete) = point_to_delete {
 2153                s.delete(point_to_delete);
 2154
 2155                if selections_count == 1 {
 2156                    s.set_pending_anchor_range(start..end, mode);
 2157                }
 2158            } else {
 2159                if !add {
 2160                    s.clear_disjoint();
 2161                } else if click_count > 1 {
 2162                    s.delete(newest_selection.id)
 2163                }
 2164
 2165                s.set_pending_anchor_range(start..end, mode);
 2166            }
 2167        });
 2168    }
 2169
 2170    fn begin_columnar_selection(
 2171        &mut self,
 2172        position: DisplayPoint,
 2173        goal_column: u32,
 2174        reset: bool,
 2175        cx: &mut ViewContext<Self>,
 2176    ) {
 2177        if !self.focus_handle.is_focused(cx) {
 2178            self.last_focused_descendant = None;
 2179            cx.focus(&self.focus_handle);
 2180        }
 2181
 2182        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2183
 2184        if reset {
 2185            let pointer_position = display_map
 2186                .buffer_snapshot
 2187                .anchor_before(position.to_point(&display_map));
 2188
 2189            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2190                s.clear_disjoint();
 2191                s.set_pending_anchor_range(
 2192                    pointer_position..pointer_position,
 2193                    SelectMode::Character,
 2194                );
 2195            });
 2196        }
 2197
 2198        let tail = self.selections.newest::<Point>(cx).tail();
 2199        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2200
 2201        if !reset {
 2202            self.select_columns(
 2203                tail.to_display_point(&display_map),
 2204                position,
 2205                goal_column,
 2206                &display_map,
 2207                cx,
 2208            );
 2209        }
 2210    }
 2211
 2212    fn update_selection(
 2213        &mut self,
 2214        position: DisplayPoint,
 2215        goal_column: u32,
 2216        scroll_delta: gpui::Point<f32>,
 2217        cx: &mut ViewContext<Self>,
 2218    ) {
 2219        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2220
 2221        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2222            let tail = tail.to_display_point(&display_map);
 2223            self.select_columns(tail, position, goal_column, &display_map, cx);
 2224        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2225            let buffer = self.buffer.read(cx).snapshot(cx);
 2226            let head;
 2227            let tail;
 2228            let mode = self.selections.pending_mode().unwrap();
 2229            match &mode {
 2230                SelectMode::Character => {
 2231                    head = position.to_point(&display_map);
 2232                    tail = pending.tail().to_point(&buffer);
 2233                }
 2234                SelectMode::Word(original_range) => {
 2235                    let original_display_range = original_range.start.to_display_point(&display_map)
 2236                        ..original_range.end.to_display_point(&display_map);
 2237                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2238                        ..original_display_range.end.to_point(&display_map);
 2239                    if movement::is_inside_word(&display_map, position)
 2240                        || original_display_range.contains(&position)
 2241                    {
 2242                        let word_range = movement::surrounding_word(&display_map, position);
 2243                        if word_range.start < original_display_range.start {
 2244                            head = word_range.start.to_point(&display_map);
 2245                        } else {
 2246                            head = word_range.end.to_point(&display_map);
 2247                        }
 2248                    } else {
 2249                        head = position.to_point(&display_map);
 2250                    }
 2251
 2252                    if head <= original_buffer_range.start {
 2253                        tail = original_buffer_range.end;
 2254                    } else {
 2255                        tail = original_buffer_range.start;
 2256                    }
 2257                }
 2258                SelectMode::Line(original_range) => {
 2259                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2260
 2261                    let position = display_map
 2262                        .clip_point(position, Bias::Left)
 2263                        .to_point(&display_map);
 2264                    let line_start = display_map.prev_line_boundary(position).0;
 2265                    let next_line_start = buffer.clip_point(
 2266                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2267                        Bias::Left,
 2268                    );
 2269
 2270                    if line_start < original_range.start {
 2271                        head = line_start
 2272                    } else {
 2273                        head = next_line_start
 2274                    }
 2275
 2276                    if head <= original_range.start {
 2277                        tail = original_range.end;
 2278                    } else {
 2279                        tail = original_range.start;
 2280                    }
 2281                }
 2282                SelectMode::All => {
 2283                    return;
 2284                }
 2285            };
 2286
 2287            if head < tail {
 2288                pending.start = buffer.anchor_before(head);
 2289                pending.end = buffer.anchor_before(tail);
 2290                pending.reversed = true;
 2291            } else {
 2292                pending.start = buffer.anchor_before(tail);
 2293                pending.end = buffer.anchor_before(head);
 2294                pending.reversed = false;
 2295            }
 2296
 2297            self.change_selections(None, cx, |s| {
 2298                s.set_pending(pending, mode);
 2299            });
 2300        } else {
 2301            log::error!("update_selection dispatched with no pending selection");
 2302            return;
 2303        }
 2304
 2305        self.apply_scroll_delta(scroll_delta, cx);
 2306        cx.notify();
 2307    }
 2308
 2309    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2310        self.columnar_selection_tail.take();
 2311        if self.selections.pending_anchor().is_some() {
 2312            let selections = self.selections.all::<usize>(cx);
 2313            self.change_selections(None, cx, |s| {
 2314                s.select(selections);
 2315                s.clear_pending();
 2316            });
 2317        }
 2318    }
 2319
 2320    fn select_columns(
 2321        &mut self,
 2322        tail: DisplayPoint,
 2323        head: DisplayPoint,
 2324        goal_column: u32,
 2325        display_map: &DisplaySnapshot,
 2326        cx: &mut ViewContext<Self>,
 2327    ) {
 2328        let start_row = cmp::min(tail.row(), head.row());
 2329        let end_row = cmp::max(tail.row(), head.row());
 2330        let start_column = cmp::min(tail.column(), goal_column);
 2331        let end_column = cmp::max(tail.column(), goal_column);
 2332        let reversed = start_column < tail.column();
 2333
 2334        let selection_ranges = (start_row.0..=end_row.0)
 2335            .map(DisplayRow)
 2336            .filter_map(|row| {
 2337                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2338                    let start = display_map
 2339                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2340                        .to_point(display_map);
 2341                    let end = display_map
 2342                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2343                        .to_point(display_map);
 2344                    if reversed {
 2345                        Some(end..start)
 2346                    } else {
 2347                        Some(start..end)
 2348                    }
 2349                } else {
 2350                    None
 2351                }
 2352            })
 2353            .collect::<Vec<_>>();
 2354
 2355        self.change_selections(None, cx, |s| {
 2356            s.select_ranges(selection_ranges);
 2357        });
 2358        cx.notify();
 2359    }
 2360
 2361    pub fn has_pending_nonempty_selection(&self) -> bool {
 2362        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2363            Some(Selection { start, end, .. }) => start != end,
 2364            None => false,
 2365        };
 2366
 2367        pending_nonempty_selection
 2368            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2369    }
 2370
 2371    pub fn has_pending_selection(&self) -> bool {
 2372        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2373    }
 2374
 2375    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2376        if self.clear_expanded_diff_hunks(cx) {
 2377            cx.notify();
 2378            return;
 2379        }
 2380        if self.dismiss_menus_and_popups(true, cx) {
 2381            return;
 2382        }
 2383
 2384        if self.mode == EditorMode::Full
 2385            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2386        {
 2387            return;
 2388        }
 2389
 2390        cx.propagate();
 2391    }
 2392
 2393    pub fn dismiss_menus_and_popups(
 2394        &mut self,
 2395        should_report_inline_completion_event: bool,
 2396        cx: &mut ViewContext<Self>,
 2397    ) -> bool {
 2398        if self.take_rename(false, cx).is_some() {
 2399            return true;
 2400        }
 2401
 2402        if hide_hover(self, cx) {
 2403            return true;
 2404        }
 2405
 2406        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2407            return true;
 2408        }
 2409
 2410        if self.hide_context_menu(cx).is_some() {
 2411            return true;
 2412        }
 2413
 2414        if self.mouse_context_menu.take().is_some() {
 2415            return true;
 2416        }
 2417
 2418        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2419            return true;
 2420        }
 2421
 2422        if self.snippet_stack.pop().is_some() {
 2423            return true;
 2424        }
 2425
 2426        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2427            self.dismiss_diagnostics(cx);
 2428            return true;
 2429        }
 2430
 2431        false
 2432    }
 2433
 2434    fn linked_editing_ranges_for(
 2435        &self,
 2436        selection: Range<text::Anchor>,
 2437        cx: &AppContext,
 2438    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2439        if self.linked_edit_ranges.is_empty() {
 2440            return None;
 2441        }
 2442        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2443            selection.end.buffer_id.and_then(|end_buffer_id| {
 2444                if selection.start.buffer_id != Some(end_buffer_id) {
 2445                    return None;
 2446                }
 2447                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2448                let snapshot = buffer.read(cx).snapshot();
 2449                self.linked_edit_ranges
 2450                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2451                    .map(|ranges| (ranges, snapshot, buffer))
 2452            })?;
 2453        use text::ToOffset as TO;
 2454        // find offset from the start of current range to current cursor position
 2455        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2456
 2457        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2458        let start_difference = start_offset - start_byte_offset;
 2459        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2460        let end_difference = end_offset - start_byte_offset;
 2461        // Current range has associated linked ranges.
 2462        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2463        for range in linked_ranges.iter() {
 2464            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2465            let end_offset = start_offset + end_difference;
 2466            let start_offset = start_offset + start_difference;
 2467            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2468                continue;
 2469            }
 2470            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2471                if s.start.buffer_id != selection.start.buffer_id
 2472                    || s.end.buffer_id != selection.end.buffer_id
 2473                {
 2474                    return false;
 2475                }
 2476                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2477                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2478            }) {
 2479                continue;
 2480            }
 2481            let start = buffer_snapshot.anchor_after(start_offset);
 2482            let end = buffer_snapshot.anchor_after(end_offset);
 2483            linked_edits
 2484                .entry(buffer.clone())
 2485                .or_default()
 2486                .push(start..end);
 2487        }
 2488        Some(linked_edits)
 2489    }
 2490
 2491    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2492        let text: Arc<str> = text.into();
 2493
 2494        if self.read_only(cx) {
 2495            return;
 2496        }
 2497
 2498        let selections = self.selections.all_adjusted(cx);
 2499        let mut bracket_inserted = false;
 2500        let mut edits = Vec::new();
 2501        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2502        let mut new_selections = Vec::with_capacity(selections.len());
 2503        let mut new_autoclose_regions = Vec::new();
 2504        let snapshot = self.buffer.read(cx).read(cx);
 2505
 2506        for (selection, autoclose_region) in
 2507            self.selections_with_autoclose_regions(selections, &snapshot)
 2508        {
 2509            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2510                // Determine if the inserted text matches the opening or closing
 2511                // bracket of any of this language's bracket pairs.
 2512                let mut bracket_pair = None;
 2513                let mut is_bracket_pair_start = false;
 2514                let mut is_bracket_pair_end = false;
 2515                if !text.is_empty() {
 2516                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2517                    //  and they are removing the character that triggered IME popup.
 2518                    for (pair, enabled) in scope.brackets() {
 2519                        if !pair.close && !pair.surround {
 2520                            continue;
 2521                        }
 2522
 2523                        if enabled && pair.start.ends_with(text.as_ref()) {
 2524                            let prefix_len = pair.start.len() - text.len();
 2525                            let preceding_text_matches_prefix = prefix_len == 0
 2526                                || (selection.start.column >= (prefix_len as u32)
 2527                                    && snapshot.contains_str_at(
 2528                                        Point::new(
 2529                                            selection.start.row,
 2530                                            selection.start.column - (prefix_len as u32),
 2531                                        ),
 2532                                        &pair.start[..prefix_len],
 2533                                    ));
 2534                            if preceding_text_matches_prefix {
 2535                                bracket_pair = Some(pair.clone());
 2536                                is_bracket_pair_start = true;
 2537                                break;
 2538                            }
 2539                        }
 2540                        if pair.end.as_str() == text.as_ref() {
 2541                            bracket_pair = Some(pair.clone());
 2542                            is_bracket_pair_end = true;
 2543                            break;
 2544                        }
 2545                    }
 2546                }
 2547
 2548                if let Some(bracket_pair) = bracket_pair {
 2549                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2550                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2551                    let auto_surround =
 2552                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2553                    if selection.is_empty() {
 2554                        if is_bracket_pair_start {
 2555                            // If the inserted text is a suffix of an opening bracket and the
 2556                            // selection is preceded by the rest of the opening bracket, then
 2557                            // insert the closing bracket.
 2558                            let following_text_allows_autoclose = snapshot
 2559                                .chars_at(selection.start)
 2560                                .next()
 2561                                .map_or(true, |c| scope.should_autoclose_before(c));
 2562
 2563                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2564                                && bracket_pair.start.len() == 1
 2565                            {
 2566                                let target = bracket_pair.start.chars().next().unwrap();
 2567                                let current_line_count = snapshot
 2568                                    .reversed_chars_at(selection.start)
 2569                                    .take_while(|&c| c != '\n')
 2570                                    .filter(|&c| c == target)
 2571                                    .count();
 2572                                current_line_count % 2 == 1
 2573                            } else {
 2574                                false
 2575                            };
 2576
 2577                            if autoclose
 2578                                && bracket_pair.close
 2579                                && following_text_allows_autoclose
 2580                                && !is_closing_quote
 2581                            {
 2582                                let anchor = snapshot.anchor_before(selection.end);
 2583                                new_selections.push((selection.map(|_| anchor), text.len()));
 2584                                new_autoclose_regions.push((
 2585                                    anchor,
 2586                                    text.len(),
 2587                                    selection.id,
 2588                                    bracket_pair.clone(),
 2589                                ));
 2590                                edits.push((
 2591                                    selection.range(),
 2592                                    format!("{}{}", text, bracket_pair.end).into(),
 2593                                ));
 2594                                bracket_inserted = true;
 2595                                continue;
 2596                            }
 2597                        }
 2598
 2599                        if let Some(region) = autoclose_region {
 2600                            // If the selection is followed by an auto-inserted closing bracket,
 2601                            // then don't insert that closing bracket again; just move the selection
 2602                            // past the closing bracket.
 2603                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2604                                && text.as_ref() == region.pair.end.as_str();
 2605                            if should_skip {
 2606                                let anchor = snapshot.anchor_after(selection.end);
 2607                                new_selections
 2608                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2609                                continue;
 2610                            }
 2611                        }
 2612
 2613                        let always_treat_brackets_as_autoclosed = snapshot
 2614                            .settings_at(selection.start, cx)
 2615                            .always_treat_brackets_as_autoclosed;
 2616                        if always_treat_brackets_as_autoclosed
 2617                            && is_bracket_pair_end
 2618                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2619                        {
 2620                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2621                            // and the inserted text is a closing bracket and the selection is followed
 2622                            // by the closing bracket then move the selection past the closing bracket.
 2623                            let anchor = snapshot.anchor_after(selection.end);
 2624                            new_selections.push((selection.map(|_| anchor), text.len()));
 2625                            continue;
 2626                        }
 2627                    }
 2628                    // If an opening bracket is 1 character long and is typed while
 2629                    // text is selected, then surround that text with the bracket pair.
 2630                    else if auto_surround
 2631                        && bracket_pair.surround
 2632                        && is_bracket_pair_start
 2633                        && bracket_pair.start.chars().count() == 1
 2634                    {
 2635                        edits.push((selection.start..selection.start, text.clone()));
 2636                        edits.push((
 2637                            selection.end..selection.end,
 2638                            bracket_pair.end.as_str().into(),
 2639                        ));
 2640                        bracket_inserted = true;
 2641                        new_selections.push((
 2642                            Selection {
 2643                                id: selection.id,
 2644                                start: snapshot.anchor_after(selection.start),
 2645                                end: snapshot.anchor_before(selection.end),
 2646                                reversed: selection.reversed,
 2647                                goal: selection.goal,
 2648                            },
 2649                            0,
 2650                        ));
 2651                        continue;
 2652                    }
 2653                }
 2654            }
 2655
 2656            if self.auto_replace_emoji_shortcode
 2657                && selection.is_empty()
 2658                && text.as_ref().ends_with(':')
 2659            {
 2660                if let Some(possible_emoji_short_code) =
 2661                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2662                {
 2663                    if !possible_emoji_short_code.is_empty() {
 2664                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2665                            let emoji_shortcode_start = Point::new(
 2666                                selection.start.row,
 2667                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2668                            );
 2669
 2670                            // Remove shortcode from buffer
 2671                            edits.push((
 2672                                emoji_shortcode_start..selection.start,
 2673                                "".to_string().into(),
 2674                            ));
 2675                            new_selections.push((
 2676                                Selection {
 2677                                    id: selection.id,
 2678                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2679                                    end: snapshot.anchor_before(selection.start),
 2680                                    reversed: selection.reversed,
 2681                                    goal: selection.goal,
 2682                                },
 2683                                0,
 2684                            ));
 2685
 2686                            // Insert emoji
 2687                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2688                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2689                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2690
 2691                            continue;
 2692                        }
 2693                    }
 2694                }
 2695            }
 2696
 2697            // If not handling any auto-close operation, then just replace the selected
 2698            // text with the given input and move the selection to the end of the
 2699            // newly inserted text.
 2700            let anchor = snapshot.anchor_after(selection.end);
 2701            if !self.linked_edit_ranges.is_empty() {
 2702                let start_anchor = snapshot.anchor_before(selection.start);
 2703
 2704                let is_word_char = text.chars().next().map_or(true, |char| {
 2705                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2706                    classifier.is_word(char)
 2707                });
 2708
 2709                if is_word_char {
 2710                    if let Some(ranges) = self
 2711                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2712                    {
 2713                        for (buffer, edits) in ranges {
 2714                            linked_edits
 2715                                .entry(buffer.clone())
 2716                                .or_default()
 2717                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2718                        }
 2719                    }
 2720                }
 2721            }
 2722
 2723            new_selections.push((selection.map(|_| anchor), 0));
 2724            edits.push((selection.start..selection.end, text.clone()));
 2725        }
 2726
 2727        drop(snapshot);
 2728
 2729        self.transact(cx, |this, cx| {
 2730            this.buffer.update(cx, |buffer, cx| {
 2731                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2732            });
 2733            for (buffer, edits) in linked_edits {
 2734                buffer.update(cx, |buffer, cx| {
 2735                    let snapshot = buffer.snapshot();
 2736                    let edits = edits
 2737                        .into_iter()
 2738                        .map(|(range, text)| {
 2739                            use text::ToPoint as TP;
 2740                            let end_point = TP::to_point(&range.end, &snapshot);
 2741                            let start_point = TP::to_point(&range.start, &snapshot);
 2742                            (start_point..end_point, text)
 2743                        })
 2744                        .sorted_by_key(|(range, _)| range.start)
 2745                        .collect::<Vec<_>>();
 2746                    buffer.edit(edits, None, cx);
 2747                })
 2748            }
 2749            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2750            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2751            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2752            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2753                .zip(new_selection_deltas)
 2754                .map(|(selection, delta)| Selection {
 2755                    id: selection.id,
 2756                    start: selection.start + delta,
 2757                    end: selection.end + delta,
 2758                    reversed: selection.reversed,
 2759                    goal: SelectionGoal::None,
 2760                })
 2761                .collect::<Vec<_>>();
 2762
 2763            let mut i = 0;
 2764            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2765                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2766                let start = map.buffer_snapshot.anchor_before(position);
 2767                let end = map.buffer_snapshot.anchor_after(position);
 2768                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2769                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2770                        Ordering::Less => i += 1,
 2771                        Ordering::Greater => break,
 2772                        Ordering::Equal => {
 2773                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2774                                Ordering::Less => i += 1,
 2775                                Ordering::Equal => break,
 2776                                Ordering::Greater => break,
 2777                            }
 2778                        }
 2779                    }
 2780                }
 2781                this.autoclose_regions.insert(
 2782                    i,
 2783                    AutocloseRegion {
 2784                        selection_id,
 2785                        range: start..end,
 2786                        pair,
 2787                    },
 2788                );
 2789            }
 2790
 2791            let had_active_inline_completion = this.has_active_inline_completion();
 2792            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2793                s.select(new_selections)
 2794            });
 2795
 2796            if !bracket_inserted {
 2797                if let Some(on_type_format_task) =
 2798                    this.trigger_on_type_formatting(text.to_string(), cx)
 2799                {
 2800                    on_type_format_task.detach_and_log_err(cx);
 2801                }
 2802            }
 2803
 2804            let editor_settings = EditorSettings::get_global(cx);
 2805            if bracket_inserted
 2806                && (editor_settings.auto_signature_help
 2807                    || editor_settings.show_signature_help_after_edits)
 2808            {
 2809                this.show_signature_help(&ShowSignatureHelp, cx);
 2810            }
 2811
 2812            let trigger_in_words = !had_active_inline_completion;
 2813            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2814            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2815            this.refresh_inline_completion(true, false, cx);
 2816        });
 2817    }
 2818
 2819    fn find_possible_emoji_shortcode_at_position(
 2820        snapshot: &MultiBufferSnapshot,
 2821        position: Point,
 2822    ) -> Option<String> {
 2823        let mut chars = Vec::new();
 2824        let mut found_colon = false;
 2825        for char in snapshot.reversed_chars_at(position).take(100) {
 2826            // Found a possible emoji shortcode in the middle of the buffer
 2827            if found_colon {
 2828                if char.is_whitespace() {
 2829                    chars.reverse();
 2830                    return Some(chars.iter().collect());
 2831                }
 2832                // If the previous character is not a whitespace, we are in the middle of a word
 2833                // and we only want to complete the shortcode if the word is made up of other emojis
 2834                let mut containing_word = String::new();
 2835                for ch in snapshot
 2836                    .reversed_chars_at(position)
 2837                    .skip(chars.len() + 1)
 2838                    .take(100)
 2839                {
 2840                    if ch.is_whitespace() {
 2841                        break;
 2842                    }
 2843                    containing_word.push(ch);
 2844                }
 2845                let containing_word = containing_word.chars().rev().collect::<String>();
 2846                if util::word_consists_of_emojis(containing_word.as_str()) {
 2847                    chars.reverse();
 2848                    return Some(chars.iter().collect());
 2849                }
 2850            }
 2851
 2852            if char.is_whitespace() || !char.is_ascii() {
 2853                return None;
 2854            }
 2855            if char == ':' {
 2856                found_colon = true;
 2857            } else {
 2858                chars.push(char);
 2859            }
 2860        }
 2861        // Found a possible emoji shortcode at the beginning of the buffer
 2862        chars.reverse();
 2863        Some(chars.iter().collect())
 2864    }
 2865
 2866    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2867        self.transact(cx, |this, cx| {
 2868            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2869                let selections = this.selections.all::<usize>(cx);
 2870                let multi_buffer = this.buffer.read(cx);
 2871                let buffer = multi_buffer.snapshot(cx);
 2872                selections
 2873                    .iter()
 2874                    .map(|selection| {
 2875                        let start_point = selection.start.to_point(&buffer);
 2876                        let mut indent =
 2877                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2878                        indent.len = cmp::min(indent.len, start_point.column);
 2879                        let start = selection.start;
 2880                        let end = selection.end;
 2881                        let selection_is_empty = start == end;
 2882                        let language_scope = buffer.language_scope_at(start);
 2883                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2884                            &language_scope
 2885                        {
 2886                            let leading_whitespace_len = buffer
 2887                                .reversed_chars_at(start)
 2888                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2889                                .map(|c| c.len_utf8())
 2890                                .sum::<usize>();
 2891
 2892                            let trailing_whitespace_len = buffer
 2893                                .chars_at(end)
 2894                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2895                                .map(|c| c.len_utf8())
 2896                                .sum::<usize>();
 2897
 2898                            let insert_extra_newline =
 2899                                language.brackets().any(|(pair, enabled)| {
 2900                                    let pair_start = pair.start.trim_end();
 2901                                    let pair_end = pair.end.trim_start();
 2902
 2903                                    enabled
 2904                                        && pair.newline
 2905                                        && buffer.contains_str_at(
 2906                                            end + trailing_whitespace_len,
 2907                                            pair_end,
 2908                                        )
 2909                                        && buffer.contains_str_at(
 2910                                            (start - leading_whitespace_len)
 2911                                                .saturating_sub(pair_start.len()),
 2912                                            pair_start,
 2913                                        )
 2914                                });
 2915
 2916                            // Comment extension on newline is allowed only for cursor selections
 2917                            let comment_delimiter = maybe!({
 2918                                if !selection_is_empty {
 2919                                    return None;
 2920                                }
 2921
 2922                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 2923                                    return None;
 2924                                }
 2925
 2926                                let delimiters = language.line_comment_prefixes();
 2927                                let max_len_of_delimiter =
 2928                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 2929                                let (snapshot, range) =
 2930                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 2931
 2932                                let mut index_of_first_non_whitespace = 0;
 2933                                let comment_candidate = snapshot
 2934                                    .chars_for_range(range)
 2935                                    .skip_while(|c| {
 2936                                        let should_skip = c.is_whitespace();
 2937                                        if should_skip {
 2938                                            index_of_first_non_whitespace += 1;
 2939                                        }
 2940                                        should_skip
 2941                                    })
 2942                                    .take(max_len_of_delimiter)
 2943                                    .collect::<String>();
 2944                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 2945                                    comment_candidate.starts_with(comment_prefix.as_ref())
 2946                                })?;
 2947                                let cursor_is_placed_after_comment_marker =
 2948                                    index_of_first_non_whitespace + comment_prefix.len()
 2949                                        <= start_point.column as usize;
 2950                                if cursor_is_placed_after_comment_marker {
 2951                                    Some(comment_prefix.clone())
 2952                                } else {
 2953                                    None
 2954                                }
 2955                            });
 2956                            (comment_delimiter, insert_extra_newline)
 2957                        } else {
 2958                            (None, false)
 2959                        };
 2960
 2961                        let capacity_for_delimiter = comment_delimiter
 2962                            .as_deref()
 2963                            .map(str::len)
 2964                            .unwrap_or_default();
 2965                        let mut new_text =
 2966                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 2967                        new_text.push('\n');
 2968                        new_text.extend(indent.chars());
 2969                        if let Some(delimiter) = &comment_delimiter {
 2970                            new_text.push_str(delimiter);
 2971                        }
 2972                        if insert_extra_newline {
 2973                            new_text = new_text.repeat(2);
 2974                        }
 2975
 2976                        let anchor = buffer.anchor_after(end);
 2977                        let new_selection = selection.map(|_| anchor);
 2978                        (
 2979                            (start..end, new_text),
 2980                            (insert_extra_newline, new_selection),
 2981                        )
 2982                    })
 2983                    .unzip()
 2984            };
 2985
 2986            this.edit_with_autoindent(edits, cx);
 2987            let buffer = this.buffer.read(cx).snapshot(cx);
 2988            let new_selections = selection_fixup_info
 2989                .into_iter()
 2990                .map(|(extra_newline_inserted, new_selection)| {
 2991                    let mut cursor = new_selection.end.to_point(&buffer);
 2992                    if extra_newline_inserted {
 2993                        cursor.row -= 1;
 2994                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 2995                    }
 2996                    new_selection.map(|_| cursor)
 2997                })
 2998                .collect();
 2999
 3000            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3001            this.refresh_inline_completion(true, false, cx);
 3002        });
 3003    }
 3004
 3005    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3006        let buffer = self.buffer.read(cx);
 3007        let snapshot = buffer.snapshot(cx);
 3008
 3009        let mut edits = Vec::new();
 3010        let mut rows = Vec::new();
 3011
 3012        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3013            let cursor = selection.head();
 3014            let row = cursor.row;
 3015
 3016            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3017
 3018            let newline = "\n".to_string();
 3019            edits.push((start_of_line..start_of_line, newline));
 3020
 3021            rows.push(row + rows_inserted as u32);
 3022        }
 3023
 3024        self.transact(cx, |editor, cx| {
 3025            editor.edit(edits, cx);
 3026
 3027            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3028                let mut index = 0;
 3029                s.move_cursors_with(|map, _, _| {
 3030                    let row = rows[index];
 3031                    index += 1;
 3032
 3033                    let point = Point::new(row, 0);
 3034                    let boundary = map.next_line_boundary(point).1;
 3035                    let clipped = map.clip_point(boundary, Bias::Left);
 3036
 3037                    (clipped, SelectionGoal::None)
 3038                });
 3039            });
 3040
 3041            let mut indent_edits = Vec::new();
 3042            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3043            for row in rows {
 3044                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3045                for (row, indent) in indents {
 3046                    if indent.len == 0 {
 3047                        continue;
 3048                    }
 3049
 3050                    let text = match indent.kind {
 3051                        IndentKind::Space => " ".repeat(indent.len as usize),
 3052                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3053                    };
 3054                    let point = Point::new(row.0, 0);
 3055                    indent_edits.push((point..point, text));
 3056                }
 3057            }
 3058            editor.edit(indent_edits, cx);
 3059        });
 3060    }
 3061
 3062    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3063        let buffer = self.buffer.read(cx);
 3064        let snapshot = buffer.snapshot(cx);
 3065
 3066        let mut edits = Vec::new();
 3067        let mut rows = Vec::new();
 3068        let mut rows_inserted = 0;
 3069
 3070        for selection in self.selections.all_adjusted(cx) {
 3071            let cursor = selection.head();
 3072            let row = cursor.row;
 3073
 3074            let point = Point::new(row + 1, 0);
 3075            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3076
 3077            let newline = "\n".to_string();
 3078            edits.push((start_of_line..start_of_line, newline));
 3079
 3080            rows_inserted += 1;
 3081            rows.push(row + rows_inserted);
 3082        }
 3083
 3084        self.transact(cx, |editor, cx| {
 3085            editor.edit(edits, cx);
 3086
 3087            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3088                let mut index = 0;
 3089                s.move_cursors_with(|map, _, _| {
 3090                    let row = rows[index];
 3091                    index += 1;
 3092
 3093                    let point = Point::new(row, 0);
 3094                    let boundary = map.next_line_boundary(point).1;
 3095                    let clipped = map.clip_point(boundary, Bias::Left);
 3096
 3097                    (clipped, SelectionGoal::None)
 3098                });
 3099            });
 3100
 3101            let mut indent_edits = Vec::new();
 3102            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3103            for row in rows {
 3104                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3105                for (row, indent) in indents {
 3106                    if indent.len == 0 {
 3107                        continue;
 3108                    }
 3109
 3110                    let text = match indent.kind {
 3111                        IndentKind::Space => " ".repeat(indent.len as usize),
 3112                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3113                    };
 3114                    let point = Point::new(row.0, 0);
 3115                    indent_edits.push((point..point, text));
 3116                }
 3117            }
 3118            editor.edit(indent_edits, cx);
 3119        });
 3120    }
 3121
 3122    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3123        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3124            original_indent_columns: Vec::new(),
 3125        });
 3126        self.insert_with_autoindent_mode(text, autoindent, cx);
 3127    }
 3128
 3129    fn insert_with_autoindent_mode(
 3130        &mut self,
 3131        text: &str,
 3132        autoindent_mode: Option<AutoindentMode>,
 3133        cx: &mut ViewContext<Self>,
 3134    ) {
 3135        if self.read_only(cx) {
 3136            return;
 3137        }
 3138
 3139        let text: Arc<str> = text.into();
 3140        self.transact(cx, |this, cx| {
 3141            let old_selections = this.selections.all_adjusted(cx);
 3142            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3143                let anchors = {
 3144                    let snapshot = buffer.read(cx);
 3145                    old_selections
 3146                        .iter()
 3147                        .map(|s| {
 3148                            let anchor = snapshot.anchor_after(s.head());
 3149                            s.map(|_| anchor)
 3150                        })
 3151                        .collect::<Vec<_>>()
 3152                };
 3153                buffer.edit(
 3154                    old_selections
 3155                        .iter()
 3156                        .map(|s| (s.start..s.end, text.clone())),
 3157                    autoindent_mode,
 3158                    cx,
 3159                );
 3160                anchors
 3161            });
 3162
 3163            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3164                s.select_anchors(selection_anchors);
 3165            })
 3166        });
 3167    }
 3168
 3169    fn trigger_completion_on_input(
 3170        &mut self,
 3171        text: &str,
 3172        trigger_in_words: bool,
 3173        cx: &mut ViewContext<Self>,
 3174    ) {
 3175        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3176            self.show_completions(
 3177                &ShowCompletions {
 3178                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3179                },
 3180                cx,
 3181            );
 3182        } else {
 3183            self.hide_context_menu(cx);
 3184        }
 3185    }
 3186
 3187    fn is_completion_trigger(
 3188        &self,
 3189        text: &str,
 3190        trigger_in_words: bool,
 3191        cx: &mut ViewContext<Self>,
 3192    ) -> bool {
 3193        let position = self.selections.newest_anchor().head();
 3194        let multibuffer = self.buffer.read(cx);
 3195        let Some(buffer) = position
 3196            .buffer_id
 3197            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3198        else {
 3199            return false;
 3200        };
 3201
 3202        if let Some(completion_provider) = &self.completion_provider {
 3203            completion_provider.is_completion_trigger(
 3204                &buffer,
 3205                position.text_anchor,
 3206                text,
 3207                trigger_in_words,
 3208                cx,
 3209            )
 3210        } else {
 3211            false
 3212        }
 3213    }
 3214
 3215    /// If any empty selections is touching the start of its innermost containing autoclose
 3216    /// region, expand it to select the brackets.
 3217    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3218        let selections = self.selections.all::<usize>(cx);
 3219        let buffer = self.buffer.read(cx).read(cx);
 3220        let new_selections = self
 3221            .selections_with_autoclose_regions(selections, &buffer)
 3222            .map(|(mut selection, region)| {
 3223                if !selection.is_empty() {
 3224                    return selection;
 3225                }
 3226
 3227                if let Some(region) = region {
 3228                    let mut range = region.range.to_offset(&buffer);
 3229                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3230                        range.start -= region.pair.start.len();
 3231                        if buffer.contains_str_at(range.start, &region.pair.start)
 3232                            && buffer.contains_str_at(range.end, &region.pair.end)
 3233                        {
 3234                            range.end += region.pair.end.len();
 3235                            selection.start = range.start;
 3236                            selection.end = range.end;
 3237
 3238                            return selection;
 3239                        }
 3240                    }
 3241                }
 3242
 3243                let always_treat_brackets_as_autoclosed = buffer
 3244                    .settings_at(selection.start, cx)
 3245                    .always_treat_brackets_as_autoclosed;
 3246
 3247                if !always_treat_brackets_as_autoclosed {
 3248                    return selection;
 3249                }
 3250
 3251                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3252                    for (pair, enabled) in scope.brackets() {
 3253                        if !enabled || !pair.close {
 3254                            continue;
 3255                        }
 3256
 3257                        if buffer.contains_str_at(selection.start, &pair.end) {
 3258                            let pair_start_len = pair.start.len();
 3259                            if buffer.contains_str_at(
 3260                                selection.start.saturating_sub(pair_start_len),
 3261                                &pair.start,
 3262                            ) {
 3263                                selection.start -= pair_start_len;
 3264                                selection.end += pair.end.len();
 3265
 3266                                return selection;
 3267                            }
 3268                        }
 3269                    }
 3270                }
 3271
 3272                selection
 3273            })
 3274            .collect();
 3275
 3276        drop(buffer);
 3277        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3278    }
 3279
 3280    /// Iterate the given selections, and for each one, find the smallest surrounding
 3281    /// autoclose region. This uses the ordering of the selections and the autoclose
 3282    /// regions to avoid repeated comparisons.
 3283    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3284        &'a self,
 3285        selections: impl IntoIterator<Item = Selection<D>>,
 3286        buffer: &'a MultiBufferSnapshot,
 3287    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3288        let mut i = 0;
 3289        let mut regions = self.autoclose_regions.as_slice();
 3290        selections.into_iter().map(move |selection| {
 3291            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3292
 3293            let mut enclosing = None;
 3294            while let Some(pair_state) = regions.get(i) {
 3295                if pair_state.range.end.to_offset(buffer) < range.start {
 3296                    regions = &regions[i + 1..];
 3297                    i = 0;
 3298                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3299                    break;
 3300                } else {
 3301                    if pair_state.selection_id == selection.id {
 3302                        enclosing = Some(pair_state);
 3303                    }
 3304                    i += 1;
 3305                }
 3306            }
 3307
 3308            (selection, enclosing)
 3309        })
 3310    }
 3311
 3312    /// Remove any autoclose regions that no longer contain their selection.
 3313    fn invalidate_autoclose_regions(
 3314        &mut self,
 3315        mut selections: &[Selection<Anchor>],
 3316        buffer: &MultiBufferSnapshot,
 3317    ) {
 3318        self.autoclose_regions.retain(|state| {
 3319            let mut i = 0;
 3320            while let Some(selection) = selections.get(i) {
 3321                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3322                    selections = &selections[1..];
 3323                    continue;
 3324                }
 3325                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3326                    break;
 3327                }
 3328                if selection.id == state.selection_id {
 3329                    return true;
 3330                } else {
 3331                    i += 1;
 3332                }
 3333            }
 3334            false
 3335        });
 3336    }
 3337
 3338    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3339        let offset = position.to_offset(buffer);
 3340        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3341        if offset > word_range.start && kind == Some(CharKind::Word) {
 3342            Some(
 3343                buffer
 3344                    .text_for_range(word_range.start..offset)
 3345                    .collect::<String>(),
 3346            )
 3347        } else {
 3348            None
 3349        }
 3350    }
 3351
 3352    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3353        self.refresh_inlay_hints(
 3354            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3355            cx,
 3356        );
 3357    }
 3358
 3359    pub fn inlay_hints_enabled(&self) -> bool {
 3360        self.inlay_hint_cache.enabled
 3361    }
 3362
 3363    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3364        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3365            return;
 3366        }
 3367
 3368        let reason_description = reason.description();
 3369        let ignore_debounce = matches!(
 3370            reason,
 3371            InlayHintRefreshReason::SettingsChange(_)
 3372                | InlayHintRefreshReason::Toggle(_)
 3373                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3374        );
 3375        let (invalidate_cache, required_languages) = match reason {
 3376            InlayHintRefreshReason::Toggle(enabled) => {
 3377                self.inlay_hint_cache.enabled = enabled;
 3378                if enabled {
 3379                    (InvalidationStrategy::RefreshRequested, None)
 3380                } else {
 3381                    self.inlay_hint_cache.clear();
 3382                    self.splice_inlays(
 3383                        self.visible_inlay_hints(cx)
 3384                            .iter()
 3385                            .map(|inlay| inlay.id)
 3386                            .collect(),
 3387                        Vec::new(),
 3388                        cx,
 3389                    );
 3390                    return;
 3391                }
 3392            }
 3393            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3394                match self.inlay_hint_cache.update_settings(
 3395                    &self.buffer,
 3396                    new_settings,
 3397                    self.visible_inlay_hints(cx),
 3398                    cx,
 3399                ) {
 3400                    ControlFlow::Break(Some(InlaySplice {
 3401                        to_remove,
 3402                        to_insert,
 3403                    })) => {
 3404                        self.splice_inlays(to_remove, to_insert, cx);
 3405                        return;
 3406                    }
 3407                    ControlFlow::Break(None) => return,
 3408                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3409                }
 3410            }
 3411            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3412                if let Some(InlaySplice {
 3413                    to_remove,
 3414                    to_insert,
 3415                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3416                {
 3417                    self.splice_inlays(to_remove, to_insert, cx);
 3418                }
 3419                return;
 3420            }
 3421            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3422            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3423                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3424            }
 3425            InlayHintRefreshReason::RefreshRequested => {
 3426                (InvalidationStrategy::RefreshRequested, None)
 3427            }
 3428        };
 3429
 3430        if let Some(InlaySplice {
 3431            to_remove,
 3432            to_insert,
 3433        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3434            reason_description,
 3435            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3436            invalidate_cache,
 3437            ignore_debounce,
 3438            cx,
 3439        ) {
 3440            self.splice_inlays(to_remove, to_insert, cx);
 3441        }
 3442    }
 3443
 3444    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3445        self.display_map
 3446            .read(cx)
 3447            .current_inlays()
 3448            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3449            .cloned()
 3450            .collect()
 3451    }
 3452
 3453    pub fn excerpts_for_inlay_hints_query(
 3454        &self,
 3455        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3456        cx: &mut ViewContext<Editor>,
 3457    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3458        let Some(project) = self.project.as_ref() else {
 3459            return HashMap::default();
 3460        };
 3461        let project = project.read(cx);
 3462        let multi_buffer = self.buffer().read(cx);
 3463        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3464        let multi_buffer_visible_start = self
 3465            .scroll_manager
 3466            .anchor()
 3467            .anchor
 3468            .to_point(&multi_buffer_snapshot);
 3469        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3470            multi_buffer_visible_start
 3471                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3472            Bias::Left,
 3473        );
 3474        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3475        multi_buffer
 3476            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3477            .into_iter()
 3478            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3479            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3480                let buffer = buffer_handle.read(cx);
 3481                let buffer_file = project::File::from_dyn(buffer.file())?;
 3482                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3483                let worktree_entry = buffer_worktree
 3484                    .read(cx)
 3485                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3486                if worktree_entry.is_ignored {
 3487                    return None;
 3488                }
 3489
 3490                let language = buffer.language()?;
 3491                if let Some(restrict_to_languages) = restrict_to_languages {
 3492                    if !restrict_to_languages.contains(language) {
 3493                        return None;
 3494                    }
 3495                }
 3496                Some((
 3497                    excerpt_id,
 3498                    (
 3499                        buffer_handle,
 3500                        buffer.version().clone(),
 3501                        excerpt_visible_range,
 3502                    ),
 3503                ))
 3504            })
 3505            .collect()
 3506    }
 3507
 3508    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3509        TextLayoutDetails {
 3510            text_system: cx.text_system().clone(),
 3511            editor_style: self.style.clone().unwrap(),
 3512            rem_size: cx.rem_size(),
 3513            scroll_anchor: self.scroll_manager.anchor(),
 3514            visible_rows: self.visible_line_count(),
 3515            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3516        }
 3517    }
 3518
 3519    fn splice_inlays(
 3520        &self,
 3521        to_remove: Vec<InlayId>,
 3522        to_insert: Vec<Inlay>,
 3523        cx: &mut ViewContext<Self>,
 3524    ) {
 3525        self.display_map.update(cx, |display_map, cx| {
 3526            display_map.splice_inlays(to_remove, to_insert, cx)
 3527        });
 3528        cx.notify();
 3529    }
 3530
 3531    fn trigger_on_type_formatting(
 3532        &self,
 3533        input: String,
 3534        cx: &mut ViewContext<Self>,
 3535    ) -> Option<Task<Result<()>>> {
 3536        if input.len() != 1 {
 3537            return None;
 3538        }
 3539
 3540        let project = self.project.as_ref()?;
 3541        let position = self.selections.newest_anchor().head();
 3542        let (buffer, buffer_position) = self
 3543            .buffer
 3544            .read(cx)
 3545            .text_anchor_for_position(position, cx)?;
 3546
 3547        let settings = language_settings::language_settings(
 3548            buffer
 3549                .read(cx)
 3550                .language_at(buffer_position)
 3551                .map(|l| l.name()),
 3552            buffer.read(cx).file(),
 3553            cx,
 3554        );
 3555        if !settings.use_on_type_format {
 3556            return None;
 3557        }
 3558
 3559        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3560        // hence we do LSP request & edit on host side only — add formats to host's history.
 3561        let push_to_lsp_host_history = true;
 3562        // If this is not the host, append its history with new edits.
 3563        let push_to_client_history = project.read(cx).is_via_collab();
 3564
 3565        let on_type_formatting = project.update(cx, |project, cx| {
 3566            project.on_type_format(
 3567                buffer.clone(),
 3568                buffer_position,
 3569                input,
 3570                push_to_lsp_host_history,
 3571                cx,
 3572            )
 3573        });
 3574        Some(cx.spawn(|editor, mut cx| async move {
 3575            if let Some(transaction) = on_type_formatting.await? {
 3576                if push_to_client_history {
 3577                    buffer
 3578                        .update(&mut cx, |buffer, _| {
 3579                            buffer.push_transaction(transaction, Instant::now());
 3580                        })
 3581                        .ok();
 3582                }
 3583                editor.update(&mut cx, |editor, cx| {
 3584                    editor.refresh_document_highlights(cx);
 3585                })?;
 3586            }
 3587            Ok(())
 3588        }))
 3589    }
 3590
 3591    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3592        if self.pending_rename.is_some() {
 3593            return;
 3594        }
 3595
 3596        let Some(provider) = self.completion_provider.as_ref() else {
 3597            return;
 3598        };
 3599
 3600        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 3601            return;
 3602        }
 3603
 3604        let position = self.selections.newest_anchor().head();
 3605        let (buffer, buffer_position) =
 3606            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3607                output
 3608            } else {
 3609                return;
 3610            };
 3611        let show_completion_documentation = buffer
 3612            .read(cx)
 3613            .snapshot()
 3614            .settings_at(buffer_position, cx)
 3615            .show_completion_documentation;
 3616
 3617        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3618
 3619        let aside_was_displayed = match self.context_menu.read().deref() {
 3620            Some(CodeContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
 3621            _ => false,
 3622        };
 3623        let trigger_kind = match &options.trigger {
 3624            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3625                CompletionTriggerKind::TRIGGER_CHARACTER
 3626            }
 3627            _ => CompletionTriggerKind::INVOKED,
 3628        };
 3629        let completion_context = CompletionContext {
 3630            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3631                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3632                    Some(String::from(trigger))
 3633                } else {
 3634                    None
 3635                }
 3636            }),
 3637            trigger_kind,
 3638        };
 3639        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3640        let sort_completions = provider.sort_completions();
 3641
 3642        let id = post_inc(&mut self.next_completion_id);
 3643        let task = cx.spawn(|editor, mut cx| {
 3644            async move {
 3645                editor.update(&mut cx, |this, _| {
 3646                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3647                })?;
 3648                let completions = completions.await.log_err();
 3649                let menu = if let Some(completions) = completions {
 3650                    let mut menu = CompletionsMenu::new(
 3651                        id,
 3652                        sort_completions,
 3653                        show_completion_documentation,
 3654                        position,
 3655                        buffer.clone(),
 3656                        completions.into(),
 3657                        aside_was_displayed,
 3658                    );
 3659                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3660                        .await;
 3661
 3662                    if menu.matches.is_empty() {
 3663                        None
 3664                    } else {
 3665                        Some(menu)
 3666                    }
 3667                } else {
 3668                    None
 3669                };
 3670
 3671                editor.update(&mut cx, |editor, cx| {
 3672                    let mut context_menu = editor.context_menu.write();
 3673                    match context_menu.as_ref() {
 3674                        None => {}
 3675
 3676                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3677                            if prev_menu.id > id {
 3678                                return;
 3679                            }
 3680                        }
 3681
 3682                        _ => return,
 3683                    }
 3684
 3685                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3686                        let mut menu = menu.unwrap();
 3687                        menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
 3688                        *context_menu = Some(CodeContextMenu::Completions(menu));
 3689                        drop(context_menu);
 3690                        editor.discard_inline_completion(false, cx);
 3691                        cx.notify();
 3692                    } else if editor.completion_tasks.len() <= 1 {
 3693                        // If there are no more completion tasks and the last menu was
 3694                        // empty, we should hide it. If it was already hidden, we should
 3695                        // also show the copilot completion when available.
 3696                        drop(context_menu);
 3697                        if editor.hide_context_menu(cx).is_none() {
 3698                            editor.update_visible_inline_completion(cx);
 3699                        }
 3700                    }
 3701                })?;
 3702
 3703                Ok::<_, anyhow::Error>(())
 3704            }
 3705            .log_err()
 3706        });
 3707
 3708        self.completion_tasks.push((id, task));
 3709    }
 3710
 3711    pub fn confirm_completion(
 3712        &mut self,
 3713        action: &ConfirmCompletion,
 3714        cx: &mut ViewContext<Self>,
 3715    ) -> Option<Task<Result<()>>> {
 3716        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3717    }
 3718
 3719    pub fn compose_completion(
 3720        &mut self,
 3721        action: &ComposeCompletion,
 3722        cx: &mut ViewContext<Self>,
 3723    ) -> Option<Task<Result<()>>> {
 3724        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3725    }
 3726
 3727    fn do_completion(
 3728        &mut self,
 3729        item_ix: Option<usize>,
 3730        intent: CompletionIntent,
 3731        cx: &mut ViewContext<Editor>,
 3732    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3733        use language::ToOffset as _;
 3734
 3735        let completions_menu =
 3736            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3737                menu
 3738            } else {
 3739                return None;
 3740            };
 3741
 3742        let mat = completions_menu
 3743            .matches
 3744            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3745        let buffer_handle = completions_menu.buffer;
 3746        let completions = completions_menu.completions.read();
 3747        let completion = completions.get(mat.candidate_id)?;
 3748        cx.stop_propagation();
 3749
 3750        let snippet;
 3751        let text;
 3752
 3753        if completion.is_snippet() {
 3754            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3755            text = snippet.as_ref().unwrap().text.clone();
 3756        } else {
 3757            snippet = None;
 3758            text = completion.new_text.clone();
 3759        };
 3760        let selections = self.selections.all::<usize>(cx);
 3761        let buffer = buffer_handle.read(cx);
 3762        let old_range = completion.old_range.to_offset(buffer);
 3763        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3764
 3765        let newest_selection = self.selections.newest_anchor();
 3766        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3767            return None;
 3768        }
 3769
 3770        let lookbehind = newest_selection
 3771            .start
 3772            .text_anchor
 3773            .to_offset(buffer)
 3774            .saturating_sub(old_range.start);
 3775        let lookahead = old_range
 3776            .end
 3777            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3778        let mut common_prefix_len = old_text
 3779            .bytes()
 3780            .zip(text.bytes())
 3781            .take_while(|(a, b)| a == b)
 3782            .count();
 3783
 3784        let snapshot = self.buffer.read(cx).snapshot(cx);
 3785        let mut range_to_replace: Option<Range<isize>> = None;
 3786        let mut ranges = Vec::new();
 3787        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3788        for selection in &selections {
 3789            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3790                let start = selection.start.saturating_sub(lookbehind);
 3791                let end = selection.end + lookahead;
 3792                if selection.id == newest_selection.id {
 3793                    range_to_replace = Some(
 3794                        ((start + common_prefix_len) as isize - selection.start as isize)
 3795                            ..(end as isize - selection.start as isize),
 3796                    );
 3797                }
 3798                ranges.push(start + common_prefix_len..end);
 3799            } else {
 3800                common_prefix_len = 0;
 3801                ranges.clear();
 3802                ranges.extend(selections.iter().map(|s| {
 3803                    if s.id == newest_selection.id {
 3804                        range_to_replace = Some(
 3805                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3806                                - selection.start as isize
 3807                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3808                                    - selection.start as isize,
 3809                        );
 3810                        old_range.clone()
 3811                    } else {
 3812                        s.start..s.end
 3813                    }
 3814                }));
 3815                break;
 3816            }
 3817            if !self.linked_edit_ranges.is_empty() {
 3818                let start_anchor = snapshot.anchor_before(selection.head());
 3819                let end_anchor = snapshot.anchor_after(selection.tail());
 3820                if let Some(ranges) = self
 3821                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3822                {
 3823                    for (buffer, edits) in ranges {
 3824                        linked_edits.entry(buffer.clone()).or_default().extend(
 3825                            edits
 3826                                .into_iter()
 3827                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3828                        );
 3829                    }
 3830                }
 3831            }
 3832        }
 3833        let text = &text[common_prefix_len..];
 3834
 3835        cx.emit(EditorEvent::InputHandled {
 3836            utf16_range_to_replace: range_to_replace,
 3837            text: text.into(),
 3838        });
 3839
 3840        self.transact(cx, |this, cx| {
 3841            if let Some(mut snippet) = snippet {
 3842                snippet.text = text.to_string();
 3843                for tabstop in snippet
 3844                    .tabstops
 3845                    .iter_mut()
 3846                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3847                {
 3848                    tabstop.start -= common_prefix_len as isize;
 3849                    tabstop.end -= common_prefix_len as isize;
 3850                }
 3851
 3852                this.insert_snippet(&ranges, snippet, cx).log_err();
 3853            } else {
 3854                this.buffer.update(cx, |buffer, cx| {
 3855                    buffer.edit(
 3856                        ranges.iter().map(|range| (range.clone(), text)),
 3857                        this.autoindent_mode.clone(),
 3858                        cx,
 3859                    );
 3860                });
 3861            }
 3862            for (buffer, edits) in linked_edits {
 3863                buffer.update(cx, |buffer, cx| {
 3864                    let snapshot = buffer.snapshot();
 3865                    let edits = edits
 3866                        .into_iter()
 3867                        .map(|(range, text)| {
 3868                            use text::ToPoint as TP;
 3869                            let end_point = TP::to_point(&range.end, &snapshot);
 3870                            let start_point = TP::to_point(&range.start, &snapshot);
 3871                            (start_point..end_point, text)
 3872                        })
 3873                        .sorted_by_key(|(range, _)| range.start)
 3874                        .collect::<Vec<_>>();
 3875                    buffer.edit(edits, None, cx);
 3876                })
 3877            }
 3878
 3879            this.refresh_inline_completion(true, false, cx);
 3880        });
 3881
 3882        let show_new_completions_on_confirm = completion
 3883            .confirm
 3884            .as_ref()
 3885            .map_or(false, |confirm| confirm(intent, cx));
 3886        if show_new_completions_on_confirm {
 3887            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3888        }
 3889
 3890        let provider = self.completion_provider.as_ref()?;
 3891        let apply_edits = provider.apply_additional_edits_for_completion(
 3892            buffer_handle,
 3893            completion.clone(),
 3894            true,
 3895            cx,
 3896        );
 3897
 3898        let editor_settings = EditorSettings::get_global(cx);
 3899        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3900            // After the code completion is finished, users often want to know what signatures are needed.
 3901            // so we should automatically call signature_help
 3902            self.show_signature_help(&ShowSignatureHelp, cx);
 3903        }
 3904
 3905        Some(cx.foreground_executor().spawn(async move {
 3906            apply_edits.await?;
 3907            Ok(())
 3908        }))
 3909    }
 3910
 3911    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3912        let mut context_menu = self.context_menu.write();
 3913        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 3914            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 3915                // Toggle if we're selecting the same one
 3916                *context_menu = None;
 3917                cx.notify();
 3918                return;
 3919            } else {
 3920                // Otherwise, clear it and start a new one
 3921                *context_menu = None;
 3922                cx.notify();
 3923            }
 3924        }
 3925        drop(context_menu);
 3926        let snapshot = self.snapshot(cx);
 3927        let deployed_from_indicator = action.deployed_from_indicator;
 3928        let mut task = self.code_actions_task.take();
 3929        let action = action.clone();
 3930        cx.spawn(|editor, mut cx| async move {
 3931            while let Some(prev_task) = task {
 3932                prev_task.await.log_err();
 3933                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 3934            }
 3935
 3936            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 3937                if editor.focus_handle.is_focused(cx) {
 3938                    let multibuffer_point = action
 3939                        .deployed_from_indicator
 3940                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 3941                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 3942                    let (buffer, buffer_row) = snapshot
 3943                        .buffer_snapshot
 3944                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 3945                        .and_then(|(buffer_snapshot, range)| {
 3946                            editor
 3947                                .buffer
 3948                                .read(cx)
 3949                                .buffer(buffer_snapshot.remote_id())
 3950                                .map(|buffer| (buffer, range.start.row))
 3951                        })?;
 3952                    let (_, code_actions) = editor
 3953                        .available_code_actions
 3954                        .clone()
 3955                        .and_then(|(location, code_actions)| {
 3956                            let snapshot = location.buffer.read(cx).snapshot();
 3957                            let point_range = location.range.to_point(&snapshot);
 3958                            let point_range = point_range.start.row..=point_range.end.row;
 3959                            if point_range.contains(&buffer_row) {
 3960                                Some((location, code_actions))
 3961                            } else {
 3962                                None
 3963                            }
 3964                        })
 3965                        .unzip();
 3966                    let buffer_id = buffer.read(cx).remote_id();
 3967                    let tasks = editor
 3968                        .tasks
 3969                        .get(&(buffer_id, buffer_row))
 3970                        .map(|t| Arc::new(t.to_owned()));
 3971                    if tasks.is_none() && code_actions.is_none() {
 3972                        return None;
 3973                    }
 3974
 3975                    editor.completion_tasks.clear();
 3976                    editor.discard_inline_completion(false, cx);
 3977                    let task_context =
 3978                        tasks
 3979                            .as_ref()
 3980                            .zip(editor.project.clone())
 3981                            .map(|(tasks, project)| {
 3982                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 3983                            });
 3984
 3985                    Some(cx.spawn(|editor, mut cx| async move {
 3986                        let task_context = match task_context {
 3987                            Some(task_context) => task_context.await,
 3988                            None => None,
 3989                        };
 3990                        let resolved_tasks =
 3991                            tasks.zip(task_context).map(|(tasks, task_context)| {
 3992                                Arc::new(ResolvedTasks {
 3993                                    templates: tasks.resolve(&task_context).collect(),
 3994                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 3995                                        multibuffer_point.row,
 3996                                        tasks.column,
 3997                                    )),
 3998                                })
 3999                            });
 4000                        let spawn_straight_away = resolved_tasks
 4001                            .as_ref()
 4002                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4003                            && code_actions
 4004                                .as_ref()
 4005                                .map_or(true, |actions| actions.is_empty());
 4006                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4007                            *editor.context_menu.write() =
 4008                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4009                                    buffer,
 4010                                    actions: CodeActionContents {
 4011                                        tasks: resolved_tasks,
 4012                                        actions: code_actions,
 4013                                    },
 4014                                    selected_item: Default::default(),
 4015                                    scroll_handle: UniformListScrollHandle::default(),
 4016                                    deployed_from_indicator,
 4017                                }));
 4018                            if spawn_straight_away {
 4019                                if let Some(task) = editor.confirm_code_action(
 4020                                    &ConfirmCodeAction { item_ix: Some(0) },
 4021                                    cx,
 4022                                ) {
 4023                                    cx.notify();
 4024                                    return task;
 4025                                }
 4026                            }
 4027                            cx.notify();
 4028                            Task::ready(Ok(()))
 4029                        }) {
 4030                            task.await
 4031                        } else {
 4032                            Ok(())
 4033                        }
 4034                    }))
 4035                } else {
 4036                    Some(Task::ready(Ok(())))
 4037                }
 4038            })?;
 4039            if let Some(task) = spawned_test_task {
 4040                task.await?;
 4041            }
 4042
 4043            Ok::<_, anyhow::Error>(())
 4044        })
 4045        .detach_and_log_err(cx);
 4046    }
 4047
 4048    pub fn confirm_code_action(
 4049        &mut self,
 4050        action: &ConfirmCodeAction,
 4051        cx: &mut ViewContext<Self>,
 4052    ) -> Option<Task<Result<()>>> {
 4053        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4054            menu
 4055        } else {
 4056            return None;
 4057        };
 4058        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4059        let action = actions_menu.actions.get(action_ix)?;
 4060        let title = action.label();
 4061        let buffer = actions_menu.buffer;
 4062        let workspace = self.workspace()?;
 4063
 4064        match action {
 4065            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4066                workspace.update(cx, |workspace, cx| {
 4067                    workspace::tasks::schedule_resolved_task(
 4068                        workspace,
 4069                        task_source_kind,
 4070                        resolved_task,
 4071                        false,
 4072                        cx,
 4073                    );
 4074
 4075                    Some(Task::ready(Ok(())))
 4076                })
 4077            }
 4078            CodeActionsItem::CodeAction {
 4079                excerpt_id,
 4080                action,
 4081                provider,
 4082            } => {
 4083                let apply_code_action =
 4084                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4085                let workspace = workspace.downgrade();
 4086                Some(cx.spawn(|editor, cx| async move {
 4087                    let project_transaction = apply_code_action.await?;
 4088                    Self::open_project_transaction(
 4089                        &editor,
 4090                        workspace,
 4091                        project_transaction,
 4092                        title,
 4093                        cx,
 4094                    )
 4095                    .await
 4096                }))
 4097            }
 4098        }
 4099    }
 4100
 4101    pub async fn open_project_transaction(
 4102        this: &WeakView<Editor>,
 4103        workspace: WeakView<Workspace>,
 4104        transaction: ProjectTransaction,
 4105        title: String,
 4106        mut cx: AsyncWindowContext,
 4107    ) -> Result<()> {
 4108        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4109        cx.update(|cx| {
 4110            entries.sort_unstable_by_key(|(buffer, _)| {
 4111                buffer.read(cx).file().map(|f| f.path().clone())
 4112            });
 4113        })?;
 4114
 4115        // If the project transaction's edits are all contained within this editor, then
 4116        // avoid opening a new editor to display them.
 4117
 4118        if let Some((buffer, transaction)) = entries.first() {
 4119            if entries.len() == 1 {
 4120                let excerpt = this.update(&mut cx, |editor, cx| {
 4121                    editor
 4122                        .buffer()
 4123                        .read(cx)
 4124                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4125                })?;
 4126                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4127                    if excerpted_buffer == *buffer {
 4128                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4129                            let excerpt_range = excerpt_range.to_offset(buffer);
 4130                            buffer
 4131                                .edited_ranges_for_transaction::<usize>(transaction)
 4132                                .all(|range| {
 4133                                    excerpt_range.start <= range.start
 4134                                        && excerpt_range.end >= range.end
 4135                                })
 4136                        })?;
 4137
 4138                        if all_edits_within_excerpt {
 4139                            return Ok(());
 4140                        }
 4141                    }
 4142                }
 4143            }
 4144        } else {
 4145            return Ok(());
 4146        }
 4147
 4148        let mut ranges_to_highlight = Vec::new();
 4149        let excerpt_buffer = cx.new_model(|cx| {
 4150            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4151            for (buffer_handle, transaction) in &entries {
 4152                let buffer = buffer_handle.read(cx);
 4153                ranges_to_highlight.extend(
 4154                    multibuffer.push_excerpts_with_context_lines(
 4155                        buffer_handle.clone(),
 4156                        buffer
 4157                            .edited_ranges_for_transaction::<usize>(transaction)
 4158                            .collect(),
 4159                        DEFAULT_MULTIBUFFER_CONTEXT,
 4160                        cx,
 4161                    ),
 4162                );
 4163            }
 4164            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4165            multibuffer
 4166        })?;
 4167
 4168        workspace.update(&mut cx, |workspace, cx| {
 4169            let project = workspace.project().clone();
 4170            let editor =
 4171                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4172            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4173            editor.update(cx, |editor, cx| {
 4174                editor.highlight_background::<Self>(
 4175                    &ranges_to_highlight,
 4176                    |theme| theme.editor_highlighted_line_background,
 4177                    cx,
 4178                );
 4179            });
 4180        })?;
 4181
 4182        Ok(())
 4183    }
 4184
 4185    pub fn clear_code_action_providers(&mut self) {
 4186        self.code_action_providers.clear();
 4187        self.available_code_actions.take();
 4188    }
 4189
 4190    pub fn push_code_action_provider(
 4191        &mut self,
 4192        provider: Arc<dyn CodeActionProvider>,
 4193        cx: &mut ViewContext<Self>,
 4194    ) {
 4195        self.code_action_providers.push(provider);
 4196        self.refresh_code_actions(cx);
 4197    }
 4198
 4199    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4200        let buffer = self.buffer.read(cx);
 4201        let newest_selection = self.selections.newest_anchor().clone();
 4202        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4203        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4204        if start_buffer != end_buffer {
 4205            return None;
 4206        }
 4207
 4208        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4209            cx.background_executor()
 4210                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4211                .await;
 4212
 4213            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4214                let providers = this.code_action_providers.clone();
 4215                let tasks = this
 4216                    .code_action_providers
 4217                    .iter()
 4218                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4219                    .collect::<Vec<_>>();
 4220                (providers, tasks)
 4221            })?;
 4222
 4223            let mut actions = Vec::new();
 4224            for (provider, provider_actions) in
 4225                providers.into_iter().zip(future::join_all(tasks).await)
 4226            {
 4227                if let Some(provider_actions) = provider_actions.log_err() {
 4228                    actions.extend(provider_actions.into_iter().map(|action| {
 4229                        AvailableCodeAction {
 4230                            excerpt_id: newest_selection.start.excerpt_id,
 4231                            action,
 4232                            provider: provider.clone(),
 4233                        }
 4234                    }));
 4235                }
 4236            }
 4237
 4238            this.update(&mut cx, |this, cx| {
 4239                this.available_code_actions = if actions.is_empty() {
 4240                    None
 4241                } else {
 4242                    Some((
 4243                        Location {
 4244                            buffer: start_buffer,
 4245                            range: start..end,
 4246                        },
 4247                        actions.into(),
 4248                    ))
 4249                };
 4250                cx.notify();
 4251            })
 4252        }));
 4253        None
 4254    }
 4255
 4256    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4257        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4258            self.show_git_blame_inline = false;
 4259
 4260            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4261                cx.background_executor().timer(delay).await;
 4262
 4263                this.update(&mut cx, |this, cx| {
 4264                    this.show_git_blame_inline = true;
 4265                    cx.notify();
 4266                })
 4267                .log_err();
 4268            }));
 4269        }
 4270    }
 4271
 4272    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4273        if self.pending_rename.is_some() {
 4274            return None;
 4275        }
 4276
 4277        let provider = self.semantics_provider.clone()?;
 4278        let buffer = self.buffer.read(cx);
 4279        let newest_selection = self.selections.newest_anchor().clone();
 4280        let cursor_position = newest_selection.head();
 4281        let (cursor_buffer, cursor_buffer_position) =
 4282            buffer.text_anchor_for_position(cursor_position, cx)?;
 4283        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4284        if cursor_buffer != tail_buffer {
 4285            return None;
 4286        }
 4287
 4288        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4289            cx.background_executor()
 4290                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4291                .await;
 4292
 4293            let highlights = if let Some(highlights) = cx
 4294                .update(|cx| {
 4295                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4296                })
 4297                .ok()
 4298                .flatten()
 4299            {
 4300                highlights.await.log_err()
 4301            } else {
 4302                None
 4303            };
 4304
 4305            if let Some(highlights) = highlights {
 4306                this.update(&mut cx, |this, cx| {
 4307                    if this.pending_rename.is_some() {
 4308                        return;
 4309                    }
 4310
 4311                    let buffer_id = cursor_position.buffer_id;
 4312                    let buffer = this.buffer.read(cx);
 4313                    if !buffer
 4314                        .text_anchor_for_position(cursor_position, cx)
 4315                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4316                    {
 4317                        return;
 4318                    }
 4319
 4320                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4321                    let mut write_ranges = Vec::new();
 4322                    let mut read_ranges = Vec::new();
 4323                    for highlight in highlights {
 4324                        for (excerpt_id, excerpt_range) in
 4325                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4326                        {
 4327                            let start = highlight
 4328                                .range
 4329                                .start
 4330                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4331                            let end = highlight
 4332                                .range
 4333                                .end
 4334                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4335                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4336                                continue;
 4337                            }
 4338
 4339                            let range = Anchor {
 4340                                buffer_id,
 4341                                excerpt_id,
 4342                                text_anchor: start,
 4343                            }..Anchor {
 4344                                buffer_id,
 4345                                excerpt_id,
 4346                                text_anchor: end,
 4347                            };
 4348                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4349                                write_ranges.push(range);
 4350                            } else {
 4351                                read_ranges.push(range);
 4352                            }
 4353                        }
 4354                    }
 4355
 4356                    this.highlight_background::<DocumentHighlightRead>(
 4357                        &read_ranges,
 4358                        |theme| theme.editor_document_highlight_read_background,
 4359                        cx,
 4360                    );
 4361                    this.highlight_background::<DocumentHighlightWrite>(
 4362                        &write_ranges,
 4363                        |theme| theme.editor_document_highlight_write_background,
 4364                        cx,
 4365                    );
 4366                    cx.notify();
 4367                })
 4368                .log_err();
 4369            }
 4370        }));
 4371        None
 4372    }
 4373
 4374    pub fn refresh_inline_completion(
 4375        &mut self,
 4376        debounce: bool,
 4377        user_requested: bool,
 4378        cx: &mut ViewContext<Self>,
 4379    ) -> Option<()> {
 4380        let provider = self.inline_completion_provider()?;
 4381        let cursor = self.selections.newest_anchor().head();
 4382        let (buffer, cursor_buffer_position) =
 4383            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4384
 4385        if !user_requested
 4386            && (!self.enable_inline_completions
 4387                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4388                || !self.is_focused(cx))
 4389        {
 4390            self.discard_inline_completion(false, cx);
 4391            return None;
 4392        }
 4393
 4394        self.update_visible_inline_completion(cx);
 4395        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4396        Some(())
 4397    }
 4398
 4399    fn cycle_inline_completion(
 4400        &mut self,
 4401        direction: Direction,
 4402        cx: &mut ViewContext<Self>,
 4403    ) -> Option<()> {
 4404        let provider = self.inline_completion_provider()?;
 4405        let cursor = self.selections.newest_anchor().head();
 4406        let (buffer, cursor_buffer_position) =
 4407            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4408        if !self.enable_inline_completions
 4409            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4410        {
 4411            return None;
 4412        }
 4413
 4414        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4415        self.update_visible_inline_completion(cx);
 4416
 4417        Some(())
 4418    }
 4419
 4420    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4421        if !self.has_active_inline_completion() {
 4422            self.refresh_inline_completion(false, true, cx);
 4423            return;
 4424        }
 4425
 4426        self.update_visible_inline_completion(cx);
 4427    }
 4428
 4429    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4430        self.show_cursor_names(cx);
 4431    }
 4432
 4433    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4434        self.show_cursor_names = true;
 4435        cx.notify();
 4436        cx.spawn(|this, mut cx| async move {
 4437            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4438            this.update(&mut cx, |this, cx| {
 4439                this.show_cursor_names = false;
 4440                cx.notify()
 4441            })
 4442            .ok()
 4443        })
 4444        .detach();
 4445    }
 4446
 4447    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4448        if self.has_active_inline_completion() {
 4449            self.cycle_inline_completion(Direction::Next, cx);
 4450        } else {
 4451            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4452            if is_copilot_disabled {
 4453                cx.propagate();
 4454            }
 4455        }
 4456    }
 4457
 4458    pub fn previous_inline_completion(
 4459        &mut self,
 4460        _: &PreviousInlineCompletion,
 4461        cx: &mut ViewContext<Self>,
 4462    ) {
 4463        if self.has_active_inline_completion() {
 4464            self.cycle_inline_completion(Direction::Prev, cx);
 4465        } else {
 4466            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4467            if is_copilot_disabled {
 4468                cx.propagate();
 4469            }
 4470        }
 4471    }
 4472
 4473    pub fn accept_inline_completion(
 4474        &mut self,
 4475        _: &AcceptInlineCompletion,
 4476        cx: &mut ViewContext<Self>,
 4477    ) {
 4478        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4479            return;
 4480        };
 4481
 4482        self.report_inline_completion_event(true, cx);
 4483
 4484        match &active_inline_completion.completion {
 4485            InlineCompletion::Move(position) => {
 4486                let position = *position;
 4487                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4488                    selections.select_anchor_ranges([position..position]);
 4489                });
 4490            }
 4491            InlineCompletion::Edit(edits) => {
 4492                if let Some(provider) = self.inline_completion_provider() {
 4493                    provider.accept(cx);
 4494                }
 4495
 4496                let snapshot = self.buffer.read(cx).snapshot(cx);
 4497                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4498
 4499                self.buffer.update(cx, |buffer, cx| {
 4500                    buffer.edit(edits.iter().cloned(), None, cx)
 4501                });
 4502
 4503                self.change_selections(None, cx, |s| {
 4504                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4505                });
 4506
 4507                self.update_visible_inline_completion(cx);
 4508                if self.active_inline_completion.is_none() {
 4509                    self.refresh_inline_completion(true, true, cx);
 4510                }
 4511
 4512                cx.notify();
 4513            }
 4514        }
 4515    }
 4516
 4517    pub fn accept_partial_inline_completion(
 4518        &mut self,
 4519        _: &AcceptPartialInlineCompletion,
 4520        cx: &mut ViewContext<Self>,
 4521    ) {
 4522        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4523            return;
 4524        };
 4525        if self.selections.count() != 1 {
 4526            return;
 4527        }
 4528
 4529        self.report_inline_completion_event(true, cx);
 4530
 4531        match &active_inline_completion.completion {
 4532            InlineCompletion::Move(position) => {
 4533                let position = *position;
 4534                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4535                    selections.select_anchor_ranges([position..position]);
 4536                });
 4537            }
 4538            InlineCompletion::Edit(edits) => {
 4539                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4540                    let text = edits[0].1.as_str();
 4541                    let mut partial_completion = text
 4542                        .chars()
 4543                        .by_ref()
 4544                        .take_while(|c| c.is_alphabetic())
 4545                        .collect::<String>();
 4546                    if partial_completion.is_empty() {
 4547                        partial_completion = text
 4548                            .chars()
 4549                            .by_ref()
 4550                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4551                            .collect::<String>();
 4552                    }
 4553
 4554                    cx.emit(EditorEvent::InputHandled {
 4555                        utf16_range_to_replace: None,
 4556                        text: partial_completion.clone().into(),
 4557                    });
 4558
 4559                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4560
 4561                    self.refresh_inline_completion(true, true, cx);
 4562                    cx.notify();
 4563                }
 4564            }
 4565        }
 4566    }
 4567
 4568    fn discard_inline_completion(
 4569        &mut self,
 4570        should_report_inline_completion_event: bool,
 4571        cx: &mut ViewContext<Self>,
 4572    ) -> bool {
 4573        if should_report_inline_completion_event {
 4574            self.report_inline_completion_event(false, cx);
 4575        }
 4576
 4577        if let Some(provider) = self.inline_completion_provider() {
 4578            provider.discard(cx);
 4579        }
 4580
 4581        self.take_active_inline_completion(cx).is_some()
 4582    }
 4583
 4584    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4585        let Some(provider) = self.inline_completion_provider() else {
 4586            return;
 4587        };
 4588        let Some(project) = self.project.as_ref() else {
 4589            return;
 4590        };
 4591        let Some((_, buffer, _)) = self
 4592            .buffer
 4593            .read(cx)
 4594            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4595        else {
 4596            return;
 4597        };
 4598
 4599        let project = project.read(cx);
 4600        let extension = buffer
 4601            .read(cx)
 4602            .file()
 4603            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4604        project.client().telemetry().report_inline_completion_event(
 4605            provider.name().into(),
 4606            accepted,
 4607            extension,
 4608        );
 4609    }
 4610
 4611    pub fn has_active_inline_completion(&self) -> bool {
 4612        self.active_inline_completion.is_some()
 4613    }
 4614
 4615    fn take_active_inline_completion(
 4616        &mut self,
 4617        cx: &mut ViewContext<Self>,
 4618    ) -> Option<InlineCompletion> {
 4619        let active_inline_completion = self.active_inline_completion.take()?;
 4620        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4621        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4622        Some(active_inline_completion.completion)
 4623    }
 4624
 4625    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4626        let selection = self.selections.newest_anchor();
 4627        let cursor = selection.head();
 4628        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4629        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4630        let excerpt_id = cursor.excerpt_id;
 4631
 4632        if self.context_menu.read().is_some()
 4633            || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion())
 4634            || !offset_selection.is_empty()
 4635            || self
 4636                .active_inline_completion
 4637                .as_ref()
 4638                .map_or(false, |completion| {
 4639                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4640                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4641                    !invalidation_range.contains(&offset_selection.head())
 4642                })
 4643        {
 4644            self.discard_inline_completion(false, cx);
 4645            return None;
 4646        }
 4647
 4648        self.take_active_inline_completion(cx);
 4649        let provider = self.inline_completion_provider()?;
 4650
 4651        let (buffer, cursor_buffer_position) =
 4652            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4653
 4654        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4655        let edits = completion
 4656            .edits
 4657            .into_iter()
 4658            .map(|(range, new_text)| {
 4659                (
 4660                    multibuffer
 4661                        .anchor_in_excerpt(excerpt_id, range.start)
 4662                        .unwrap()
 4663                        ..multibuffer
 4664                            .anchor_in_excerpt(excerpt_id, range.end)
 4665                            .unwrap(),
 4666                    new_text,
 4667                )
 4668            })
 4669            .collect::<Vec<_>>();
 4670        if edits.is_empty() {
 4671            return None;
 4672        }
 4673
 4674        let first_edit_start = edits.first().unwrap().0.start;
 4675        let edit_start_row = first_edit_start
 4676            .to_point(&multibuffer)
 4677            .row
 4678            .saturating_sub(2);
 4679
 4680        let last_edit_end = edits.last().unwrap().0.end;
 4681        let edit_end_row = cmp::min(
 4682            multibuffer.max_point().row,
 4683            last_edit_end.to_point(&multibuffer).row + 2,
 4684        );
 4685
 4686        let cursor_row = cursor.to_point(&multibuffer).row;
 4687
 4688        let mut inlay_ids = Vec::new();
 4689        let invalidation_row_range;
 4690        let completion;
 4691        if cursor_row < edit_start_row {
 4692            invalidation_row_range = cursor_row..edit_end_row;
 4693            completion = InlineCompletion::Move(first_edit_start);
 4694        } else if cursor_row > edit_end_row {
 4695            invalidation_row_range = edit_start_row..cursor_row;
 4696            completion = InlineCompletion::Move(first_edit_start);
 4697        } else {
 4698            if edits
 4699                .iter()
 4700                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4701            {
 4702                let mut inlays = Vec::new();
 4703                for (range, new_text) in &edits {
 4704                    let inlay = Inlay::suggestion(
 4705                        post_inc(&mut self.next_inlay_id),
 4706                        range.start,
 4707                        new_text.as_str(),
 4708                    );
 4709                    inlay_ids.push(inlay.id);
 4710                    inlays.push(inlay);
 4711                }
 4712
 4713                self.splice_inlays(vec![], inlays, cx);
 4714            } else {
 4715                let background_color = cx.theme().status().deleted_background;
 4716                self.highlight_text::<InlineCompletionHighlight>(
 4717                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4718                    HighlightStyle {
 4719                        background_color: Some(background_color),
 4720                        ..Default::default()
 4721                    },
 4722                    cx,
 4723                );
 4724            }
 4725
 4726            invalidation_row_range = edit_start_row..edit_end_row;
 4727            completion = InlineCompletion::Edit(edits);
 4728        };
 4729
 4730        let invalidation_range = multibuffer
 4731            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4732            ..multibuffer.anchor_after(Point::new(
 4733                invalidation_row_range.end,
 4734                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4735            ));
 4736
 4737        self.active_inline_completion = Some(InlineCompletionState {
 4738            inlay_ids,
 4739            completion,
 4740            invalidation_range,
 4741        });
 4742        cx.notify();
 4743
 4744        Some(())
 4745    }
 4746
 4747    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4748        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4749    }
 4750
 4751    fn render_code_actions_indicator(
 4752        &self,
 4753        _style: &EditorStyle,
 4754        row: DisplayRow,
 4755        is_active: bool,
 4756        cx: &mut ViewContext<Self>,
 4757    ) -> Option<IconButton> {
 4758        if self.available_code_actions.is_some() {
 4759            Some(
 4760                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4761                    .shape(ui::IconButtonShape::Square)
 4762                    .icon_size(IconSize::XSmall)
 4763                    .icon_color(Color::Muted)
 4764                    .selected(is_active)
 4765                    .tooltip({
 4766                        let focus_handle = self.focus_handle.clone();
 4767                        move |cx| {
 4768                            Tooltip::for_action_in(
 4769                                "Toggle Code Actions",
 4770                                &ToggleCodeActions {
 4771                                    deployed_from_indicator: None,
 4772                                },
 4773                                &focus_handle,
 4774                                cx,
 4775                            )
 4776                        }
 4777                    })
 4778                    .on_click(cx.listener(move |editor, _e, cx| {
 4779                        editor.focus(cx);
 4780                        editor.toggle_code_actions(
 4781                            &ToggleCodeActions {
 4782                                deployed_from_indicator: Some(row),
 4783                            },
 4784                            cx,
 4785                        );
 4786                    })),
 4787            )
 4788        } else {
 4789            None
 4790        }
 4791    }
 4792
 4793    fn clear_tasks(&mut self) {
 4794        self.tasks.clear()
 4795    }
 4796
 4797    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4798        if self.tasks.insert(key, value).is_some() {
 4799            // This case should hopefully be rare, but just in case...
 4800            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4801        }
 4802    }
 4803
 4804    fn build_tasks_context(
 4805        project: &Model<Project>,
 4806        buffer: &Model<Buffer>,
 4807        buffer_row: u32,
 4808        tasks: &Arc<RunnableTasks>,
 4809        cx: &mut ViewContext<Self>,
 4810    ) -> Task<Option<task::TaskContext>> {
 4811        let position = Point::new(buffer_row, tasks.column);
 4812        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4813        let location = Location {
 4814            buffer: buffer.clone(),
 4815            range: range_start..range_start,
 4816        };
 4817        // Fill in the environmental variables from the tree-sitter captures
 4818        let mut captured_task_variables = TaskVariables::default();
 4819        for (capture_name, value) in tasks.extra_variables.clone() {
 4820            captured_task_variables.insert(
 4821                task::VariableName::Custom(capture_name.into()),
 4822                value.clone(),
 4823            );
 4824        }
 4825        project.update(cx, |project, cx| {
 4826            project.task_store().update(cx, |task_store, cx| {
 4827                task_store.task_context_for_location(captured_task_variables, location, cx)
 4828            })
 4829        })
 4830    }
 4831
 4832    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4833        let Some((workspace, _)) = self.workspace.clone() else {
 4834            return;
 4835        };
 4836        let Some(project) = self.project.clone() else {
 4837            return;
 4838        };
 4839
 4840        // Try to find a closest, enclosing node using tree-sitter that has a
 4841        // task
 4842        let Some((buffer, buffer_row, tasks)) = self
 4843            .find_enclosing_node_task(cx)
 4844            // Or find the task that's closest in row-distance.
 4845            .or_else(|| self.find_closest_task(cx))
 4846        else {
 4847            return;
 4848        };
 4849
 4850        let reveal_strategy = action.reveal;
 4851        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 4852        cx.spawn(|_, mut cx| async move {
 4853            let context = task_context.await?;
 4854            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 4855
 4856            let resolved = resolved_task.resolved.as_mut()?;
 4857            resolved.reveal = reveal_strategy;
 4858
 4859            workspace
 4860                .update(&mut cx, |workspace, cx| {
 4861                    workspace::tasks::schedule_resolved_task(
 4862                        workspace,
 4863                        task_source_kind,
 4864                        resolved_task,
 4865                        false,
 4866                        cx,
 4867                    );
 4868                })
 4869                .ok()
 4870        })
 4871        .detach();
 4872    }
 4873
 4874    fn find_closest_task(
 4875        &mut self,
 4876        cx: &mut ViewContext<Self>,
 4877    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4878        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 4879
 4880        let ((buffer_id, row), tasks) = self
 4881            .tasks
 4882            .iter()
 4883            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 4884
 4885        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 4886        let tasks = Arc::new(tasks.to_owned());
 4887        Some((buffer, *row, tasks))
 4888    }
 4889
 4890    fn find_enclosing_node_task(
 4891        &mut self,
 4892        cx: &mut ViewContext<Self>,
 4893    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4894        let snapshot = self.buffer.read(cx).snapshot(cx);
 4895        let offset = self.selections.newest::<usize>(cx).head();
 4896        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 4897        let buffer_id = excerpt.buffer().remote_id();
 4898
 4899        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 4900        let mut cursor = layer.node().walk();
 4901
 4902        while cursor.goto_first_child_for_byte(offset).is_some() {
 4903            if cursor.node().end_byte() == offset {
 4904                cursor.goto_next_sibling();
 4905            }
 4906        }
 4907
 4908        // Ascend to the smallest ancestor that contains the range and has a task.
 4909        loop {
 4910            let node = cursor.node();
 4911            let node_range = node.byte_range();
 4912            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 4913
 4914            // Check if this node contains our offset
 4915            if node_range.start <= offset && node_range.end >= offset {
 4916                // If it contains offset, check for task
 4917                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 4918                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 4919                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 4920                }
 4921            }
 4922
 4923            if !cursor.goto_parent() {
 4924                break;
 4925            }
 4926        }
 4927        None
 4928    }
 4929
 4930    fn render_run_indicator(
 4931        &self,
 4932        _style: &EditorStyle,
 4933        is_active: bool,
 4934        row: DisplayRow,
 4935        cx: &mut ViewContext<Self>,
 4936    ) -> IconButton {
 4937        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 4938            .shape(ui::IconButtonShape::Square)
 4939            .icon_size(IconSize::XSmall)
 4940            .icon_color(Color::Muted)
 4941            .selected(is_active)
 4942            .on_click(cx.listener(move |editor, _e, cx| {
 4943                editor.focus(cx);
 4944                editor.toggle_code_actions(
 4945                    &ToggleCodeActions {
 4946                        deployed_from_indicator: Some(row),
 4947                    },
 4948                    cx,
 4949                );
 4950            }))
 4951    }
 4952
 4953    pub fn context_menu_visible(&self) -> bool {
 4954        self.context_menu
 4955            .read()
 4956            .as_ref()
 4957            .map_or(false, |menu| menu.visible())
 4958    }
 4959
 4960    fn render_context_menu(
 4961        &self,
 4962        cursor_position: DisplayPoint,
 4963        style: &EditorStyle,
 4964        max_height: Pixels,
 4965        cx: &mut ViewContext<Editor>,
 4966    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 4967        self.context_menu.read().as_ref().map(|menu| {
 4968            menu.render(
 4969                cursor_position,
 4970                style,
 4971                max_height,
 4972                self.workspace.as_ref().map(|(w, _)| w.clone()),
 4973                cx,
 4974            )
 4975        })
 4976    }
 4977
 4978    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 4979        cx.notify();
 4980        self.completion_tasks.clear();
 4981        let context_menu = self.context_menu.write().take();
 4982        if context_menu.is_some() {
 4983            self.update_visible_inline_completion(cx);
 4984        }
 4985        context_menu
 4986    }
 4987
 4988    fn show_snippet_choices(
 4989        &mut self,
 4990        choices: &Vec<String>,
 4991        selection: Range<Anchor>,
 4992        cx: &mut ViewContext<Self>,
 4993    ) {
 4994        if selection.start.buffer_id.is_none() {
 4995            return;
 4996        }
 4997        let buffer_id = selection.start.buffer_id.unwrap();
 4998        let buffer = self.buffer().read(cx).buffer(buffer_id);
 4999        let id = post_inc(&mut self.next_completion_id);
 5000
 5001        if let Some(buffer) = buffer {
 5002            *self.context_menu.write() = Some(CodeContextMenu::Completions(
 5003                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5004            ));
 5005        }
 5006    }
 5007
 5008    pub fn insert_snippet(
 5009        &mut self,
 5010        insertion_ranges: &[Range<usize>],
 5011        snippet: Snippet,
 5012        cx: &mut ViewContext<Self>,
 5013    ) -> Result<()> {
 5014        struct Tabstop<T> {
 5015            is_end_tabstop: bool,
 5016            ranges: Vec<Range<T>>,
 5017            choices: Option<Vec<String>>,
 5018        }
 5019
 5020        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5021            let snippet_text: Arc<str> = snippet.text.clone().into();
 5022            buffer.edit(
 5023                insertion_ranges
 5024                    .iter()
 5025                    .cloned()
 5026                    .map(|range| (range, snippet_text.clone())),
 5027                Some(AutoindentMode::EachLine),
 5028                cx,
 5029            );
 5030
 5031            let snapshot = &*buffer.read(cx);
 5032            let snippet = &snippet;
 5033            snippet
 5034                .tabstops
 5035                .iter()
 5036                .map(|tabstop| {
 5037                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5038                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5039                    });
 5040                    let mut tabstop_ranges = tabstop
 5041                        .ranges
 5042                        .iter()
 5043                        .flat_map(|tabstop_range| {
 5044                            let mut delta = 0_isize;
 5045                            insertion_ranges.iter().map(move |insertion_range| {
 5046                                let insertion_start = insertion_range.start as isize + delta;
 5047                                delta +=
 5048                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5049
 5050                                let start = ((insertion_start + tabstop_range.start) as usize)
 5051                                    .min(snapshot.len());
 5052                                let end = ((insertion_start + tabstop_range.end) as usize)
 5053                                    .min(snapshot.len());
 5054                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5055                            })
 5056                        })
 5057                        .collect::<Vec<_>>();
 5058                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5059
 5060                    Tabstop {
 5061                        is_end_tabstop,
 5062                        ranges: tabstop_ranges,
 5063                        choices: tabstop.choices.clone(),
 5064                    }
 5065                })
 5066                .collect::<Vec<_>>()
 5067        });
 5068        if let Some(tabstop) = tabstops.first() {
 5069            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5070                s.select_ranges(tabstop.ranges.iter().cloned());
 5071            });
 5072
 5073            if let Some(choices) = &tabstop.choices {
 5074                if let Some(selection) = tabstop.ranges.first() {
 5075                    self.show_snippet_choices(choices, selection.clone(), cx)
 5076                }
 5077            }
 5078
 5079            // If we're already at the last tabstop and it's at the end of the snippet,
 5080            // we're done, we don't need to keep the state around.
 5081            if !tabstop.is_end_tabstop {
 5082                let choices = tabstops
 5083                    .iter()
 5084                    .map(|tabstop| tabstop.choices.clone())
 5085                    .collect();
 5086
 5087                let ranges = tabstops
 5088                    .into_iter()
 5089                    .map(|tabstop| tabstop.ranges)
 5090                    .collect::<Vec<_>>();
 5091
 5092                self.snippet_stack.push(SnippetState {
 5093                    active_index: 0,
 5094                    ranges,
 5095                    choices,
 5096                });
 5097            }
 5098
 5099            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5100            if self.autoclose_regions.is_empty() {
 5101                let snapshot = self.buffer.read(cx).snapshot(cx);
 5102                for selection in &mut self.selections.all::<Point>(cx) {
 5103                    let selection_head = selection.head();
 5104                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5105                        continue;
 5106                    };
 5107
 5108                    let mut bracket_pair = None;
 5109                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5110                    let prev_chars = snapshot
 5111                        .reversed_chars_at(selection_head)
 5112                        .collect::<String>();
 5113                    for (pair, enabled) in scope.brackets() {
 5114                        if enabled
 5115                            && pair.close
 5116                            && prev_chars.starts_with(pair.start.as_str())
 5117                            && next_chars.starts_with(pair.end.as_str())
 5118                        {
 5119                            bracket_pair = Some(pair.clone());
 5120                            break;
 5121                        }
 5122                    }
 5123                    if let Some(pair) = bracket_pair {
 5124                        let start = snapshot.anchor_after(selection_head);
 5125                        let end = snapshot.anchor_after(selection_head);
 5126                        self.autoclose_regions.push(AutocloseRegion {
 5127                            selection_id: selection.id,
 5128                            range: start..end,
 5129                            pair,
 5130                        });
 5131                    }
 5132                }
 5133            }
 5134        }
 5135        Ok(())
 5136    }
 5137
 5138    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5139        self.move_to_snippet_tabstop(Bias::Right, cx)
 5140    }
 5141
 5142    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5143        self.move_to_snippet_tabstop(Bias::Left, cx)
 5144    }
 5145
 5146    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5147        if let Some(mut snippet) = self.snippet_stack.pop() {
 5148            match bias {
 5149                Bias::Left => {
 5150                    if snippet.active_index > 0 {
 5151                        snippet.active_index -= 1;
 5152                    } else {
 5153                        self.snippet_stack.push(snippet);
 5154                        return false;
 5155                    }
 5156                }
 5157                Bias::Right => {
 5158                    if snippet.active_index + 1 < snippet.ranges.len() {
 5159                        snippet.active_index += 1;
 5160                    } else {
 5161                        self.snippet_stack.push(snippet);
 5162                        return false;
 5163                    }
 5164                }
 5165            }
 5166            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5167                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5168                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5169                });
 5170
 5171                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5172                    if let Some(selection) = current_ranges.first() {
 5173                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5174                    }
 5175                }
 5176
 5177                // If snippet state is not at the last tabstop, push it back on the stack
 5178                if snippet.active_index + 1 < snippet.ranges.len() {
 5179                    self.snippet_stack.push(snippet);
 5180                }
 5181                return true;
 5182            }
 5183        }
 5184
 5185        false
 5186    }
 5187
 5188    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5189        self.transact(cx, |this, cx| {
 5190            this.select_all(&SelectAll, cx);
 5191            this.insert("", cx);
 5192        });
 5193    }
 5194
 5195    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5196        self.transact(cx, |this, cx| {
 5197            this.select_autoclose_pair(cx);
 5198            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5199            if !this.linked_edit_ranges.is_empty() {
 5200                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5201                let snapshot = this.buffer.read(cx).snapshot(cx);
 5202
 5203                for selection in selections.iter() {
 5204                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5205                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5206                    if selection_start.buffer_id != selection_end.buffer_id {
 5207                        continue;
 5208                    }
 5209                    if let Some(ranges) =
 5210                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5211                    {
 5212                        for (buffer, entries) in ranges {
 5213                            linked_ranges.entry(buffer).or_default().extend(entries);
 5214                        }
 5215                    }
 5216                }
 5217            }
 5218
 5219            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5220            if !this.selections.line_mode {
 5221                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5222                for selection in &mut selections {
 5223                    if selection.is_empty() {
 5224                        let old_head = selection.head();
 5225                        let mut new_head =
 5226                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5227                                .to_point(&display_map);
 5228                        if let Some((buffer, line_buffer_range)) = display_map
 5229                            .buffer_snapshot
 5230                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5231                        {
 5232                            let indent_size =
 5233                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5234                            let indent_len = match indent_size.kind {
 5235                                IndentKind::Space => {
 5236                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5237                                }
 5238                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5239                            };
 5240                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5241                                let indent_len = indent_len.get();
 5242                                new_head = cmp::min(
 5243                                    new_head,
 5244                                    MultiBufferPoint::new(
 5245                                        old_head.row,
 5246                                        ((old_head.column - 1) / indent_len) * indent_len,
 5247                                    ),
 5248                                );
 5249                            }
 5250                        }
 5251
 5252                        selection.set_head(new_head, SelectionGoal::None);
 5253                    }
 5254                }
 5255            }
 5256
 5257            this.signature_help_state.set_backspace_pressed(true);
 5258            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5259            this.insert("", cx);
 5260            let empty_str: Arc<str> = Arc::from("");
 5261            for (buffer, edits) in linked_ranges {
 5262                let snapshot = buffer.read(cx).snapshot();
 5263                use text::ToPoint as TP;
 5264
 5265                let edits = edits
 5266                    .into_iter()
 5267                    .map(|range| {
 5268                        let end_point = TP::to_point(&range.end, &snapshot);
 5269                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5270
 5271                        if end_point == start_point {
 5272                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5273                                .saturating_sub(1);
 5274                            start_point =
 5275                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5276                        };
 5277
 5278                        (start_point..end_point, empty_str.clone())
 5279                    })
 5280                    .sorted_by_key(|(range, _)| range.start)
 5281                    .collect::<Vec<_>>();
 5282                buffer.update(cx, |this, cx| {
 5283                    this.edit(edits, None, cx);
 5284                })
 5285            }
 5286            this.refresh_inline_completion(true, false, cx);
 5287            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5288        });
 5289    }
 5290
 5291    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5292        self.transact(cx, |this, cx| {
 5293            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5294                let line_mode = s.line_mode;
 5295                s.move_with(|map, selection| {
 5296                    if selection.is_empty() && !line_mode {
 5297                        let cursor = movement::right(map, selection.head());
 5298                        selection.end = cursor;
 5299                        selection.reversed = true;
 5300                        selection.goal = SelectionGoal::None;
 5301                    }
 5302                })
 5303            });
 5304            this.insert("", cx);
 5305            this.refresh_inline_completion(true, false, cx);
 5306        });
 5307    }
 5308
 5309    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5310        if self.move_to_prev_snippet_tabstop(cx) {
 5311            return;
 5312        }
 5313
 5314        self.outdent(&Outdent, cx);
 5315    }
 5316
 5317    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5318        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5319            return;
 5320        }
 5321
 5322        let mut selections = self.selections.all_adjusted(cx);
 5323        let buffer = self.buffer.read(cx);
 5324        let snapshot = buffer.snapshot(cx);
 5325        let rows_iter = selections.iter().map(|s| s.head().row);
 5326        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5327
 5328        let mut edits = Vec::new();
 5329        let mut prev_edited_row = 0;
 5330        let mut row_delta = 0;
 5331        for selection in &mut selections {
 5332            if selection.start.row != prev_edited_row {
 5333                row_delta = 0;
 5334            }
 5335            prev_edited_row = selection.end.row;
 5336
 5337            // If the selection is non-empty, then increase the indentation of the selected lines.
 5338            if !selection.is_empty() {
 5339                row_delta =
 5340                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5341                continue;
 5342            }
 5343
 5344            // If the selection is empty and the cursor is in the leading whitespace before the
 5345            // suggested indentation, then auto-indent the line.
 5346            let cursor = selection.head();
 5347            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5348            if let Some(suggested_indent) =
 5349                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5350            {
 5351                if cursor.column < suggested_indent.len
 5352                    && cursor.column <= current_indent.len
 5353                    && current_indent.len <= suggested_indent.len
 5354                {
 5355                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5356                    selection.end = selection.start;
 5357                    if row_delta == 0 {
 5358                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5359                            cursor.row,
 5360                            current_indent,
 5361                            suggested_indent,
 5362                        ));
 5363                        row_delta = suggested_indent.len - current_indent.len;
 5364                    }
 5365                    continue;
 5366                }
 5367            }
 5368
 5369            // Otherwise, insert a hard or soft tab.
 5370            let settings = buffer.settings_at(cursor, cx);
 5371            let tab_size = if settings.hard_tabs {
 5372                IndentSize::tab()
 5373            } else {
 5374                let tab_size = settings.tab_size.get();
 5375                let char_column = snapshot
 5376                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5377                    .flat_map(str::chars)
 5378                    .count()
 5379                    + row_delta as usize;
 5380                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5381                IndentSize::spaces(chars_to_next_tab_stop)
 5382            };
 5383            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5384            selection.end = selection.start;
 5385            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5386            row_delta += tab_size.len;
 5387        }
 5388
 5389        self.transact(cx, |this, cx| {
 5390            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5391            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5392            this.refresh_inline_completion(true, false, cx);
 5393        });
 5394    }
 5395
 5396    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5397        if self.read_only(cx) {
 5398            return;
 5399        }
 5400        let mut selections = self.selections.all::<Point>(cx);
 5401        let mut prev_edited_row = 0;
 5402        let mut row_delta = 0;
 5403        let mut edits = Vec::new();
 5404        let buffer = self.buffer.read(cx);
 5405        let snapshot = buffer.snapshot(cx);
 5406        for selection in &mut selections {
 5407            if selection.start.row != prev_edited_row {
 5408                row_delta = 0;
 5409            }
 5410            prev_edited_row = selection.end.row;
 5411
 5412            row_delta =
 5413                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5414        }
 5415
 5416        self.transact(cx, |this, cx| {
 5417            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5418            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5419        });
 5420    }
 5421
 5422    fn indent_selection(
 5423        buffer: &MultiBuffer,
 5424        snapshot: &MultiBufferSnapshot,
 5425        selection: &mut Selection<Point>,
 5426        edits: &mut Vec<(Range<Point>, String)>,
 5427        delta_for_start_row: u32,
 5428        cx: &AppContext,
 5429    ) -> u32 {
 5430        let settings = buffer.settings_at(selection.start, cx);
 5431        let tab_size = settings.tab_size.get();
 5432        let indent_kind = if settings.hard_tabs {
 5433            IndentKind::Tab
 5434        } else {
 5435            IndentKind::Space
 5436        };
 5437        let mut start_row = selection.start.row;
 5438        let mut end_row = selection.end.row + 1;
 5439
 5440        // If a selection ends at the beginning of a line, don't indent
 5441        // that last line.
 5442        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5443            end_row -= 1;
 5444        }
 5445
 5446        // Avoid re-indenting a row that has already been indented by a
 5447        // previous selection, but still update this selection's column
 5448        // to reflect that indentation.
 5449        if delta_for_start_row > 0 {
 5450            start_row += 1;
 5451            selection.start.column += delta_for_start_row;
 5452            if selection.end.row == selection.start.row {
 5453                selection.end.column += delta_for_start_row;
 5454            }
 5455        }
 5456
 5457        let mut delta_for_end_row = 0;
 5458        let has_multiple_rows = start_row + 1 != end_row;
 5459        for row in start_row..end_row {
 5460            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5461            let indent_delta = match (current_indent.kind, indent_kind) {
 5462                (IndentKind::Space, IndentKind::Space) => {
 5463                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5464                    IndentSize::spaces(columns_to_next_tab_stop)
 5465                }
 5466                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5467                (_, IndentKind::Tab) => IndentSize::tab(),
 5468            };
 5469
 5470            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5471                0
 5472            } else {
 5473                selection.start.column
 5474            };
 5475            let row_start = Point::new(row, start);
 5476            edits.push((
 5477                row_start..row_start,
 5478                indent_delta.chars().collect::<String>(),
 5479            ));
 5480
 5481            // Update this selection's endpoints to reflect the indentation.
 5482            if row == selection.start.row {
 5483                selection.start.column += indent_delta.len;
 5484            }
 5485            if row == selection.end.row {
 5486                selection.end.column += indent_delta.len;
 5487                delta_for_end_row = indent_delta.len;
 5488            }
 5489        }
 5490
 5491        if selection.start.row == selection.end.row {
 5492            delta_for_start_row + delta_for_end_row
 5493        } else {
 5494            delta_for_end_row
 5495        }
 5496    }
 5497
 5498    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5499        if self.read_only(cx) {
 5500            return;
 5501        }
 5502        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5503        let selections = self.selections.all::<Point>(cx);
 5504        let mut deletion_ranges = Vec::new();
 5505        let mut last_outdent = None;
 5506        {
 5507            let buffer = self.buffer.read(cx);
 5508            let snapshot = buffer.snapshot(cx);
 5509            for selection in &selections {
 5510                let settings = buffer.settings_at(selection.start, cx);
 5511                let tab_size = settings.tab_size.get();
 5512                let mut rows = selection.spanned_rows(false, &display_map);
 5513
 5514                // Avoid re-outdenting a row that has already been outdented by a
 5515                // previous selection.
 5516                if let Some(last_row) = last_outdent {
 5517                    if last_row == rows.start {
 5518                        rows.start = rows.start.next_row();
 5519                    }
 5520                }
 5521                let has_multiple_rows = rows.len() > 1;
 5522                for row in rows.iter_rows() {
 5523                    let indent_size = snapshot.indent_size_for_line(row);
 5524                    if indent_size.len > 0 {
 5525                        let deletion_len = match indent_size.kind {
 5526                            IndentKind::Space => {
 5527                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5528                                if columns_to_prev_tab_stop == 0 {
 5529                                    tab_size
 5530                                } else {
 5531                                    columns_to_prev_tab_stop
 5532                                }
 5533                            }
 5534                            IndentKind::Tab => 1,
 5535                        };
 5536                        let start = if has_multiple_rows
 5537                            || deletion_len > selection.start.column
 5538                            || indent_size.len < selection.start.column
 5539                        {
 5540                            0
 5541                        } else {
 5542                            selection.start.column - deletion_len
 5543                        };
 5544                        deletion_ranges.push(
 5545                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5546                        );
 5547                        last_outdent = Some(row);
 5548                    }
 5549                }
 5550            }
 5551        }
 5552
 5553        self.transact(cx, |this, cx| {
 5554            this.buffer.update(cx, |buffer, cx| {
 5555                let empty_str: Arc<str> = Arc::default();
 5556                buffer.edit(
 5557                    deletion_ranges
 5558                        .into_iter()
 5559                        .map(|range| (range, empty_str.clone())),
 5560                    None,
 5561                    cx,
 5562                );
 5563            });
 5564            let selections = this.selections.all::<usize>(cx);
 5565            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5566        });
 5567    }
 5568
 5569    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5570        if self.read_only(cx) {
 5571            return;
 5572        }
 5573        let selections = self
 5574            .selections
 5575            .all::<usize>(cx)
 5576            .into_iter()
 5577            .map(|s| s.range());
 5578
 5579        self.transact(cx, |this, cx| {
 5580            this.buffer.update(cx, |buffer, cx| {
 5581                buffer.autoindent_ranges(selections, cx);
 5582            });
 5583            let selections = this.selections.all::<usize>(cx);
 5584            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5585        });
 5586    }
 5587
 5588    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5589        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5590        let selections = self.selections.all::<Point>(cx);
 5591
 5592        let mut new_cursors = Vec::new();
 5593        let mut edit_ranges = Vec::new();
 5594        let mut selections = selections.iter().peekable();
 5595        while let Some(selection) = selections.next() {
 5596            let mut rows = selection.spanned_rows(false, &display_map);
 5597            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5598
 5599            // Accumulate contiguous regions of rows that we want to delete.
 5600            while let Some(next_selection) = selections.peek() {
 5601                let next_rows = next_selection.spanned_rows(false, &display_map);
 5602                if next_rows.start <= rows.end {
 5603                    rows.end = next_rows.end;
 5604                    selections.next().unwrap();
 5605                } else {
 5606                    break;
 5607                }
 5608            }
 5609
 5610            let buffer = &display_map.buffer_snapshot;
 5611            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5612            let edit_end;
 5613            let cursor_buffer_row;
 5614            if buffer.max_point().row >= rows.end.0 {
 5615                // If there's a line after the range, delete the \n from the end of the row range
 5616                // and position the cursor on the next line.
 5617                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5618                cursor_buffer_row = rows.end;
 5619            } else {
 5620                // If there isn't a line after the range, delete the \n from the line before the
 5621                // start of the row range and position the cursor there.
 5622                edit_start = edit_start.saturating_sub(1);
 5623                edit_end = buffer.len();
 5624                cursor_buffer_row = rows.start.previous_row();
 5625            }
 5626
 5627            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5628            *cursor.column_mut() =
 5629                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5630
 5631            new_cursors.push((
 5632                selection.id,
 5633                buffer.anchor_after(cursor.to_point(&display_map)),
 5634            ));
 5635            edit_ranges.push(edit_start..edit_end);
 5636        }
 5637
 5638        self.transact(cx, |this, cx| {
 5639            let buffer = this.buffer.update(cx, |buffer, cx| {
 5640                let empty_str: Arc<str> = Arc::default();
 5641                buffer.edit(
 5642                    edit_ranges
 5643                        .into_iter()
 5644                        .map(|range| (range, empty_str.clone())),
 5645                    None,
 5646                    cx,
 5647                );
 5648                buffer.snapshot(cx)
 5649            });
 5650            let new_selections = new_cursors
 5651                .into_iter()
 5652                .map(|(id, cursor)| {
 5653                    let cursor = cursor.to_point(&buffer);
 5654                    Selection {
 5655                        id,
 5656                        start: cursor,
 5657                        end: cursor,
 5658                        reversed: false,
 5659                        goal: SelectionGoal::None,
 5660                    }
 5661                })
 5662                .collect();
 5663
 5664            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5665                s.select(new_selections);
 5666            });
 5667        });
 5668    }
 5669
 5670    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5671        if self.read_only(cx) {
 5672            return;
 5673        }
 5674        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5675        for selection in self.selections.all::<Point>(cx) {
 5676            let start = MultiBufferRow(selection.start.row);
 5677            // Treat single line selections as if they include the next line. Otherwise this action
 5678            // would do nothing for single line selections individual cursors.
 5679            let end = if selection.start.row == selection.end.row {
 5680                MultiBufferRow(selection.start.row + 1)
 5681            } else {
 5682                MultiBufferRow(selection.end.row)
 5683            };
 5684
 5685            if let Some(last_row_range) = row_ranges.last_mut() {
 5686                if start <= last_row_range.end {
 5687                    last_row_range.end = end;
 5688                    continue;
 5689                }
 5690            }
 5691            row_ranges.push(start..end);
 5692        }
 5693
 5694        let snapshot = self.buffer.read(cx).snapshot(cx);
 5695        let mut cursor_positions = Vec::new();
 5696        for row_range in &row_ranges {
 5697            let anchor = snapshot.anchor_before(Point::new(
 5698                row_range.end.previous_row().0,
 5699                snapshot.line_len(row_range.end.previous_row()),
 5700            ));
 5701            cursor_positions.push(anchor..anchor);
 5702        }
 5703
 5704        self.transact(cx, |this, cx| {
 5705            for row_range in row_ranges.into_iter().rev() {
 5706                for row in row_range.iter_rows().rev() {
 5707                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5708                    let next_line_row = row.next_row();
 5709                    let indent = snapshot.indent_size_for_line(next_line_row);
 5710                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5711
 5712                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5713                        " "
 5714                    } else {
 5715                        ""
 5716                    };
 5717
 5718                    this.buffer.update(cx, |buffer, cx| {
 5719                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5720                    });
 5721                }
 5722            }
 5723
 5724            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5725                s.select_anchor_ranges(cursor_positions)
 5726            });
 5727        });
 5728    }
 5729
 5730    pub fn sort_lines_case_sensitive(
 5731        &mut self,
 5732        _: &SortLinesCaseSensitive,
 5733        cx: &mut ViewContext<Self>,
 5734    ) {
 5735        self.manipulate_lines(cx, |lines| lines.sort())
 5736    }
 5737
 5738    pub fn sort_lines_case_insensitive(
 5739        &mut self,
 5740        _: &SortLinesCaseInsensitive,
 5741        cx: &mut ViewContext<Self>,
 5742    ) {
 5743        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5744    }
 5745
 5746    pub fn unique_lines_case_insensitive(
 5747        &mut self,
 5748        _: &UniqueLinesCaseInsensitive,
 5749        cx: &mut ViewContext<Self>,
 5750    ) {
 5751        self.manipulate_lines(cx, |lines| {
 5752            let mut seen = HashSet::default();
 5753            lines.retain(|line| seen.insert(line.to_lowercase()));
 5754        })
 5755    }
 5756
 5757    pub fn unique_lines_case_sensitive(
 5758        &mut self,
 5759        _: &UniqueLinesCaseSensitive,
 5760        cx: &mut ViewContext<Self>,
 5761    ) {
 5762        self.manipulate_lines(cx, |lines| {
 5763            let mut seen = HashSet::default();
 5764            lines.retain(|line| seen.insert(*line));
 5765        })
 5766    }
 5767
 5768    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5769        let mut revert_changes = HashMap::default();
 5770        let snapshot = self.snapshot(cx);
 5771        for hunk in hunks_for_ranges(
 5772            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5773            &snapshot,
 5774        ) {
 5775            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5776        }
 5777        if !revert_changes.is_empty() {
 5778            self.transact(cx, |editor, cx| {
 5779                editor.revert(revert_changes, cx);
 5780            });
 5781        }
 5782    }
 5783
 5784    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5785        let Some(project) = self.project.clone() else {
 5786            return;
 5787        };
 5788        self.reload(project, cx).detach_and_notify_err(cx);
 5789    }
 5790
 5791    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5792        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5793        if !revert_changes.is_empty() {
 5794            self.transact(cx, |editor, cx| {
 5795                editor.revert(revert_changes, cx);
 5796            });
 5797        }
 5798    }
 5799
 5800    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5801        let snapshot = self.buffer.read(cx).read(cx);
 5802        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5803            drop(snapshot);
 5804            let mut revert_changes = HashMap::default();
 5805            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5806            if !revert_changes.is_empty() {
 5807                self.revert(revert_changes, cx)
 5808            }
 5809        }
 5810    }
 5811
 5812    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5813        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5814            let project_path = buffer.read(cx).project_path(cx)?;
 5815            let project = self.project.as_ref()?.read(cx);
 5816            let entry = project.entry_for_path(&project_path, cx)?;
 5817            let parent = match &entry.canonical_path {
 5818                Some(canonical_path) => canonical_path.to_path_buf(),
 5819                None => project.absolute_path(&project_path, cx)?,
 5820            }
 5821            .parent()?
 5822            .to_path_buf();
 5823            Some(parent)
 5824        }) {
 5825            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5826        }
 5827    }
 5828
 5829    fn gather_revert_changes(
 5830        &mut self,
 5831        selections: &[Selection<Point>],
 5832        cx: &mut ViewContext<'_, Editor>,
 5833    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5834        let mut revert_changes = HashMap::default();
 5835        let snapshot = self.snapshot(cx);
 5836        for hunk in hunks_for_selections(&snapshot, selections) {
 5837            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5838        }
 5839        revert_changes
 5840    }
 5841
 5842    pub fn prepare_revert_change(
 5843        &mut self,
 5844        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5845        hunk: &MultiBufferDiffHunk,
 5846        cx: &AppContext,
 5847    ) -> Option<()> {
 5848        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 5849        let buffer = buffer.read(cx);
 5850        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 5851        let original_text = change_set
 5852            .read(cx)
 5853            .base_text
 5854            .as_ref()?
 5855            .read(cx)
 5856            .as_rope()
 5857            .slice(hunk.diff_base_byte_range.clone());
 5858        let buffer_snapshot = buffer.snapshot();
 5859        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5860        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5861            probe
 5862                .0
 5863                .start
 5864                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5865                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5866        }) {
 5867            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5868            Some(())
 5869        } else {
 5870            None
 5871        }
 5872    }
 5873
 5874    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5875        self.manipulate_lines(cx, |lines| lines.reverse())
 5876    }
 5877
 5878    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5879        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5880    }
 5881
 5882    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5883    where
 5884        Fn: FnMut(&mut Vec<&str>),
 5885    {
 5886        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5887        let buffer = self.buffer.read(cx).snapshot(cx);
 5888
 5889        let mut edits = Vec::new();
 5890
 5891        let selections = self.selections.all::<Point>(cx);
 5892        let mut selections = selections.iter().peekable();
 5893        let mut contiguous_row_selections = Vec::new();
 5894        let mut new_selections = Vec::new();
 5895        let mut added_lines = 0;
 5896        let mut removed_lines = 0;
 5897
 5898        while let Some(selection) = selections.next() {
 5899            let (start_row, end_row) = consume_contiguous_rows(
 5900                &mut contiguous_row_selections,
 5901                selection,
 5902                &display_map,
 5903                &mut selections,
 5904            );
 5905
 5906            let start_point = Point::new(start_row.0, 0);
 5907            let end_point = Point::new(
 5908                end_row.previous_row().0,
 5909                buffer.line_len(end_row.previous_row()),
 5910            );
 5911            let text = buffer
 5912                .text_for_range(start_point..end_point)
 5913                .collect::<String>();
 5914
 5915            let mut lines = text.split('\n').collect_vec();
 5916
 5917            let lines_before = lines.len();
 5918            callback(&mut lines);
 5919            let lines_after = lines.len();
 5920
 5921            edits.push((start_point..end_point, lines.join("\n")));
 5922
 5923            // Selections must change based on added and removed line count
 5924            let start_row =
 5925                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5926            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5927            new_selections.push(Selection {
 5928                id: selection.id,
 5929                start: start_row,
 5930                end: end_row,
 5931                goal: SelectionGoal::None,
 5932                reversed: selection.reversed,
 5933            });
 5934
 5935            if lines_after > lines_before {
 5936                added_lines += lines_after - lines_before;
 5937            } else if lines_before > lines_after {
 5938                removed_lines += lines_before - lines_after;
 5939            }
 5940        }
 5941
 5942        self.transact(cx, |this, cx| {
 5943            let buffer = this.buffer.update(cx, |buffer, cx| {
 5944                buffer.edit(edits, None, cx);
 5945                buffer.snapshot(cx)
 5946            });
 5947
 5948            // Recalculate offsets on newly edited buffer
 5949            let new_selections = new_selections
 5950                .iter()
 5951                .map(|s| {
 5952                    let start_point = Point::new(s.start.0, 0);
 5953                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 5954                    Selection {
 5955                        id: s.id,
 5956                        start: buffer.point_to_offset(start_point),
 5957                        end: buffer.point_to_offset(end_point),
 5958                        goal: s.goal,
 5959                        reversed: s.reversed,
 5960                    }
 5961                })
 5962                .collect();
 5963
 5964            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5965                s.select(new_selections);
 5966            });
 5967
 5968            this.request_autoscroll(Autoscroll::fit(), cx);
 5969        });
 5970    }
 5971
 5972    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 5973        self.manipulate_text(cx, |text| text.to_uppercase())
 5974    }
 5975
 5976    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 5977        self.manipulate_text(cx, |text| text.to_lowercase())
 5978    }
 5979
 5980    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 5981        self.manipulate_text(cx, |text| {
 5982            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5983            // https://github.com/rutrum/convert-case/issues/16
 5984            text.split('\n')
 5985                .map(|line| line.to_case(Case::Title))
 5986                .join("\n")
 5987        })
 5988    }
 5989
 5990    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 5991        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 5992    }
 5993
 5994    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 5995        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 5996    }
 5997
 5998    pub fn convert_to_upper_camel_case(
 5999        &mut self,
 6000        _: &ConvertToUpperCamelCase,
 6001        cx: &mut ViewContext<Self>,
 6002    ) {
 6003        self.manipulate_text(cx, |text| {
 6004            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6005            // https://github.com/rutrum/convert-case/issues/16
 6006            text.split('\n')
 6007                .map(|line| line.to_case(Case::UpperCamel))
 6008                .join("\n")
 6009        })
 6010    }
 6011
 6012    pub fn convert_to_lower_camel_case(
 6013        &mut self,
 6014        _: &ConvertToLowerCamelCase,
 6015        cx: &mut ViewContext<Self>,
 6016    ) {
 6017        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6018    }
 6019
 6020    pub fn convert_to_opposite_case(
 6021        &mut self,
 6022        _: &ConvertToOppositeCase,
 6023        cx: &mut ViewContext<Self>,
 6024    ) {
 6025        self.manipulate_text(cx, |text| {
 6026            text.chars()
 6027                .fold(String::with_capacity(text.len()), |mut t, c| {
 6028                    if c.is_uppercase() {
 6029                        t.extend(c.to_lowercase());
 6030                    } else {
 6031                        t.extend(c.to_uppercase());
 6032                    }
 6033                    t
 6034                })
 6035        })
 6036    }
 6037
 6038    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6039    where
 6040        Fn: FnMut(&str) -> String,
 6041    {
 6042        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6043        let buffer = self.buffer.read(cx).snapshot(cx);
 6044
 6045        let mut new_selections = Vec::new();
 6046        let mut edits = Vec::new();
 6047        let mut selection_adjustment = 0i32;
 6048
 6049        for selection in self.selections.all::<usize>(cx) {
 6050            let selection_is_empty = selection.is_empty();
 6051
 6052            let (start, end) = if selection_is_empty {
 6053                let word_range = movement::surrounding_word(
 6054                    &display_map,
 6055                    selection.start.to_display_point(&display_map),
 6056                );
 6057                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6058                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6059                (start, end)
 6060            } else {
 6061                (selection.start, selection.end)
 6062            };
 6063
 6064            let text = buffer.text_for_range(start..end).collect::<String>();
 6065            let old_length = text.len() as i32;
 6066            let text = callback(&text);
 6067
 6068            new_selections.push(Selection {
 6069                start: (start as i32 - selection_adjustment) as usize,
 6070                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6071                goal: SelectionGoal::None,
 6072                ..selection
 6073            });
 6074
 6075            selection_adjustment += old_length - text.len() as i32;
 6076
 6077            edits.push((start..end, text));
 6078        }
 6079
 6080        self.transact(cx, |this, cx| {
 6081            this.buffer.update(cx, |buffer, cx| {
 6082                buffer.edit(edits, None, cx);
 6083            });
 6084
 6085            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6086                s.select(new_selections);
 6087            });
 6088
 6089            this.request_autoscroll(Autoscroll::fit(), cx);
 6090        });
 6091    }
 6092
 6093    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6094        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6095        let buffer = &display_map.buffer_snapshot;
 6096        let selections = self.selections.all::<Point>(cx);
 6097
 6098        let mut edits = Vec::new();
 6099        let mut selections_iter = selections.iter().peekable();
 6100        while let Some(selection) = selections_iter.next() {
 6101            // Avoid duplicating the same lines twice.
 6102            let mut rows = selection.spanned_rows(false, &display_map);
 6103
 6104            while let Some(next_selection) = selections_iter.peek() {
 6105                let next_rows = next_selection.spanned_rows(false, &display_map);
 6106                if next_rows.start < rows.end {
 6107                    rows.end = next_rows.end;
 6108                    selections_iter.next().unwrap();
 6109                } else {
 6110                    break;
 6111                }
 6112            }
 6113
 6114            // Copy the text from the selected row region and splice it either at the start
 6115            // or end of the region.
 6116            let start = Point::new(rows.start.0, 0);
 6117            let end = Point::new(
 6118                rows.end.previous_row().0,
 6119                buffer.line_len(rows.end.previous_row()),
 6120            );
 6121            let text = buffer
 6122                .text_for_range(start..end)
 6123                .chain(Some("\n"))
 6124                .collect::<String>();
 6125            let insert_location = if upwards {
 6126                Point::new(rows.end.0, 0)
 6127            } else {
 6128                start
 6129            };
 6130            edits.push((insert_location..insert_location, text));
 6131        }
 6132
 6133        self.transact(cx, |this, cx| {
 6134            this.buffer.update(cx, |buffer, cx| {
 6135                buffer.edit(edits, None, cx);
 6136            });
 6137
 6138            this.request_autoscroll(Autoscroll::fit(), cx);
 6139        });
 6140    }
 6141
 6142    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6143        self.duplicate_line(true, cx);
 6144    }
 6145
 6146    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6147        self.duplicate_line(false, cx);
 6148    }
 6149
 6150    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6151        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6152        let buffer = self.buffer.read(cx).snapshot(cx);
 6153
 6154        let mut edits = Vec::new();
 6155        let mut unfold_ranges = Vec::new();
 6156        let mut refold_creases = Vec::new();
 6157
 6158        let selections = self.selections.all::<Point>(cx);
 6159        let mut selections = selections.iter().peekable();
 6160        let mut contiguous_row_selections = Vec::new();
 6161        let mut new_selections = Vec::new();
 6162
 6163        while let Some(selection) = selections.next() {
 6164            // Find all the selections that span a contiguous row range
 6165            let (start_row, end_row) = consume_contiguous_rows(
 6166                &mut contiguous_row_selections,
 6167                selection,
 6168                &display_map,
 6169                &mut selections,
 6170            );
 6171
 6172            // Move the text spanned by the row range to be before the line preceding the row range
 6173            if start_row.0 > 0 {
 6174                let range_to_move = Point::new(
 6175                    start_row.previous_row().0,
 6176                    buffer.line_len(start_row.previous_row()),
 6177                )
 6178                    ..Point::new(
 6179                        end_row.previous_row().0,
 6180                        buffer.line_len(end_row.previous_row()),
 6181                    );
 6182                let insertion_point = display_map
 6183                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6184                    .0;
 6185
 6186                // Don't move lines across excerpts
 6187                if buffer
 6188                    .excerpt_boundaries_in_range((
 6189                        Bound::Excluded(insertion_point),
 6190                        Bound::Included(range_to_move.end),
 6191                    ))
 6192                    .next()
 6193                    .is_none()
 6194                {
 6195                    let text = buffer
 6196                        .text_for_range(range_to_move.clone())
 6197                        .flat_map(|s| s.chars())
 6198                        .skip(1)
 6199                        .chain(['\n'])
 6200                        .collect::<String>();
 6201
 6202                    edits.push((
 6203                        buffer.anchor_after(range_to_move.start)
 6204                            ..buffer.anchor_before(range_to_move.end),
 6205                        String::new(),
 6206                    ));
 6207                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6208                    edits.push((insertion_anchor..insertion_anchor, text));
 6209
 6210                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6211
 6212                    // Move selections up
 6213                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6214                        |mut selection| {
 6215                            selection.start.row -= row_delta;
 6216                            selection.end.row -= row_delta;
 6217                            selection
 6218                        },
 6219                    ));
 6220
 6221                    // Move folds up
 6222                    unfold_ranges.push(range_to_move.clone());
 6223                    for fold in display_map.folds_in_range(
 6224                        buffer.anchor_before(range_to_move.start)
 6225                            ..buffer.anchor_after(range_to_move.end),
 6226                    ) {
 6227                        let mut start = fold.range.start.to_point(&buffer);
 6228                        let mut end = fold.range.end.to_point(&buffer);
 6229                        start.row -= row_delta;
 6230                        end.row -= row_delta;
 6231                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6232                    }
 6233                }
 6234            }
 6235
 6236            // If we didn't move line(s), preserve the existing selections
 6237            new_selections.append(&mut contiguous_row_selections);
 6238        }
 6239
 6240        self.transact(cx, |this, cx| {
 6241            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6242            this.buffer.update(cx, |buffer, cx| {
 6243                for (range, text) in edits {
 6244                    buffer.edit([(range, text)], None, cx);
 6245                }
 6246            });
 6247            this.fold_creases(refold_creases, true, cx);
 6248            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6249                s.select(new_selections);
 6250            })
 6251        });
 6252    }
 6253
 6254    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6256        let buffer = self.buffer.read(cx).snapshot(cx);
 6257
 6258        let mut edits = Vec::new();
 6259        let mut unfold_ranges = Vec::new();
 6260        let mut refold_creases = Vec::new();
 6261
 6262        let selections = self.selections.all::<Point>(cx);
 6263        let mut selections = selections.iter().peekable();
 6264        let mut contiguous_row_selections = Vec::new();
 6265        let mut new_selections = Vec::new();
 6266
 6267        while let Some(selection) = selections.next() {
 6268            // Find all the selections that span a contiguous row range
 6269            let (start_row, end_row) = consume_contiguous_rows(
 6270                &mut contiguous_row_selections,
 6271                selection,
 6272                &display_map,
 6273                &mut selections,
 6274            );
 6275
 6276            // Move the text spanned by the row range to be after the last line of the row range
 6277            if end_row.0 <= buffer.max_point().row {
 6278                let range_to_move =
 6279                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6280                let insertion_point = display_map
 6281                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6282                    .0;
 6283
 6284                // Don't move lines across excerpt boundaries
 6285                if buffer
 6286                    .excerpt_boundaries_in_range((
 6287                        Bound::Excluded(range_to_move.start),
 6288                        Bound::Included(insertion_point),
 6289                    ))
 6290                    .next()
 6291                    .is_none()
 6292                {
 6293                    let mut text = String::from("\n");
 6294                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6295                    text.pop(); // Drop trailing newline
 6296                    edits.push((
 6297                        buffer.anchor_after(range_to_move.start)
 6298                            ..buffer.anchor_before(range_to_move.end),
 6299                        String::new(),
 6300                    ));
 6301                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6302                    edits.push((insertion_anchor..insertion_anchor, text));
 6303
 6304                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6305
 6306                    // Move selections down
 6307                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6308                        |mut selection| {
 6309                            selection.start.row += row_delta;
 6310                            selection.end.row += row_delta;
 6311                            selection
 6312                        },
 6313                    ));
 6314
 6315                    // Move folds down
 6316                    unfold_ranges.push(range_to_move.clone());
 6317                    for fold in display_map.folds_in_range(
 6318                        buffer.anchor_before(range_to_move.start)
 6319                            ..buffer.anchor_after(range_to_move.end),
 6320                    ) {
 6321                        let mut start = fold.range.start.to_point(&buffer);
 6322                        let mut end = fold.range.end.to_point(&buffer);
 6323                        start.row += row_delta;
 6324                        end.row += row_delta;
 6325                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6326                    }
 6327                }
 6328            }
 6329
 6330            // If we didn't move line(s), preserve the existing selections
 6331            new_selections.append(&mut contiguous_row_selections);
 6332        }
 6333
 6334        self.transact(cx, |this, cx| {
 6335            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6336            this.buffer.update(cx, |buffer, cx| {
 6337                for (range, text) in edits {
 6338                    buffer.edit([(range, text)], None, cx);
 6339                }
 6340            });
 6341            this.fold_creases(refold_creases, true, cx);
 6342            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6343        });
 6344    }
 6345
 6346    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6347        let text_layout_details = &self.text_layout_details(cx);
 6348        self.transact(cx, |this, cx| {
 6349            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6350                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6351                let line_mode = s.line_mode;
 6352                s.move_with(|display_map, selection| {
 6353                    if !selection.is_empty() || line_mode {
 6354                        return;
 6355                    }
 6356
 6357                    let mut head = selection.head();
 6358                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6359                    if head.column() == display_map.line_len(head.row()) {
 6360                        transpose_offset = display_map
 6361                            .buffer_snapshot
 6362                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6363                    }
 6364
 6365                    if transpose_offset == 0 {
 6366                        return;
 6367                    }
 6368
 6369                    *head.column_mut() += 1;
 6370                    head = display_map.clip_point(head, Bias::Right);
 6371                    let goal = SelectionGoal::HorizontalPosition(
 6372                        display_map
 6373                            .x_for_display_point(head, text_layout_details)
 6374                            .into(),
 6375                    );
 6376                    selection.collapse_to(head, goal);
 6377
 6378                    let transpose_start = display_map
 6379                        .buffer_snapshot
 6380                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6381                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6382                        let transpose_end = display_map
 6383                            .buffer_snapshot
 6384                            .clip_offset(transpose_offset + 1, Bias::Right);
 6385                        if let Some(ch) =
 6386                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6387                        {
 6388                            edits.push((transpose_start..transpose_offset, String::new()));
 6389                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6390                        }
 6391                    }
 6392                });
 6393                edits
 6394            });
 6395            this.buffer
 6396                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6397            let selections = this.selections.all::<usize>(cx);
 6398            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6399                s.select(selections);
 6400            });
 6401        });
 6402    }
 6403
 6404    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6405        self.rewrap_impl(IsVimMode::No, cx)
 6406    }
 6407
 6408    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6409        let buffer = self.buffer.read(cx).snapshot(cx);
 6410        let selections = self.selections.all::<Point>(cx);
 6411        let mut selections = selections.iter().peekable();
 6412
 6413        let mut edits = Vec::new();
 6414        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6415
 6416        while let Some(selection) = selections.next() {
 6417            let mut start_row = selection.start.row;
 6418            let mut end_row = selection.end.row;
 6419
 6420            // Skip selections that overlap with a range that has already been rewrapped.
 6421            let selection_range = start_row..end_row;
 6422            if rewrapped_row_ranges
 6423                .iter()
 6424                .any(|range| range.overlaps(&selection_range))
 6425            {
 6426                continue;
 6427            }
 6428
 6429            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6430
 6431            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6432                match language_scope.language_name().0.as_ref() {
 6433                    "Markdown" | "Plain Text" => {
 6434                        should_rewrap = true;
 6435                    }
 6436                    _ => {}
 6437                }
 6438            }
 6439
 6440            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6441
 6442            // Since not all lines in the selection may be at the same indent
 6443            // level, choose the indent size that is the most common between all
 6444            // of the lines.
 6445            //
 6446            // If there is a tie, we use the deepest indent.
 6447            let (indent_size, indent_end) = {
 6448                let mut indent_size_occurrences = HashMap::default();
 6449                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6450
 6451                for row in start_row..=end_row {
 6452                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6453                    rows_by_indent_size.entry(indent).or_default().push(row);
 6454                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6455                }
 6456
 6457                let indent_size = indent_size_occurrences
 6458                    .into_iter()
 6459                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6460                    .map(|(indent, _)| indent)
 6461                    .unwrap_or_default();
 6462                let row = rows_by_indent_size[&indent_size][0];
 6463                let indent_end = Point::new(row, indent_size.len);
 6464
 6465                (indent_size, indent_end)
 6466            };
 6467
 6468            let mut line_prefix = indent_size.chars().collect::<String>();
 6469
 6470            if let Some(comment_prefix) =
 6471                buffer
 6472                    .language_scope_at(selection.head())
 6473                    .and_then(|language| {
 6474                        language
 6475                            .line_comment_prefixes()
 6476                            .iter()
 6477                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6478                            .cloned()
 6479                    })
 6480            {
 6481                line_prefix.push_str(&comment_prefix);
 6482                should_rewrap = true;
 6483            }
 6484
 6485            if !should_rewrap {
 6486                continue;
 6487            }
 6488
 6489            if selection.is_empty() {
 6490                'expand_upwards: while start_row > 0 {
 6491                    let prev_row = start_row - 1;
 6492                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6493                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6494                    {
 6495                        start_row = prev_row;
 6496                    } else {
 6497                        break 'expand_upwards;
 6498                    }
 6499                }
 6500
 6501                'expand_downwards: while end_row < buffer.max_point().row {
 6502                    let next_row = end_row + 1;
 6503                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6504                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6505                    {
 6506                        end_row = next_row;
 6507                    } else {
 6508                        break 'expand_downwards;
 6509                    }
 6510                }
 6511            }
 6512
 6513            let start = Point::new(start_row, 0);
 6514            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6515            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6516            let Some(lines_without_prefixes) = selection_text
 6517                .lines()
 6518                .map(|line| {
 6519                    line.strip_prefix(&line_prefix)
 6520                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6521                        .ok_or_else(|| {
 6522                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6523                        })
 6524                })
 6525                .collect::<Result<Vec<_>, _>>()
 6526                .log_err()
 6527            else {
 6528                continue;
 6529            };
 6530
 6531            let wrap_column = buffer
 6532                .settings_at(Point::new(start_row, 0), cx)
 6533                .preferred_line_length as usize;
 6534            let wrapped_text = wrap_with_prefix(
 6535                line_prefix,
 6536                lines_without_prefixes.join(" "),
 6537                wrap_column,
 6538                tab_size,
 6539            );
 6540
 6541            // TODO: should always use char-based diff while still supporting cursor behavior that
 6542            // matches vim.
 6543            let diff = match is_vim_mode {
 6544                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6545                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6546            };
 6547            let mut offset = start.to_offset(&buffer);
 6548            let mut moved_since_edit = true;
 6549
 6550            for change in diff.iter_all_changes() {
 6551                let value = change.value();
 6552                match change.tag() {
 6553                    ChangeTag::Equal => {
 6554                        offset += value.len();
 6555                        moved_since_edit = true;
 6556                    }
 6557                    ChangeTag::Delete => {
 6558                        let start = buffer.anchor_after(offset);
 6559                        let end = buffer.anchor_before(offset + value.len());
 6560
 6561                        if moved_since_edit {
 6562                            edits.push((start..end, String::new()));
 6563                        } else {
 6564                            edits.last_mut().unwrap().0.end = end;
 6565                        }
 6566
 6567                        offset += value.len();
 6568                        moved_since_edit = false;
 6569                    }
 6570                    ChangeTag::Insert => {
 6571                        if moved_since_edit {
 6572                            let anchor = buffer.anchor_after(offset);
 6573                            edits.push((anchor..anchor, value.to_string()));
 6574                        } else {
 6575                            edits.last_mut().unwrap().1.push_str(value);
 6576                        }
 6577
 6578                        moved_since_edit = false;
 6579                    }
 6580                }
 6581            }
 6582
 6583            rewrapped_row_ranges.push(start_row..=end_row);
 6584        }
 6585
 6586        self.buffer
 6587            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6588    }
 6589
 6590    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6591        let mut text = String::new();
 6592        let buffer = self.buffer.read(cx).snapshot(cx);
 6593        let mut selections = self.selections.all::<Point>(cx);
 6594        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6595        {
 6596            let max_point = buffer.max_point();
 6597            let mut is_first = true;
 6598            for selection in &mut selections {
 6599                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6600                if is_entire_line {
 6601                    selection.start = Point::new(selection.start.row, 0);
 6602                    if !selection.is_empty() && selection.end.column == 0 {
 6603                        selection.end = cmp::min(max_point, selection.end);
 6604                    } else {
 6605                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6606                    }
 6607                    selection.goal = SelectionGoal::None;
 6608                }
 6609                if is_first {
 6610                    is_first = false;
 6611                } else {
 6612                    text += "\n";
 6613                }
 6614                let mut len = 0;
 6615                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6616                    text.push_str(chunk);
 6617                    len += chunk.len();
 6618                }
 6619                clipboard_selections.push(ClipboardSelection {
 6620                    len,
 6621                    is_entire_line,
 6622                    first_line_indent: buffer
 6623                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6624                        .len,
 6625                });
 6626            }
 6627        }
 6628
 6629        self.transact(cx, |this, cx| {
 6630            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6631                s.select(selections);
 6632            });
 6633            this.insert("", cx);
 6634        });
 6635        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6636    }
 6637
 6638    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6639        let item = self.cut_common(cx);
 6640        cx.write_to_clipboard(item);
 6641    }
 6642
 6643    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6644        self.change_selections(None, cx, |s| {
 6645            s.move_with(|snapshot, sel| {
 6646                if sel.is_empty() {
 6647                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6648                }
 6649            });
 6650        });
 6651        let item = self.cut_common(cx);
 6652        cx.set_global(KillRing(item))
 6653    }
 6654
 6655    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6656        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6657            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6658                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6659            } else {
 6660                return;
 6661            }
 6662        } else {
 6663            return;
 6664        };
 6665        self.do_paste(&text, metadata, false, cx);
 6666    }
 6667
 6668    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6669        let selections = self.selections.all::<Point>(cx);
 6670        let buffer = self.buffer.read(cx).read(cx);
 6671        let mut text = String::new();
 6672
 6673        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6674        {
 6675            let max_point = buffer.max_point();
 6676            let mut is_first = true;
 6677            for selection in selections.iter() {
 6678                let mut start = selection.start;
 6679                let mut end = selection.end;
 6680                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6681                if is_entire_line {
 6682                    start = Point::new(start.row, 0);
 6683                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6684                }
 6685                if is_first {
 6686                    is_first = false;
 6687                } else {
 6688                    text += "\n";
 6689                }
 6690                let mut len = 0;
 6691                for chunk in buffer.text_for_range(start..end) {
 6692                    text.push_str(chunk);
 6693                    len += chunk.len();
 6694                }
 6695                clipboard_selections.push(ClipboardSelection {
 6696                    len,
 6697                    is_entire_line,
 6698                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6699                });
 6700            }
 6701        }
 6702
 6703        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6704            text,
 6705            clipboard_selections,
 6706        ));
 6707    }
 6708
 6709    pub fn do_paste(
 6710        &mut self,
 6711        text: &String,
 6712        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6713        handle_entire_lines: bool,
 6714        cx: &mut ViewContext<Self>,
 6715    ) {
 6716        if self.read_only(cx) {
 6717            return;
 6718        }
 6719
 6720        let clipboard_text = Cow::Borrowed(text);
 6721
 6722        self.transact(cx, |this, cx| {
 6723            if let Some(mut clipboard_selections) = clipboard_selections {
 6724                let old_selections = this.selections.all::<usize>(cx);
 6725                let all_selections_were_entire_line =
 6726                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6727                let first_selection_indent_column =
 6728                    clipboard_selections.first().map(|s| s.first_line_indent);
 6729                if clipboard_selections.len() != old_selections.len() {
 6730                    clipboard_selections.drain(..);
 6731                }
 6732                let cursor_offset = this.selections.last::<usize>(cx).head();
 6733                let mut auto_indent_on_paste = true;
 6734
 6735                this.buffer.update(cx, |buffer, cx| {
 6736                    let snapshot = buffer.read(cx);
 6737                    auto_indent_on_paste =
 6738                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6739
 6740                    let mut start_offset = 0;
 6741                    let mut edits = Vec::new();
 6742                    let mut original_indent_columns = Vec::new();
 6743                    for (ix, selection) in old_selections.iter().enumerate() {
 6744                        let to_insert;
 6745                        let entire_line;
 6746                        let original_indent_column;
 6747                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6748                            let end_offset = start_offset + clipboard_selection.len;
 6749                            to_insert = &clipboard_text[start_offset..end_offset];
 6750                            entire_line = clipboard_selection.is_entire_line;
 6751                            start_offset = end_offset + 1;
 6752                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6753                        } else {
 6754                            to_insert = clipboard_text.as_str();
 6755                            entire_line = all_selections_were_entire_line;
 6756                            original_indent_column = first_selection_indent_column
 6757                        }
 6758
 6759                        // If the corresponding selection was empty when this slice of the
 6760                        // clipboard text was written, then the entire line containing the
 6761                        // selection was copied. If this selection is also currently empty,
 6762                        // then paste the line before the current line of the buffer.
 6763                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6764                            let column = selection.start.to_point(&snapshot).column as usize;
 6765                            let line_start = selection.start - column;
 6766                            line_start..line_start
 6767                        } else {
 6768                            selection.range()
 6769                        };
 6770
 6771                        edits.push((range, to_insert));
 6772                        original_indent_columns.extend(original_indent_column);
 6773                    }
 6774                    drop(snapshot);
 6775
 6776                    buffer.edit(
 6777                        edits,
 6778                        if auto_indent_on_paste {
 6779                            Some(AutoindentMode::Block {
 6780                                original_indent_columns,
 6781                            })
 6782                        } else {
 6783                            None
 6784                        },
 6785                        cx,
 6786                    );
 6787                });
 6788
 6789                let selections = this.selections.all::<usize>(cx);
 6790                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6791            } else {
 6792                this.insert(&clipboard_text, cx);
 6793            }
 6794        });
 6795    }
 6796
 6797    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6798        if let Some(item) = cx.read_from_clipboard() {
 6799            let entries = item.entries();
 6800
 6801            match entries.first() {
 6802                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6803                // of all the pasted entries.
 6804                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6805                    .do_paste(
 6806                        clipboard_string.text(),
 6807                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 6808                        true,
 6809                        cx,
 6810                    ),
 6811                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 6812            }
 6813        }
 6814    }
 6815
 6816    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6817        if self.read_only(cx) {
 6818            return;
 6819        }
 6820
 6821        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6822            if let Some((selections, _)) =
 6823                self.selection_history.transaction(transaction_id).cloned()
 6824            {
 6825                self.change_selections(None, cx, |s| {
 6826                    s.select_anchors(selections.to_vec());
 6827                });
 6828            }
 6829            self.request_autoscroll(Autoscroll::fit(), cx);
 6830            self.unmark_text(cx);
 6831            self.refresh_inline_completion(true, false, cx);
 6832            cx.emit(EditorEvent::Edited { transaction_id });
 6833            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6834        }
 6835    }
 6836
 6837    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6838        if self.read_only(cx) {
 6839            return;
 6840        }
 6841
 6842        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6843            if let Some((_, Some(selections))) =
 6844                self.selection_history.transaction(transaction_id).cloned()
 6845            {
 6846                self.change_selections(None, cx, |s| {
 6847                    s.select_anchors(selections.to_vec());
 6848                });
 6849            }
 6850            self.request_autoscroll(Autoscroll::fit(), cx);
 6851            self.unmark_text(cx);
 6852            self.refresh_inline_completion(true, false, cx);
 6853            cx.emit(EditorEvent::Edited { transaction_id });
 6854        }
 6855    }
 6856
 6857    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6858        self.buffer
 6859            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6860    }
 6861
 6862    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6863        self.buffer
 6864            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6865    }
 6866
 6867    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6868        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6869            let line_mode = s.line_mode;
 6870            s.move_with(|map, selection| {
 6871                let cursor = if selection.is_empty() && !line_mode {
 6872                    movement::left(map, selection.start)
 6873                } else {
 6874                    selection.start
 6875                };
 6876                selection.collapse_to(cursor, SelectionGoal::None);
 6877            });
 6878        })
 6879    }
 6880
 6881    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6882        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6883            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6884        })
 6885    }
 6886
 6887    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6888        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6889            let line_mode = s.line_mode;
 6890            s.move_with(|map, selection| {
 6891                let cursor = if selection.is_empty() && !line_mode {
 6892                    movement::right(map, selection.end)
 6893                } else {
 6894                    selection.end
 6895                };
 6896                selection.collapse_to(cursor, SelectionGoal::None)
 6897            });
 6898        })
 6899    }
 6900
 6901    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6902        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6903            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6904        })
 6905    }
 6906
 6907    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6908        if self.take_rename(true, cx).is_some() {
 6909            return;
 6910        }
 6911
 6912        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6913            cx.propagate();
 6914            return;
 6915        }
 6916
 6917        let text_layout_details = &self.text_layout_details(cx);
 6918        let selection_count = self.selections.count();
 6919        let first_selection = self.selections.first_anchor();
 6920
 6921        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6922            let line_mode = s.line_mode;
 6923            s.move_with(|map, selection| {
 6924                if !selection.is_empty() && !line_mode {
 6925                    selection.goal = SelectionGoal::None;
 6926                }
 6927                let (cursor, goal) = movement::up(
 6928                    map,
 6929                    selection.start,
 6930                    selection.goal,
 6931                    false,
 6932                    text_layout_details,
 6933                );
 6934                selection.collapse_to(cursor, goal);
 6935            });
 6936        });
 6937
 6938        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6939        {
 6940            cx.propagate();
 6941        }
 6942    }
 6943
 6944    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6945        if self.take_rename(true, cx).is_some() {
 6946            return;
 6947        }
 6948
 6949        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6950            cx.propagate();
 6951            return;
 6952        }
 6953
 6954        let text_layout_details = &self.text_layout_details(cx);
 6955
 6956        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6957            let line_mode = s.line_mode;
 6958            s.move_with(|map, selection| {
 6959                if !selection.is_empty() && !line_mode {
 6960                    selection.goal = SelectionGoal::None;
 6961                }
 6962                let (cursor, goal) = movement::up_by_rows(
 6963                    map,
 6964                    selection.start,
 6965                    action.lines,
 6966                    selection.goal,
 6967                    false,
 6968                    text_layout_details,
 6969                );
 6970                selection.collapse_to(cursor, goal);
 6971            });
 6972        })
 6973    }
 6974
 6975    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6976        if self.take_rename(true, cx).is_some() {
 6977            return;
 6978        }
 6979
 6980        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6981            cx.propagate();
 6982            return;
 6983        }
 6984
 6985        let text_layout_details = &self.text_layout_details(cx);
 6986
 6987        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6988            let line_mode = s.line_mode;
 6989            s.move_with(|map, selection| {
 6990                if !selection.is_empty() && !line_mode {
 6991                    selection.goal = SelectionGoal::None;
 6992                }
 6993                let (cursor, goal) = movement::down_by_rows(
 6994                    map,
 6995                    selection.start,
 6996                    action.lines,
 6997                    selection.goal,
 6998                    false,
 6999                    text_layout_details,
 7000                );
 7001                selection.collapse_to(cursor, goal);
 7002            });
 7003        })
 7004    }
 7005
 7006    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7007        let text_layout_details = &self.text_layout_details(cx);
 7008        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7009            s.move_heads_with(|map, head, goal| {
 7010                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7011            })
 7012        })
 7013    }
 7014
 7015    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7016        let text_layout_details = &self.text_layout_details(cx);
 7017        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7018            s.move_heads_with(|map, head, goal| {
 7019                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7020            })
 7021        })
 7022    }
 7023
 7024    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7025        let Some(row_count) = self.visible_row_count() else {
 7026            return;
 7027        };
 7028
 7029        let text_layout_details = &self.text_layout_details(cx);
 7030
 7031        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7032            s.move_heads_with(|map, head, goal| {
 7033                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7034            })
 7035        })
 7036    }
 7037
 7038    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7039        if self.take_rename(true, cx).is_some() {
 7040            return;
 7041        }
 7042
 7043        if self
 7044            .context_menu
 7045            .write()
 7046            .as_mut()
 7047            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7048            .unwrap_or(false)
 7049        {
 7050            return;
 7051        }
 7052
 7053        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7054            cx.propagate();
 7055            return;
 7056        }
 7057
 7058        let Some(row_count) = self.visible_row_count() else {
 7059            return;
 7060        };
 7061
 7062        let autoscroll = if action.center_cursor {
 7063            Autoscroll::center()
 7064        } else {
 7065            Autoscroll::fit()
 7066        };
 7067
 7068        let text_layout_details = &self.text_layout_details(cx);
 7069
 7070        self.change_selections(Some(autoscroll), cx, |s| {
 7071            let line_mode = s.line_mode;
 7072            s.move_with(|map, selection| {
 7073                if !selection.is_empty() && !line_mode {
 7074                    selection.goal = SelectionGoal::None;
 7075                }
 7076                let (cursor, goal) = movement::up_by_rows(
 7077                    map,
 7078                    selection.end,
 7079                    row_count,
 7080                    selection.goal,
 7081                    false,
 7082                    text_layout_details,
 7083                );
 7084                selection.collapse_to(cursor, goal);
 7085            });
 7086        });
 7087    }
 7088
 7089    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7090        let text_layout_details = &self.text_layout_details(cx);
 7091        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7092            s.move_heads_with(|map, head, goal| {
 7093                movement::up(map, head, goal, false, text_layout_details)
 7094            })
 7095        })
 7096    }
 7097
 7098    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7099        self.take_rename(true, cx);
 7100
 7101        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7102            cx.propagate();
 7103            return;
 7104        }
 7105
 7106        let text_layout_details = &self.text_layout_details(cx);
 7107        let selection_count = self.selections.count();
 7108        let first_selection = self.selections.first_anchor();
 7109
 7110        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7111            let line_mode = s.line_mode;
 7112            s.move_with(|map, selection| {
 7113                if !selection.is_empty() && !line_mode {
 7114                    selection.goal = SelectionGoal::None;
 7115                }
 7116                let (cursor, goal) = movement::down(
 7117                    map,
 7118                    selection.end,
 7119                    selection.goal,
 7120                    false,
 7121                    text_layout_details,
 7122                );
 7123                selection.collapse_to(cursor, goal);
 7124            });
 7125        });
 7126
 7127        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7128        {
 7129            cx.propagate();
 7130        }
 7131    }
 7132
 7133    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7134        let Some(row_count) = self.visible_row_count() else {
 7135            return;
 7136        };
 7137
 7138        let text_layout_details = &self.text_layout_details(cx);
 7139
 7140        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7141            s.move_heads_with(|map, head, goal| {
 7142                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7143            })
 7144        })
 7145    }
 7146
 7147    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7148        if self.take_rename(true, cx).is_some() {
 7149            return;
 7150        }
 7151
 7152        if self
 7153            .context_menu
 7154            .write()
 7155            .as_mut()
 7156            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7157            .unwrap_or(false)
 7158        {
 7159            return;
 7160        }
 7161
 7162        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7163            cx.propagate();
 7164            return;
 7165        }
 7166
 7167        let Some(row_count) = self.visible_row_count() else {
 7168            return;
 7169        };
 7170
 7171        let autoscroll = if action.center_cursor {
 7172            Autoscroll::center()
 7173        } else {
 7174            Autoscroll::fit()
 7175        };
 7176
 7177        let text_layout_details = &self.text_layout_details(cx);
 7178        self.change_selections(Some(autoscroll), cx, |s| {
 7179            let line_mode = s.line_mode;
 7180            s.move_with(|map, selection| {
 7181                if !selection.is_empty() && !line_mode {
 7182                    selection.goal = SelectionGoal::None;
 7183                }
 7184                let (cursor, goal) = movement::down_by_rows(
 7185                    map,
 7186                    selection.end,
 7187                    row_count,
 7188                    selection.goal,
 7189                    false,
 7190                    text_layout_details,
 7191                );
 7192                selection.collapse_to(cursor, goal);
 7193            });
 7194        });
 7195    }
 7196
 7197    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7198        let text_layout_details = &self.text_layout_details(cx);
 7199        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7200            s.move_heads_with(|map, head, goal| {
 7201                movement::down(map, head, goal, false, text_layout_details)
 7202            })
 7203        });
 7204    }
 7205
 7206    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7207        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7208            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7209        }
 7210    }
 7211
 7212    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7213        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7214            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7215        }
 7216    }
 7217
 7218    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7219        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7220            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7221        }
 7222    }
 7223
 7224    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7225        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7226            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7227        }
 7228    }
 7229
 7230    pub fn move_to_previous_word_start(
 7231        &mut self,
 7232        _: &MoveToPreviousWordStart,
 7233        cx: &mut ViewContext<Self>,
 7234    ) {
 7235        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7236            s.move_cursors_with(|map, head, _| {
 7237                (
 7238                    movement::previous_word_start(map, head),
 7239                    SelectionGoal::None,
 7240                )
 7241            });
 7242        })
 7243    }
 7244
 7245    pub fn move_to_previous_subword_start(
 7246        &mut self,
 7247        _: &MoveToPreviousSubwordStart,
 7248        cx: &mut ViewContext<Self>,
 7249    ) {
 7250        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7251            s.move_cursors_with(|map, head, _| {
 7252                (
 7253                    movement::previous_subword_start(map, head),
 7254                    SelectionGoal::None,
 7255                )
 7256            });
 7257        })
 7258    }
 7259
 7260    pub fn select_to_previous_word_start(
 7261        &mut self,
 7262        _: &SelectToPreviousWordStart,
 7263        cx: &mut ViewContext<Self>,
 7264    ) {
 7265        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7266            s.move_heads_with(|map, head, _| {
 7267                (
 7268                    movement::previous_word_start(map, head),
 7269                    SelectionGoal::None,
 7270                )
 7271            });
 7272        })
 7273    }
 7274
 7275    pub fn select_to_previous_subword_start(
 7276        &mut self,
 7277        _: &SelectToPreviousSubwordStart,
 7278        cx: &mut ViewContext<Self>,
 7279    ) {
 7280        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7281            s.move_heads_with(|map, head, _| {
 7282                (
 7283                    movement::previous_subword_start(map, head),
 7284                    SelectionGoal::None,
 7285                )
 7286            });
 7287        })
 7288    }
 7289
 7290    pub fn delete_to_previous_word_start(
 7291        &mut self,
 7292        action: &DeleteToPreviousWordStart,
 7293        cx: &mut ViewContext<Self>,
 7294    ) {
 7295        self.transact(cx, |this, cx| {
 7296            this.select_autoclose_pair(cx);
 7297            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7298                let line_mode = s.line_mode;
 7299                s.move_with(|map, selection| {
 7300                    if selection.is_empty() && !line_mode {
 7301                        let cursor = if action.ignore_newlines {
 7302                            movement::previous_word_start(map, selection.head())
 7303                        } else {
 7304                            movement::previous_word_start_or_newline(map, selection.head())
 7305                        };
 7306                        selection.set_head(cursor, SelectionGoal::None);
 7307                    }
 7308                });
 7309            });
 7310            this.insert("", cx);
 7311        });
 7312    }
 7313
 7314    pub fn delete_to_previous_subword_start(
 7315        &mut self,
 7316        _: &DeleteToPreviousSubwordStart,
 7317        cx: &mut ViewContext<Self>,
 7318    ) {
 7319        self.transact(cx, |this, cx| {
 7320            this.select_autoclose_pair(cx);
 7321            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7322                let line_mode = s.line_mode;
 7323                s.move_with(|map, selection| {
 7324                    if selection.is_empty() && !line_mode {
 7325                        let cursor = movement::previous_subword_start(map, selection.head());
 7326                        selection.set_head(cursor, SelectionGoal::None);
 7327                    }
 7328                });
 7329            });
 7330            this.insert("", cx);
 7331        });
 7332    }
 7333
 7334    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7335        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7336            s.move_cursors_with(|map, head, _| {
 7337                (movement::next_word_end(map, head), SelectionGoal::None)
 7338            });
 7339        })
 7340    }
 7341
 7342    pub fn move_to_next_subword_end(
 7343        &mut self,
 7344        _: &MoveToNextSubwordEnd,
 7345        cx: &mut ViewContext<Self>,
 7346    ) {
 7347        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7348            s.move_cursors_with(|map, head, _| {
 7349                (movement::next_subword_end(map, head), SelectionGoal::None)
 7350            });
 7351        })
 7352    }
 7353
 7354    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7355        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7356            s.move_heads_with(|map, head, _| {
 7357                (movement::next_word_end(map, head), SelectionGoal::None)
 7358            });
 7359        })
 7360    }
 7361
 7362    pub fn select_to_next_subword_end(
 7363        &mut self,
 7364        _: &SelectToNextSubwordEnd,
 7365        cx: &mut ViewContext<Self>,
 7366    ) {
 7367        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7368            s.move_heads_with(|map, head, _| {
 7369                (movement::next_subword_end(map, head), SelectionGoal::None)
 7370            });
 7371        })
 7372    }
 7373
 7374    pub fn delete_to_next_word_end(
 7375        &mut self,
 7376        action: &DeleteToNextWordEnd,
 7377        cx: &mut ViewContext<Self>,
 7378    ) {
 7379        self.transact(cx, |this, cx| {
 7380            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7381                let line_mode = s.line_mode;
 7382                s.move_with(|map, selection| {
 7383                    if selection.is_empty() && !line_mode {
 7384                        let cursor = if action.ignore_newlines {
 7385                            movement::next_word_end(map, selection.head())
 7386                        } else {
 7387                            movement::next_word_end_or_newline(map, selection.head())
 7388                        };
 7389                        selection.set_head(cursor, SelectionGoal::None);
 7390                    }
 7391                });
 7392            });
 7393            this.insert("", cx);
 7394        });
 7395    }
 7396
 7397    pub fn delete_to_next_subword_end(
 7398        &mut self,
 7399        _: &DeleteToNextSubwordEnd,
 7400        cx: &mut ViewContext<Self>,
 7401    ) {
 7402        self.transact(cx, |this, cx| {
 7403            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7404                s.move_with(|map, selection| {
 7405                    if selection.is_empty() {
 7406                        let cursor = movement::next_subword_end(map, selection.head());
 7407                        selection.set_head(cursor, SelectionGoal::None);
 7408                    }
 7409                });
 7410            });
 7411            this.insert("", cx);
 7412        });
 7413    }
 7414
 7415    pub fn move_to_beginning_of_line(
 7416        &mut self,
 7417        action: &MoveToBeginningOfLine,
 7418        cx: &mut ViewContext<Self>,
 7419    ) {
 7420        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7421            s.move_cursors_with(|map, head, _| {
 7422                (
 7423                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7424                    SelectionGoal::None,
 7425                )
 7426            });
 7427        })
 7428    }
 7429
 7430    pub fn select_to_beginning_of_line(
 7431        &mut self,
 7432        action: &SelectToBeginningOfLine,
 7433        cx: &mut ViewContext<Self>,
 7434    ) {
 7435        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7436            s.move_heads_with(|map, head, _| {
 7437                (
 7438                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7439                    SelectionGoal::None,
 7440                )
 7441            });
 7442        });
 7443    }
 7444
 7445    pub fn delete_to_beginning_of_line(
 7446        &mut self,
 7447        _: &DeleteToBeginningOfLine,
 7448        cx: &mut ViewContext<Self>,
 7449    ) {
 7450        self.transact(cx, |this, cx| {
 7451            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7452                s.move_with(|_, selection| {
 7453                    selection.reversed = true;
 7454                });
 7455            });
 7456
 7457            this.select_to_beginning_of_line(
 7458                &SelectToBeginningOfLine {
 7459                    stop_at_soft_wraps: false,
 7460                },
 7461                cx,
 7462            );
 7463            this.backspace(&Backspace, cx);
 7464        });
 7465    }
 7466
 7467    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7468        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7469            s.move_cursors_with(|map, head, _| {
 7470                (
 7471                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7472                    SelectionGoal::None,
 7473                )
 7474            });
 7475        })
 7476    }
 7477
 7478    pub fn select_to_end_of_line(
 7479        &mut self,
 7480        action: &SelectToEndOfLine,
 7481        cx: &mut ViewContext<Self>,
 7482    ) {
 7483        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7484            s.move_heads_with(|map, head, _| {
 7485                (
 7486                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7487                    SelectionGoal::None,
 7488                )
 7489            });
 7490        })
 7491    }
 7492
 7493    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7494        self.transact(cx, |this, cx| {
 7495            this.select_to_end_of_line(
 7496                &SelectToEndOfLine {
 7497                    stop_at_soft_wraps: false,
 7498                },
 7499                cx,
 7500            );
 7501            this.delete(&Delete, cx);
 7502        });
 7503    }
 7504
 7505    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7506        self.transact(cx, |this, cx| {
 7507            this.select_to_end_of_line(
 7508                &SelectToEndOfLine {
 7509                    stop_at_soft_wraps: false,
 7510                },
 7511                cx,
 7512            );
 7513            this.cut(&Cut, cx);
 7514        });
 7515    }
 7516
 7517    pub fn move_to_start_of_paragraph(
 7518        &mut self,
 7519        _: &MoveToStartOfParagraph,
 7520        cx: &mut ViewContext<Self>,
 7521    ) {
 7522        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7523            cx.propagate();
 7524            return;
 7525        }
 7526
 7527        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7528            s.move_with(|map, selection| {
 7529                selection.collapse_to(
 7530                    movement::start_of_paragraph(map, selection.head(), 1),
 7531                    SelectionGoal::None,
 7532                )
 7533            });
 7534        })
 7535    }
 7536
 7537    pub fn move_to_end_of_paragraph(
 7538        &mut self,
 7539        _: &MoveToEndOfParagraph,
 7540        cx: &mut ViewContext<Self>,
 7541    ) {
 7542        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7543            cx.propagate();
 7544            return;
 7545        }
 7546
 7547        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7548            s.move_with(|map, selection| {
 7549                selection.collapse_to(
 7550                    movement::end_of_paragraph(map, selection.head(), 1),
 7551                    SelectionGoal::None,
 7552                )
 7553            });
 7554        })
 7555    }
 7556
 7557    pub fn select_to_start_of_paragraph(
 7558        &mut self,
 7559        _: &SelectToStartOfParagraph,
 7560        cx: &mut ViewContext<Self>,
 7561    ) {
 7562        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7563            cx.propagate();
 7564            return;
 7565        }
 7566
 7567        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7568            s.move_heads_with(|map, head, _| {
 7569                (
 7570                    movement::start_of_paragraph(map, head, 1),
 7571                    SelectionGoal::None,
 7572                )
 7573            });
 7574        })
 7575    }
 7576
 7577    pub fn select_to_end_of_paragraph(
 7578        &mut self,
 7579        _: &SelectToEndOfParagraph,
 7580        cx: &mut ViewContext<Self>,
 7581    ) {
 7582        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7583            cx.propagate();
 7584            return;
 7585        }
 7586
 7587        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7588            s.move_heads_with(|map, head, _| {
 7589                (
 7590                    movement::end_of_paragraph(map, head, 1),
 7591                    SelectionGoal::None,
 7592                )
 7593            });
 7594        })
 7595    }
 7596
 7597    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 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.select_ranges(vec![0..0]);
 7605        });
 7606    }
 7607
 7608    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7609        let mut selection = self.selections.last::<Point>(cx);
 7610        selection.set_head(Point::zero(), SelectionGoal::None);
 7611
 7612        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7613            s.select(vec![selection]);
 7614        });
 7615    }
 7616
 7617    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7618        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7619            cx.propagate();
 7620            return;
 7621        }
 7622
 7623        let cursor = self.buffer.read(cx).read(cx).len();
 7624        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7625            s.select_ranges(vec![cursor..cursor])
 7626        });
 7627    }
 7628
 7629    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7630        self.nav_history = nav_history;
 7631    }
 7632
 7633    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7634        self.nav_history.as_ref()
 7635    }
 7636
 7637    fn push_to_nav_history(
 7638        &mut self,
 7639        cursor_anchor: Anchor,
 7640        new_position: Option<Point>,
 7641        cx: &mut ViewContext<Self>,
 7642    ) {
 7643        if let Some(nav_history) = self.nav_history.as_mut() {
 7644            let buffer = self.buffer.read(cx).read(cx);
 7645            let cursor_position = cursor_anchor.to_point(&buffer);
 7646            let scroll_state = self.scroll_manager.anchor();
 7647            let scroll_top_row = scroll_state.top_row(&buffer);
 7648            drop(buffer);
 7649
 7650            if let Some(new_position) = new_position {
 7651                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7652                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7653                    return;
 7654                }
 7655            }
 7656
 7657            nav_history.push(
 7658                Some(NavigationData {
 7659                    cursor_anchor,
 7660                    cursor_position,
 7661                    scroll_anchor: scroll_state,
 7662                    scroll_top_row,
 7663                }),
 7664                cx,
 7665            );
 7666        }
 7667    }
 7668
 7669    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7670        let buffer = self.buffer.read(cx).snapshot(cx);
 7671        let mut selection = self.selections.first::<usize>(cx);
 7672        selection.set_head(buffer.len(), SelectionGoal::None);
 7673        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7674            s.select(vec![selection]);
 7675        });
 7676    }
 7677
 7678    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7679        let end = self.buffer.read(cx).read(cx).len();
 7680        self.change_selections(None, cx, |s| {
 7681            s.select_ranges(vec![0..end]);
 7682        });
 7683    }
 7684
 7685    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7686        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7687        let mut selections = self.selections.all::<Point>(cx);
 7688        let max_point = display_map.buffer_snapshot.max_point();
 7689        for selection in &mut selections {
 7690            let rows = selection.spanned_rows(true, &display_map);
 7691            selection.start = Point::new(rows.start.0, 0);
 7692            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7693            selection.reversed = false;
 7694        }
 7695        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7696            s.select(selections);
 7697        });
 7698    }
 7699
 7700    pub fn split_selection_into_lines(
 7701        &mut self,
 7702        _: &SplitSelectionIntoLines,
 7703        cx: &mut ViewContext<Self>,
 7704    ) {
 7705        let mut to_unfold = Vec::new();
 7706        let mut new_selection_ranges = Vec::new();
 7707        {
 7708            let selections = self.selections.all::<Point>(cx);
 7709            let buffer = self.buffer.read(cx).read(cx);
 7710            for selection in selections {
 7711                for row in selection.start.row..selection.end.row {
 7712                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7713                    new_selection_ranges.push(cursor..cursor);
 7714                }
 7715                new_selection_ranges.push(selection.end..selection.end);
 7716                to_unfold.push(selection.start..selection.end);
 7717            }
 7718        }
 7719        self.unfold_ranges(&to_unfold, true, true, cx);
 7720        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7721            s.select_ranges(new_selection_ranges);
 7722        });
 7723    }
 7724
 7725    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7726        self.add_selection(true, cx);
 7727    }
 7728
 7729    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7730        self.add_selection(false, cx);
 7731    }
 7732
 7733    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7734        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7735        let mut selections = self.selections.all::<Point>(cx);
 7736        let text_layout_details = self.text_layout_details(cx);
 7737        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7738            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7739            let range = oldest_selection.display_range(&display_map).sorted();
 7740
 7741            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7742            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7743            let positions = start_x.min(end_x)..start_x.max(end_x);
 7744
 7745            selections.clear();
 7746            let mut stack = Vec::new();
 7747            for row in range.start.row().0..=range.end.row().0 {
 7748                if let Some(selection) = self.selections.build_columnar_selection(
 7749                    &display_map,
 7750                    DisplayRow(row),
 7751                    &positions,
 7752                    oldest_selection.reversed,
 7753                    &text_layout_details,
 7754                ) {
 7755                    stack.push(selection.id);
 7756                    selections.push(selection);
 7757                }
 7758            }
 7759
 7760            if above {
 7761                stack.reverse();
 7762            }
 7763
 7764            AddSelectionsState { above, stack }
 7765        });
 7766
 7767        let last_added_selection = *state.stack.last().unwrap();
 7768        let mut new_selections = Vec::new();
 7769        if above == state.above {
 7770            let end_row = if above {
 7771                DisplayRow(0)
 7772            } else {
 7773                display_map.max_point().row()
 7774            };
 7775
 7776            'outer: for selection in selections {
 7777                if selection.id == last_added_selection {
 7778                    let range = selection.display_range(&display_map).sorted();
 7779                    debug_assert_eq!(range.start.row(), range.end.row());
 7780                    let mut row = range.start.row();
 7781                    let positions =
 7782                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7783                            px(start)..px(end)
 7784                        } else {
 7785                            let start_x =
 7786                                display_map.x_for_display_point(range.start, &text_layout_details);
 7787                            let end_x =
 7788                                display_map.x_for_display_point(range.end, &text_layout_details);
 7789                            start_x.min(end_x)..start_x.max(end_x)
 7790                        };
 7791
 7792                    while row != end_row {
 7793                        if above {
 7794                            row.0 -= 1;
 7795                        } else {
 7796                            row.0 += 1;
 7797                        }
 7798
 7799                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7800                            &display_map,
 7801                            row,
 7802                            &positions,
 7803                            selection.reversed,
 7804                            &text_layout_details,
 7805                        ) {
 7806                            state.stack.push(new_selection.id);
 7807                            if above {
 7808                                new_selections.push(new_selection);
 7809                                new_selections.push(selection);
 7810                            } else {
 7811                                new_selections.push(selection);
 7812                                new_selections.push(new_selection);
 7813                            }
 7814
 7815                            continue 'outer;
 7816                        }
 7817                    }
 7818                }
 7819
 7820                new_selections.push(selection);
 7821            }
 7822        } else {
 7823            new_selections = selections;
 7824            new_selections.retain(|s| s.id != last_added_selection);
 7825            state.stack.pop();
 7826        }
 7827
 7828        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7829            s.select(new_selections);
 7830        });
 7831        if state.stack.len() > 1 {
 7832            self.add_selections_state = Some(state);
 7833        }
 7834    }
 7835
 7836    pub fn select_next_match_internal(
 7837        &mut self,
 7838        display_map: &DisplaySnapshot,
 7839        replace_newest: bool,
 7840        autoscroll: Option<Autoscroll>,
 7841        cx: &mut ViewContext<Self>,
 7842    ) -> Result<()> {
 7843        fn select_next_match_ranges(
 7844            this: &mut Editor,
 7845            range: Range<usize>,
 7846            replace_newest: bool,
 7847            auto_scroll: Option<Autoscroll>,
 7848            cx: &mut ViewContext<Editor>,
 7849        ) {
 7850            this.unfold_ranges(&[range.clone()], false, true, cx);
 7851            this.change_selections(auto_scroll, cx, |s| {
 7852                if replace_newest {
 7853                    s.delete(s.newest_anchor().id);
 7854                }
 7855                s.insert_range(range.clone());
 7856            });
 7857        }
 7858
 7859        let buffer = &display_map.buffer_snapshot;
 7860        let mut selections = self.selections.all::<usize>(cx);
 7861        if let Some(mut select_next_state) = self.select_next_state.take() {
 7862            let query = &select_next_state.query;
 7863            if !select_next_state.done {
 7864                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7865                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7866                let mut next_selected_range = None;
 7867
 7868                let bytes_after_last_selection =
 7869                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7870                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7871                let query_matches = query
 7872                    .stream_find_iter(bytes_after_last_selection)
 7873                    .map(|result| (last_selection.end, result))
 7874                    .chain(
 7875                        query
 7876                            .stream_find_iter(bytes_before_first_selection)
 7877                            .map(|result| (0, result)),
 7878                    );
 7879
 7880                for (start_offset, query_match) in query_matches {
 7881                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7882                    let offset_range =
 7883                        start_offset + query_match.start()..start_offset + query_match.end();
 7884                    let display_range = offset_range.start.to_display_point(display_map)
 7885                        ..offset_range.end.to_display_point(display_map);
 7886
 7887                    if !select_next_state.wordwise
 7888                        || (!movement::is_inside_word(display_map, display_range.start)
 7889                            && !movement::is_inside_word(display_map, display_range.end))
 7890                    {
 7891                        // TODO: This is n^2, because we might check all the selections
 7892                        if !selections
 7893                            .iter()
 7894                            .any(|selection| selection.range().overlaps(&offset_range))
 7895                        {
 7896                            next_selected_range = Some(offset_range);
 7897                            break;
 7898                        }
 7899                    }
 7900                }
 7901
 7902                if let Some(next_selected_range) = next_selected_range {
 7903                    select_next_match_ranges(
 7904                        self,
 7905                        next_selected_range,
 7906                        replace_newest,
 7907                        autoscroll,
 7908                        cx,
 7909                    );
 7910                } else {
 7911                    select_next_state.done = true;
 7912                }
 7913            }
 7914
 7915            self.select_next_state = Some(select_next_state);
 7916        } else {
 7917            let mut only_carets = true;
 7918            let mut same_text_selected = true;
 7919            let mut selected_text = None;
 7920
 7921            let mut selections_iter = selections.iter().peekable();
 7922            while let Some(selection) = selections_iter.next() {
 7923                if selection.start != selection.end {
 7924                    only_carets = false;
 7925                }
 7926
 7927                if same_text_selected {
 7928                    if selected_text.is_none() {
 7929                        selected_text =
 7930                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7931                    }
 7932
 7933                    if let Some(next_selection) = selections_iter.peek() {
 7934                        if next_selection.range().len() == selection.range().len() {
 7935                            let next_selected_text = buffer
 7936                                .text_for_range(next_selection.range())
 7937                                .collect::<String>();
 7938                            if Some(next_selected_text) != selected_text {
 7939                                same_text_selected = false;
 7940                                selected_text = None;
 7941                            }
 7942                        } else {
 7943                            same_text_selected = false;
 7944                            selected_text = None;
 7945                        }
 7946                    }
 7947                }
 7948            }
 7949
 7950            if only_carets {
 7951                for selection in &mut selections {
 7952                    let word_range = movement::surrounding_word(
 7953                        display_map,
 7954                        selection.start.to_display_point(display_map),
 7955                    );
 7956                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 7957                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 7958                    selection.goal = SelectionGoal::None;
 7959                    selection.reversed = false;
 7960                    select_next_match_ranges(
 7961                        self,
 7962                        selection.start..selection.end,
 7963                        replace_newest,
 7964                        autoscroll,
 7965                        cx,
 7966                    );
 7967                }
 7968
 7969                if selections.len() == 1 {
 7970                    let selection = selections
 7971                        .last()
 7972                        .expect("ensured that there's only one selection");
 7973                    let query = buffer
 7974                        .text_for_range(selection.start..selection.end)
 7975                        .collect::<String>();
 7976                    let is_empty = query.is_empty();
 7977                    let select_state = SelectNextState {
 7978                        query: AhoCorasick::new(&[query])?,
 7979                        wordwise: true,
 7980                        done: is_empty,
 7981                    };
 7982                    self.select_next_state = Some(select_state);
 7983                } else {
 7984                    self.select_next_state = None;
 7985                }
 7986            } else if let Some(selected_text) = selected_text {
 7987                self.select_next_state = Some(SelectNextState {
 7988                    query: AhoCorasick::new(&[selected_text])?,
 7989                    wordwise: false,
 7990                    done: false,
 7991                });
 7992                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7993            }
 7994        }
 7995        Ok(())
 7996    }
 7997
 7998    pub fn select_all_matches(
 7999        &mut self,
 8000        _action: &SelectAllMatches,
 8001        cx: &mut ViewContext<Self>,
 8002    ) -> Result<()> {
 8003        self.push_to_selection_history();
 8004        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8005
 8006        self.select_next_match_internal(&display_map, false, None, cx)?;
 8007        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8008            return Ok(());
 8009        };
 8010        if select_next_state.done {
 8011            return Ok(());
 8012        }
 8013
 8014        let mut new_selections = self.selections.all::<usize>(cx);
 8015
 8016        let buffer = &display_map.buffer_snapshot;
 8017        let query_matches = select_next_state
 8018            .query
 8019            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8020
 8021        for query_match in query_matches {
 8022            let query_match = query_match.unwrap(); // can only fail due to I/O
 8023            let offset_range = query_match.start()..query_match.end();
 8024            let display_range = offset_range.start.to_display_point(&display_map)
 8025                ..offset_range.end.to_display_point(&display_map);
 8026
 8027            if !select_next_state.wordwise
 8028                || (!movement::is_inside_word(&display_map, display_range.start)
 8029                    && !movement::is_inside_word(&display_map, display_range.end))
 8030            {
 8031                self.selections.change_with(cx, |selections| {
 8032                    new_selections.push(Selection {
 8033                        id: selections.new_selection_id(),
 8034                        start: offset_range.start,
 8035                        end: offset_range.end,
 8036                        reversed: false,
 8037                        goal: SelectionGoal::None,
 8038                    });
 8039                });
 8040            }
 8041        }
 8042
 8043        new_selections.sort_by_key(|selection| selection.start);
 8044        let mut ix = 0;
 8045        while ix + 1 < new_selections.len() {
 8046            let current_selection = &new_selections[ix];
 8047            let next_selection = &new_selections[ix + 1];
 8048            if current_selection.range().overlaps(&next_selection.range()) {
 8049                if current_selection.id < next_selection.id {
 8050                    new_selections.remove(ix + 1);
 8051                } else {
 8052                    new_selections.remove(ix);
 8053                }
 8054            } else {
 8055                ix += 1;
 8056            }
 8057        }
 8058
 8059        select_next_state.done = true;
 8060        self.unfold_ranges(
 8061            &new_selections
 8062                .iter()
 8063                .map(|selection| selection.range())
 8064                .collect::<Vec<_>>(),
 8065            false,
 8066            false,
 8067            cx,
 8068        );
 8069        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8070            selections.select(new_selections)
 8071        });
 8072
 8073        Ok(())
 8074    }
 8075
 8076    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8077        self.push_to_selection_history();
 8078        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8079        self.select_next_match_internal(
 8080            &display_map,
 8081            action.replace_newest,
 8082            Some(Autoscroll::newest()),
 8083            cx,
 8084        )?;
 8085        Ok(())
 8086    }
 8087
 8088    pub fn select_previous(
 8089        &mut self,
 8090        action: &SelectPrevious,
 8091        cx: &mut ViewContext<Self>,
 8092    ) -> Result<()> {
 8093        self.push_to_selection_history();
 8094        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8095        let buffer = &display_map.buffer_snapshot;
 8096        let mut selections = self.selections.all::<usize>(cx);
 8097        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8098            let query = &select_prev_state.query;
 8099            if !select_prev_state.done {
 8100                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8101                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8102                let mut next_selected_range = None;
 8103                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8104                let bytes_before_last_selection =
 8105                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8106                let bytes_after_first_selection =
 8107                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8108                let query_matches = query
 8109                    .stream_find_iter(bytes_before_last_selection)
 8110                    .map(|result| (last_selection.start, result))
 8111                    .chain(
 8112                        query
 8113                            .stream_find_iter(bytes_after_first_selection)
 8114                            .map(|result| (buffer.len(), result)),
 8115                    );
 8116                for (end_offset, query_match) in query_matches {
 8117                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8118                    let offset_range =
 8119                        end_offset - query_match.end()..end_offset - query_match.start();
 8120                    let display_range = offset_range.start.to_display_point(&display_map)
 8121                        ..offset_range.end.to_display_point(&display_map);
 8122
 8123                    if !select_prev_state.wordwise
 8124                        || (!movement::is_inside_word(&display_map, display_range.start)
 8125                            && !movement::is_inside_word(&display_map, display_range.end))
 8126                    {
 8127                        next_selected_range = Some(offset_range);
 8128                        break;
 8129                    }
 8130                }
 8131
 8132                if let Some(next_selected_range) = next_selected_range {
 8133                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8134                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8135                        if action.replace_newest {
 8136                            s.delete(s.newest_anchor().id);
 8137                        }
 8138                        s.insert_range(next_selected_range);
 8139                    });
 8140                } else {
 8141                    select_prev_state.done = true;
 8142                }
 8143            }
 8144
 8145            self.select_prev_state = Some(select_prev_state);
 8146        } else {
 8147            let mut only_carets = true;
 8148            let mut same_text_selected = true;
 8149            let mut selected_text = None;
 8150
 8151            let mut selections_iter = selections.iter().peekable();
 8152            while let Some(selection) = selections_iter.next() {
 8153                if selection.start != selection.end {
 8154                    only_carets = false;
 8155                }
 8156
 8157                if same_text_selected {
 8158                    if selected_text.is_none() {
 8159                        selected_text =
 8160                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8161                    }
 8162
 8163                    if let Some(next_selection) = selections_iter.peek() {
 8164                        if next_selection.range().len() == selection.range().len() {
 8165                            let next_selected_text = buffer
 8166                                .text_for_range(next_selection.range())
 8167                                .collect::<String>();
 8168                            if Some(next_selected_text) != selected_text {
 8169                                same_text_selected = false;
 8170                                selected_text = None;
 8171                            }
 8172                        } else {
 8173                            same_text_selected = false;
 8174                            selected_text = None;
 8175                        }
 8176                    }
 8177                }
 8178            }
 8179
 8180            if only_carets {
 8181                for selection in &mut selections {
 8182                    let word_range = movement::surrounding_word(
 8183                        &display_map,
 8184                        selection.start.to_display_point(&display_map),
 8185                    );
 8186                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8187                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8188                    selection.goal = SelectionGoal::None;
 8189                    selection.reversed = false;
 8190                }
 8191                if selections.len() == 1 {
 8192                    let selection = selections
 8193                        .last()
 8194                        .expect("ensured that there's only one selection");
 8195                    let query = buffer
 8196                        .text_for_range(selection.start..selection.end)
 8197                        .collect::<String>();
 8198                    let is_empty = query.is_empty();
 8199                    let select_state = SelectNextState {
 8200                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8201                        wordwise: true,
 8202                        done: is_empty,
 8203                    };
 8204                    self.select_prev_state = Some(select_state);
 8205                } else {
 8206                    self.select_prev_state = None;
 8207                }
 8208
 8209                self.unfold_ranges(
 8210                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8211                    false,
 8212                    true,
 8213                    cx,
 8214                );
 8215                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8216                    s.select(selections);
 8217                });
 8218            } else if let Some(selected_text) = selected_text {
 8219                self.select_prev_state = Some(SelectNextState {
 8220                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8221                    wordwise: false,
 8222                    done: false,
 8223                });
 8224                self.select_previous(action, cx)?;
 8225            }
 8226        }
 8227        Ok(())
 8228    }
 8229
 8230    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8231        if self.read_only(cx) {
 8232            return;
 8233        }
 8234        let text_layout_details = &self.text_layout_details(cx);
 8235        self.transact(cx, |this, cx| {
 8236            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8237            let mut edits = Vec::new();
 8238            let mut selection_edit_ranges = Vec::new();
 8239            let mut last_toggled_row = None;
 8240            let snapshot = this.buffer.read(cx).read(cx);
 8241            let empty_str: Arc<str> = Arc::default();
 8242            let mut suffixes_inserted = Vec::new();
 8243            let ignore_indent = action.ignore_indent;
 8244
 8245            fn comment_prefix_range(
 8246                snapshot: &MultiBufferSnapshot,
 8247                row: MultiBufferRow,
 8248                comment_prefix: &str,
 8249                comment_prefix_whitespace: &str,
 8250                ignore_indent: bool,
 8251            ) -> Range<Point> {
 8252                let indent_size = if ignore_indent {
 8253                    0
 8254                } else {
 8255                    snapshot.indent_size_for_line(row).len
 8256                };
 8257
 8258                let start = Point::new(row.0, indent_size);
 8259
 8260                let mut line_bytes = snapshot
 8261                    .bytes_in_range(start..snapshot.max_point())
 8262                    .flatten()
 8263                    .copied();
 8264
 8265                // If this line currently begins with the line comment prefix, then record
 8266                // the range containing the prefix.
 8267                if line_bytes
 8268                    .by_ref()
 8269                    .take(comment_prefix.len())
 8270                    .eq(comment_prefix.bytes())
 8271                {
 8272                    // Include any whitespace that matches the comment prefix.
 8273                    let matching_whitespace_len = line_bytes
 8274                        .zip(comment_prefix_whitespace.bytes())
 8275                        .take_while(|(a, b)| a == b)
 8276                        .count() as u32;
 8277                    let end = Point::new(
 8278                        start.row,
 8279                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8280                    );
 8281                    start..end
 8282                } else {
 8283                    start..start
 8284                }
 8285            }
 8286
 8287            fn comment_suffix_range(
 8288                snapshot: &MultiBufferSnapshot,
 8289                row: MultiBufferRow,
 8290                comment_suffix: &str,
 8291                comment_suffix_has_leading_space: bool,
 8292            ) -> Range<Point> {
 8293                let end = Point::new(row.0, snapshot.line_len(row));
 8294                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8295
 8296                let mut line_end_bytes = snapshot
 8297                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8298                    .flatten()
 8299                    .copied();
 8300
 8301                let leading_space_len = if suffix_start_column > 0
 8302                    && line_end_bytes.next() == Some(b' ')
 8303                    && comment_suffix_has_leading_space
 8304                {
 8305                    1
 8306                } else {
 8307                    0
 8308                };
 8309
 8310                // If this line currently begins with the line comment prefix, then record
 8311                // the range containing the prefix.
 8312                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8313                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8314                    start..end
 8315                } else {
 8316                    end..end
 8317                }
 8318            }
 8319
 8320            // TODO: Handle selections that cross excerpts
 8321            for selection in &mut selections {
 8322                let start_column = snapshot
 8323                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8324                    .len;
 8325                let language = if let Some(language) =
 8326                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8327                {
 8328                    language
 8329                } else {
 8330                    continue;
 8331                };
 8332
 8333                selection_edit_ranges.clear();
 8334
 8335                // If multiple selections contain a given row, avoid processing that
 8336                // row more than once.
 8337                let mut start_row = MultiBufferRow(selection.start.row);
 8338                if last_toggled_row == Some(start_row) {
 8339                    start_row = start_row.next_row();
 8340                }
 8341                let end_row =
 8342                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8343                        MultiBufferRow(selection.end.row - 1)
 8344                    } else {
 8345                        MultiBufferRow(selection.end.row)
 8346                    };
 8347                last_toggled_row = Some(end_row);
 8348
 8349                if start_row > end_row {
 8350                    continue;
 8351                }
 8352
 8353                // If the language has line comments, toggle those.
 8354                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8355
 8356                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8357                if ignore_indent {
 8358                    full_comment_prefixes = full_comment_prefixes
 8359                        .into_iter()
 8360                        .map(|s| Arc::from(s.trim_end()))
 8361                        .collect();
 8362                }
 8363
 8364                if !full_comment_prefixes.is_empty() {
 8365                    let first_prefix = full_comment_prefixes
 8366                        .first()
 8367                        .expect("prefixes is non-empty");
 8368                    let prefix_trimmed_lengths = full_comment_prefixes
 8369                        .iter()
 8370                        .map(|p| p.trim_end_matches(' ').len())
 8371                        .collect::<SmallVec<[usize; 4]>>();
 8372
 8373                    let mut all_selection_lines_are_comments = true;
 8374
 8375                    for row in start_row.0..=end_row.0 {
 8376                        let row = MultiBufferRow(row);
 8377                        if start_row < end_row && snapshot.is_line_blank(row) {
 8378                            continue;
 8379                        }
 8380
 8381                        let prefix_range = full_comment_prefixes
 8382                            .iter()
 8383                            .zip(prefix_trimmed_lengths.iter().copied())
 8384                            .map(|(prefix, trimmed_prefix_len)| {
 8385                                comment_prefix_range(
 8386                                    snapshot.deref(),
 8387                                    row,
 8388                                    &prefix[..trimmed_prefix_len],
 8389                                    &prefix[trimmed_prefix_len..],
 8390                                    ignore_indent,
 8391                                )
 8392                            })
 8393                            .max_by_key(|range| range.end.column - range.start.column)
 8394                            .expect("prefixes is non-empty");
 8395
 8396                        if prefix_range.is_empty() {
 8397                            all_selection_lines_are_comments = false;
 8398                        }
 8399
 8400                        selection_edit_ranges.push(prefix_range);
 8401                    }
 8402
 8403                    if all_selection_lines_are_comments {
 8404                        edits.extend(
 8405                            selection_edit_ranges
 8406                                .iter()
 8407                                .cloned()
 8408                                .map(|range| (range, empty_str.clone())),
 8409                        );
 8410                    } else {
 8411                        let min_column = selection_edit_ranges
 8412                            .iter()
 8413                            .map(|range| range.start.column)
 8414                            .min()
 8415                            .unwrap_or(0);
 8416                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8417                            let position = Point::new(range.start.row, min_column);
 8418                            (position..position, first_prefix.clone())
 8419                        }));
 8420                    }
 8421                } else if let Some((full_comment_prefix, comment_suffix)) =
 8422                    language.block_comment_delimiters()
 8423                {
 8424                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8425                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8426                    let prefix_range = comment_prefix_range(
 8427                        snapshot.deref(),
 8428                        start_row,
 8429                        comment_prefix,
 8430                        comment_prefix_whitespace,
 8431                        ignore_indent,
 8432                    );
 8433                    let suffix_range = comment_suffix_range(
 8434                        snapshot.deref(),
 8435                        end_row,
 8436                        comment_suffix.trim_start_matches(' '),
 8437                        comment_suffix.starts_with(' '),
 8438                    );
 8439
 8440                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8441                        edits.push((
 8442                            prefix_range.start..prefix_range.start,
 8443                            full_comment_prefix.clone(),
 8444                        ));
 8445                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8446                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8447                    } else {
 8448                        edits.push((prefix_range, empty_str.clone()));
 8449                        edits.push((suffix_range, empty_str.clone()));
 8450                    }
 8451                } else {
 8452                    continue;
 8453                }
 8454            }
 8455
 8456            drop(snapshot);
 8457            this.buffer.update(cx, |buffer, cx| {
 8458                buffer.edit(edits, None, cx);
 8459            });
 8460
 8461            // Adjust selections so that they end before any comment suffixes that
 8462            // were inserted.
 8463            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8464            let mut selections = this.selections.all::<Point>(cx);
 8465            let snapshot = this.buffer.read(cx).read(cx);
 8466            for selection in &mut selections {
 8467                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8468                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8469                        Ordering::Less => {
 8470                            suffixes_inserted.next();
 8471                            continue;
 8472                        }
 8473                        Ordering::Greater => break,
 8474                        Ordering::Equal => {
 8475                            if selection.end.column == snapshot.line_len(row) {
 8476                                if selection.is_empty() {
 8477                                    selection.start.column -= suffix_len as u32;
 8478                                }
 8479                                selection.end.column -= suffix_len as u32;
 8480                            }
 8481                            break;
 8482                        }
 8483                    }
 8484                }
 8485            }
 8486
 8487            drop(snapshot);
 8488            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8489
 8490            let selections = this.selections.all::<Point>(cx);
 8491            let selections_on_single_row = selections.windows(2).all(|selections| {
 8492                selections[0].start.row == selections[1].start.row
 8493                    && selections[0].end.row == selections[1].end.row
 8494                    && selections[0].start.row == selections[0].end.row
 8495            });
 8496            let selections_selecting = selections
 8497                .iter()
 8498                .any(|selection| selection.start != selection.end);
 8499            let advance_downwards = action.advance_downwards
 8500                && selections_on_single_row
 8501                && !selections_selecting
 8502                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8503
 8504            if advance_downwards {
 8505                let snapshot = this.buffer.read(cx).snapshot(cx);
 8506
 8507                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8508                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8509                        let mut point = display_point.to_point(display_snapshot);
 8510                        point.row += 1;
 8511                        point = snapshot.clip_point(point, Bias::Left);
 8512                        let display_point = point.to_display_point(display_snapshot);
 8513                        let goal = SelectionGoal::HorizontalPosition(
 8514                            display_snapshot
 8515                                .x_for_display_point(display_point, text_layout_details)
 8516                                .into(),
 8517                        );
 8518                        (display_point, goal)
 8519                    })
 8520                });
 8521            }
 8522        });
 8523    }
 8524
 8525    pub fn select_enclosing_symbol(
 8526        &mut self,
 8527        _: &SelectEnclosingSymbol,
 8528        cx: &mut ViewContext<Self>,
 8529    ) {
 8530        let buffer = self.buffer.read(cx).snapshot(cx);
 8531        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8532
 8533        fn update_selection(
 8534            selection: &Selection<usize>,
 8535            buffer_snap: &MultiBufferSnapshot,
 8536        ) -> Option<Selection<usize>> {
 8537            let cursor = selection.head();
 8538            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8539            for symbol in symbols.iter().rev() {
 8540                let start = symbol.range.start.to_offset(buffer_snap);
 8541                let end = symbol.range.end.to_offset(buffer_snap);
 8542                let new_range = start..end;
 8543                if start < selection.start || end > selection.end {
 8544                    return Some(Selection {
 8545                        id: selection.id,
 8546                        start: new_range.start,
 8547                        end: new_range.end,
 8548                        goal: SelectionGoal::None,
 8549                        reversed: selection.reversed,
 8550                    });
 8551                }
 8552            }
 8553            None
 8554        }
 8555
 8556        let mut selected_larger_symbol = false;
 8557        let new_selections = old_selections
 8558            .iter()
 8559            .map(|selection| match update_selection(selection, &buffer) {
 8560                Some(new_selection) => {
 8561                    if new_selection.range() != selection.range() {
 8562                        selected_larger_symbol = true;
 8563                    }
 8564                    new_selection
 8565                }
 8566                None => selection.clone(),
 8567            })
 8568            .collect::<Vec<_>>();
 8569
 8570        if selected_larger_symbol {
 8571            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8572                s.select(new_selections);
 8573            });
 8574        }
 8575    }
 8576
 8577    pub fn select_larger_syntax_node(
 8578        &mut self,
 8579        _: &SelectLargerSyntaxNode,
 8580        cx: &mut ViewContext<Self>,
 8581    ) {
 8582        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8583        let buffer = self.buffer.read(cx).snapshot(cx);
 8584        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8585
 8586        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8587        let mut selected_larger_node = false;
 8588        let new_selections = old_selections
 8589            .iter()
 8590            .map(|selection| {
 8591                let old_range = selection.start..selection.end;
 8592                let mut new_range = old_range.clone();
 8593                while let Some(containing_range) =
 8594                    buffer.range_for_syntax_ancestor(new_range.clone())
 8595                {
 8596                    new_range = containing_range;
 8597                    if !display_map.intersects_fold(new_range.start)
 8598                        && !display_map.intersects_fold(new_range.end)
 8599                    {
 8600                        break;
 8601                    }
 8602                }
 8603
 8604                selected_larger_node |= new_range != old_range;
 8605                Selection {
 8606                    id: selection.id,
 8607                    start: new_range.start,
 8608                    end: new_range.end,
 8609                    goal: SelectionGoal::None,
 8610                    reversed: selection.reversed,
 8611                }
 8612            })
 8613            .collect::<Vec<_>>();
 8614
 8615        if selected_larger_node {
 8616            stack.push(old_selections);
 8617            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8618                s.select(new_selections);
 8619            });
 8620        }
 8621        self.select_larger_syntax_node_stack = stack;
 8622    }
 8623
 8624    pub fn select_smaller_syntax_node(
 8625        &mut self,
 8626        _: &SelectSmallerSyntaxNode,
 8627        cx: &mut ViewContext<Self>,
 8628    ) {
 8629        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8630        if let Some(selections) = stack.pop() {
 8631            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8632                s.select(selections.to_vec());
 8633            });
 8634        }
 8635        self.select_larger_syntax_node_stack = stack;
 8636    }
 8637
 8638    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8639        if !EditorSettings::get_global(cx).gutter.runnables {
 8640            self.clear_tasks();
 8641            return Task::ready(());
 8642        }
 8643        let project = self.project.as_ref().map(Model::downgrade);
 8644        cx.spawn(|this, mut cx| async move {
 8645            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8646            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8647                return;
 8648            };
 8649            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8650                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8651            }) else {
 8652                return;
 8653            };
 8654
 8655            let hide_runnables = project
 8656                .update(&mut cx, |project, cx| {
 8657                    // Do not display any test indicators in non-dev server remote projects.
 8658                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8659                })
 8660                .unwrap_or(true);
 8661            if hide_runnables {
 8662                return;
 8663            }
 8664            let new_rows =
 8665                cx.background_executor()
 8666                    .spawn({
 8667                        let snapshot = display_snapshot.clone();
 8668                        async move {
 8669                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8670                        }
 8671                    })
 8672                    .await;
 8673            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8674
 8675            this.update(&mut cx, |this, _| {
 8676                this.clear_tasks();
 8677                for (key, value) in rows {
 8678                    this.insert_tasks(key, value);
 8679                }
 8680            })
 8681            .ok();
 8682        })
 8683    }
 8684    fn fetch_runnable_ranges(
 8685        snapshot: &DisplaySnapshot,
 8686        range: Range<Anchor>,
 8687    ) -> Vec<language::RunnableRange> {
 8688        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8689    }
 8690
 8691    fn runnable_rows(
 8692        project: Model<Project>,
 8693        snapshot: DisplaySnapshot,
 8694        runnable_ranges: Vec<RunnableRange>,
 8695        mut cx: AsyncWindowContext,
 8696    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8697        runnable_ranges
 8698            .into_iter()
 8699            .filter_map(|mut runnable| {
 8700                let tasks = cx
 8701                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8702                    .ok()?;
 8703                if tasks.is_empty() {
 8704                    return None;
 8705                }
 8706
 8707                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8708
 8709                let row = snapshot
 8710                    .buffer_snapshot
 8711                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8712                    .1
 8713                    .start
 8714                    .row;
 8715
 8716                let context_range =
 8717                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8718                Some((
 8719                    (runnable.buffer_id, row),
 8720                    RunnableTasks {
 8721                        templates: tasks,
 8722                        offset: MultiBufferOffset(runnable.run_range.start),
 8723                        context_range,
 8724                        column: point.column,
 8725                        extra_variables: runnable.extra_captures,
 8726                    },
 8727                ))
 8728            })
 8729            .collect()
 8730    }
 8731
 8732    fn templates_with_tags(
 8733        project: &Model<Project>,
 8734        runnable: &mut Runnable,
 8735        cx: &WindowContext<'_>,
 8736    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8737        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8738            let (worktree_id, file) = project
 8739                .buffer_for_id(runnable.buffer, cx)
 8740                .and_then(|buffer| buffer.read(cx).file())
 8741                .map(|file| (file.worktree_id(cx), file.clone()))
 8742                .unzip();
 8743
 8744            (
 8745                project.task_store().read(cx).task_inventory().cloned(),
 8746                worktree_id,
 8747                file,
 8748            )
 8749        });
 8750
 8751        let tags = mem::take(&mut runnable.tags);
 8752        let mut tags: Vec<_> = tags
 8753            .into_iter()
 8754            .flat_map(|tag| {
 8755                let tag = tag.0.clone();
 8756                inventory
 8757                    .as_ref()
 8758                    .into_iter()
 8759                    .flat_map(|inventory| {
 8760                        inventory.read(cx).list_tasks(
 8761                            file.clone(),
 8762                            Some(runnable.language.clone()),
 8763                            worktree_id,
 8764                            cx,
 8765                        )
 8766                    })
 8767                    .filter(move |(_, template)| {
 8768                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8769                    })
 8770            })
 8771            .sorted_by_key(|(kind, _)| kind.to_owned())
 8772            .collect();
 8773        if let Some((leading_tag_source, _)) = tags.first() {
 8774            // Strongest source wins; if we have worktree tag binding, prefer that to
 8775            // global and language bindings;
 8776            // if we have a global binding, prefer that to language binding.
 8777            let first_mismatch = tags
 8778                .iter()
 8779                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8780            if let Some(index) = first_mismatch {
 8781                tags.truncate(index);
 8782            }
 8783        }
 8784
 8785        tags
 8786    }
 8787
 8788    pub fn move_to_enclosing_bracket(
 8789        &mut self,
 8790        _: &MoveToEnclosingBracket,
 8791        cx: &mut ViewContext<Self>,
 8792    ) {
 8793        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8794            s.move_offsets_with(|snapshot, selection| {
 8795                let Some(enclosing_bracket_ranges) =
 8796                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8797                else {
 8798                    return;
 8799                };
 8800
 8801                let mut best_length = usize::MAX;
 8802                let mut best_inside = false;
 8803                let mut best_in_bracket_range = false;
 8804                let mut best_destination = None;
 8805                for (open, close) in enclosing_bracket_ranges {
 8806                    let close = close.to_inclusive();
 8807                    let length = close.end() - open.start;
 8808                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8809                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8810                        || close.contains(&selection.head());
 8811
 8812                    // If best is next to a bracket and current isn't, skip
 8813                    if !in_bracket_range && best_in_bracket_range {
 8814                        continue;
 8815                    }
 8816
 8817                    // Prefer smaller lengths unless best is inside and current isn't
 8818                    if length > best_length && (best_inside || !inside) {
 8819                        continue;
 8820                    }
 8821
 8822                    best_length = length;
 8823                    best_inside = inside;
 8824                    best_in_bracket_range = in_bracket_range;
 8825                    best_destination = Some(
 8826                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8827                            if inside {
 8828                                open.end
 8829                            } else {
 8830                                open.start
 8831                            }
 8832                        } else if inside {
 8833                            *close.start()
 8834                        } else {
 8835                            *close.end()
 8836                        },
 8837                    );
 8838                }
 8839
 8840                if let Some(destination) = best_destination {
 8841                    selection.collapse_to(destination, SelectionGoal::None);
 8842                }
 8843            })
 8844        });
 8845    }
 8846
 8847    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8848        self.end_selection(cx);
 8849        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8850        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8851            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8852            self.select_next_state = entry.select_next_state;
 8853            self.select_prev_state = entry.select_prev_state;
 8854            self.add_selections_state = entry.add_selections_state;
 8855            self.request_autoscroll(Autoscroll::newest(), cx);
 8856        }
 8857        self.selection_history.mode = SelectionHistoryMode::Normal;
 8858    }
 8859
 8860    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8861        self.end_selection(cx);
 8862        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8863        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8864            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8865            self.select_next_state = entry.select_next_state;
 8866            self.select_prev_state = entry.select_prev_state;
 8867            self.add_selections_state = entry.add_selections_state;
 8868            self.request_autoscroll(Autoscroll::newest(), cx);
 8869        }
 8870        self.selection_history.mode = SelectionHistoryMode::Normal;
 8871    }
 8872
 8873    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8874        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8875    }
 8876
 8877    pub fn expand_excerpts_down(
 8878        &mut self,
 8879        action: &ExpandExcerptsDown,
 8880        cx: &mut ViewContext<Self>,
 8881    ) {
 8882        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8883    }
 8884
 8885    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8886        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8887    }
 8888
 8889    pub fn expand_excerpts_for_direction(
 8890        &mut self,
 8891        lines: u32,
 8892        direction: ExpandExcerptDirection,
 8893        cx: &mut ViewContext<Self>,
 8894    ) {
 8895        let selections = self.selections.disjoint_anchors();
 8896
 8897        let lines = if lines == 0 {
 8898            EditorSettings::get_global(cx).expand_excerpt_lines
 8899        } else {
 8900            lines
 8901        };
 8902
 8903        self.buffer.update(cx, |buffer, cx| {
 8904            buffer.expand_excerpts(
 8905                selections
 8906                    .iter()
 8907                    .map(|selection| selection.head().excerpt_id)
 8908                    .dedup(),
 8909                lines,
 8910                direction,
 8911                cx,
 8912            )
 8913        })
 8914    }
 8915
 8916    pub fn expand_excerpt(
 8917        &mut self,
 8918        excerpt: ExcerptId,
 8919        direction: ExpandExcerptDirection,
 8920        cx: &mut ViewContext<Self>,
 8921    ) {
 8922        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8923        self.buffer.update(cx, |buffer, cx| {
 8924            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8925        })
 8926    }
 8927
 8928    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8929        self.go_to_diagnostic_impl(Direction::Next, cx)
 8930    }
 8931
 8932    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8933        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8934    }
 8935
 8936    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8937        let buffer = self.buffer.read(cx).snapshot(cx);
 8938        let selection = self.selections.newest::<usize>(cx);
 8939
 8940        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8941        if direction == Direction::Next {
 8942            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8943                let (group_id, jump_to) = popover.activation_info();
 8944                if self.activate_diagnostics(group_id, cx) {
 8945                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8946                        let mut new_selection = s.newest_anchor().clone();
 8947                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8948                        s.select_anchors(vec![new_selection.clone()]);
 8949                    });
 8950                }
 8951                return;
 8952            }
 8953        }
 8954
 8955        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8956            active_diagnostics
 8957                .primary_range
 8958                .to_offset(&buffer)
 8959                .to_inclusive()
 8960        });
 8961        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8962            if active_primary_range.contains(&selection.head()) {
 8963                *active_primary_range.start()
 8964            } else {
 8965                selection.head()
 8966            }
 8967        } else {
 8968            selection.head()
 8969        };
 8970        let snapshot = self.snapshot(cx);
 8971        loop {
 8972            let diagnostics = if direction == Direction::Prev {
 8973                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8974            } else {
 8975                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8976            }
 8977            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8978            let group = diagnostics
 8979                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8980                // be sorted in a stable way
 8981                // skip until we are at current active diagnostic, if it exists
 8982                .skip_while(|entry| {
 8983                    (match direction {
 8984                        Direction::Prev => entry.range.start >= search_start,
 8985                        Direction::Next => entry.range.start <= search_start,
 8986                    }) && self
 8987                        .active_diagnostics
 8988                        .as_ref()
 8989                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8990                })
 8991                .find_map(|entry| {
 8992                    if entry.diagnostic.is_primary
 8993                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8994                        && !entry.range.is_empty()
 8995                        // if we match with the active diagnostic, skip it
 8996                        && Some(entry.diagnostic.group_id)
 8997                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8998                    {
 8999                        Some((entry.range, entry.diagnostic.group_id))
 9000                    } else {
 9001                        None
 9002                    }
 9003                });
 9004
 9005            if let Some((primary_range, group_id)) = group {
 9006                if self.activate_diagnostics(group_id, cx) {
 9007                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9008                        s.select(vec![Selection {
 9009                            id: selection.id,
 9010                            start: primary_range.start,
 9011                            end: primary_range.start,
 9012                            reversed: false,
 9013                            goal: SelectionGoal::None,
 9014                        }]);
 9015                    });
 9016                }
 9017                break;
 9018            } else {
 9019                // Cycle around to the start of the buffer, potentially moving back to the start of
 9020                // the currently active diagnostic.
 9021                active_primary_range.take();
 9022                if direction == Direction::Prev {
 9023                    if search_start == buffer.len() {
 9024                        break;
 9025                    } else {
 9026                        search_start = buffer.len();
 9027                    }
 9028                } else if search_start == 0 {
 9029                    break;
 9030                } else {
 9031                    search_start = 0;
 9032                }
 9033            }
 9034        }
 9035    }
 9036
 9037    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9038        let snapshot = self.snapshot(cx);
 9039        let selection = self.selections.newest::<Point>(cx);
 9040        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9041    }
 9042
 9043    fn go_to_hunk_after_position(
 9044        &mut self,
 9045        snapshot: &EditorSnapshot,
 9046        position: Point,
 9047        cx: &mut ViewContext<'_, Editor>,
 9048    ) -> Option<MultiBufferDiffHunk> {
 9049        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9050            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9051                snapshot,
 9052                position,
 9053                ix > 0,
 9054                snapshot.diff_map.diff_hunks_in_range(
 9055                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9056                    &snapshot.buffer_snapshot,
 9057                ),
 9058                cx,
 9059            ) {
 9060                return Some(hunk);
 9061            }
 9062        }
 9063        None
 9064    }
 9065
 9066    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9067        let snapshot = self.snapshot(cx);
 9068        let selection = self.selections.newest::<Point>(cx);
 9069        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9070    }
 9071
 9072    fn go_to_hunk_before_position(
 9073        &mut self,
 9074        snapshot: &EditorSnapshot,
 9075        position: Point,
 9076        cx: &mut ViewContext<'_, Editor>,
 9077    ) -> Option<MultiBufferDiffHunk> {
 9078        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9079            .into_iter()
 9080            .enumerate()
 9081        {
 9082            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9083                snapshot,
 9084                position,
 9085                ix > 0,
 9086                snapshot
 9087                    .diff_map
 9088                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9089                cx,
 9090            ) {
 9091                return Some(hunk);
 9092            }
 9093        }
 9094        None
 9095    }
 9096
 9097    fn go_to_next_hunk_in_direction(
 9098        &mut self,
 9099        snapshot: &DisplaySnapshot,
 9100        initial_point: Point,
 9101        is_wrapped: bool,
 9102        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9103        cx: &mut ViewContext<Editor>,
 9104    ) -> Option<MultiBufferDiffHunk> {
 9105        let display_point = initial_point.to_display_point(snapshot);
 9106        let mut hunks = hunks
 9107            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9108            .filter(|(display_hunk, _)| {
 9109                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9110            })
 9111            .dedup();
 9112
 9113        if let Some((display_hunk, hunk)) = hunks.next() {
 9114            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9115                let row = display_hunk.start_display_row();
 9116                let point = DisplayPoint::new(row, 0);
 9117                s.select_display_ranges([point..point]);
 9118            });
 9119
 9120            Some(hunk)
 9121        } else {
 9122            None
 9123        }
 9124    }
 9125
 9126    pub fn go_to_definition(
 9127        &mut self,
 9128        _: &GoToDefinition,
 9129        cx: &mut ViewContext<Self>,
 9130    ) -> Task<Result<Navigated>> {
 9131        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9132        cx.spawn(|editor, mut cx| async move {
 9133            if definition.await? == Navigated::Yes {
 9134                return Ok(Navigated::Yes);
 9135            }
 9136            match editor.update(&mut cx, |editor, cx| {
 9137                editor.find_all_references(&FindAllReferences, cx)
 9138            })? {
 9139                Some(references) => references.await,
 9140                None => Ok(Navigated::No),
 9141            }
 9142        })
 9143    }
 9144
 9145    pub fn go_to_declaration(
 9146        &mut self,
 9147        _: &GoToDeclaration,
 9148        cx: &mut ViewContext<Self>,
 9149    ) -> Task<Result<Navigated>> {
 9150        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9151    }
 9152
 9153    pub fn go_to_declaration_split(
 9154        &mut self,
 9155        _: &GoToDeclaration,
 9156        cx: &mut ViewContext<Self>,
 9157    ) -> Task<Result<Navigated>> {
 9158        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9159    }
 9160
 9161    pub fn go_to_implementation(
 9162        &mut self,
 9163        _: &GoToImplementation,
 9164        cx: &mut ViewContext<Self>,
 9165    ) -> Task<Result<Navigated>> {
 9166        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9167    }
 9168
 9169    pub fn go_to_implementation_split(
 9170        &mut self,
 9171        _: &GoToImplementationSplit,
 9172        cx: &mut ViewContext<Self>,
 9173    ) -> Task<Result<Navigated>> {
 9174        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9175    }
 9176
 9177    pub fn go_to_type_definition(
 9178        &mut self,
 9179        _: &GoToTypeDefinition,
 9180        cx: &mut ViewContext<Self>,
 9181    ) -> Task<Result<Navigated>> {
 9182        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9183    }
 9184
 9185    pub fn go_to_definition_split(
 9186        &mut self,
 9187        _: &GoToDefinitionSplit,
 9188        cx: &mut ViewContext<Self>,
 9189    ) -> Task<Result<Navigated>> {
 9190        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9191    }
 9192
 9193    pub fn go_to_type_definition_split(
 9194        &mut self,
 9195        _: &GoToTypeDefinitionSplit,
 9196        cx: &mut ViewContext<Self>,
 9197    ) -> Task<Result<Navigated>> {
 9198        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9199    }
 9200
 9201    fn go_to_definition_of_kind(
 9202        &mut self,
 9203        kind: GotoDefinitionKind,
 9204        split: bool,
 9205        cx: &mut ViewContext<Self>,
 9206    ) -> Task<Result<Navigated>> {
 9207        let Some(provider) = self.semantics_provider.clone() else {
 9208            return Task::ready(Ok(Navigated::No));
 9209        };
 9210        let head = self.selections.newest::<usize>(cx).head();
 9211        let buffer = self.buffer.read(cx);
 9212        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9213            text_anchor
 9214        } else {
 9215            return Task::ready(Ok(Navigated::No));
 9216        };
 9217
 9218        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9219            return Task::ready(Ok(Navigated::No));
 9220        };
 9221
 9222        cx.spawn(|editor, mut cx| async move {
 9223            let definitions = definitions.await?;
 9224            let navigated = editor
 9225                .update(&mut cx, |editor, cx| {
 9226                    editor.navigate_to_hover_links(
 9227                        Some(kind),
 9228                        definitions
 9229                            .into_iter()
 9230                            .filter(|location| {
 9231                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9232                            })
 9233                            .map(HoverLink::Text)
 9234                            .collect::<Vec<_>>(),
 9235                        split,
 9236                        cx,
 9237                    )
 9238                })?
 9239                .await?;
 9240            anyhow::Ok(navigated)
 9241        })
 9242    }
 9243
 9244    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9245        let position = self.selections.newest_anchor().head();
 9246        let Some((buffer, buffer_position)) =
 9247            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9248        else {
 9249            return;
 9250        };
 9251
 9252        cx.spawn(|editor, mut cx| async move {
 9253            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9254                editor.update(&mut cx, |_, cx| {
 9255                    cx.open_url(&url);
 9256                })
 9257            } else {
 9258                Ok(())
 9259            }
 9260        })
 9261        .detach();
 9262    }
 9263
 9264    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9265        let Some(workspace) = self.workspace() else {
 9266            return;
 9267        };
 9268
 9269        let position = self.selections.newest_anchor().head();
 9270
 9271        let Some((buffer, buffer_position)) =
 9272            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9273        else {
 9274            return;
 9275        };
 9276
 9277        let project = self.project.clone();
 9278
 9279        cx.spawn(|_, mut cx| async move {
 9280            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9281
 9282            if let Some((_, path)) = result {
 9283                workspace
 9284                    .update(&mut cx, |workspace, cx| {
 9285                        workspace.open_resolved_path(path, cx)
 9286                    })?
 9287                    .await?;
 9288            }
 9289            anyhow::Ok(())
 9290        })
 9291        .detach();
 9292    }
 9293
 9294    pub(crate) fn navigate_to_hover_links(
 9295        &mut self,
 9296        kind: Option<GotoDefinitionKind>,
 9297        mut definitions: Vec<HoverLink>,
 9298        split: bool,
 9299        cx: &mut ViewContext<Editor>,
 9300    ) -> Task<Result<Navigated>> {
 9301        // If there is one definition, just open it directly
 9302        if definitions.len() == 1 {
 9303            let definition = definitions.pop().unwrap();
 9304
 9305            enum TargetTaskResult {
 9306                Location(Option<Location>),
 9307                AlreadyNavigated,
 9308            }
 9309
 9310            let target_task = match definition {
 9311                HoverLink::Text(link) => {
 9312                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9313                }
 9314                HoverLink::InlayHint(lsp_location, server_id) => {
 9315                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9316                    cx.background_executor().spawn(async move {
 9317                        let location = computation.await?;
 9318                        Ok(TargetTaskResult::Location(location))
 9319                    })
 9320                }
 9321                HoverLink::Url(url) => {
 9322                    cx.open_url(&url);
 9323                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9324                }
 9325                HoverLink::File(path) => {
 9326                    if let Some(workspace) = self.workspace() {
 9327                        cx.spawn(|_, mut cx| async move {
 9328                            workspace
 9329                                .update(&mut cx, |workspace, cx| {
 9330                                    workspace.open_resolved_path(path, cx)
 9331                                })?
 9332                                .await
 9333                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9334                        })
 9335                    } else {
 9336                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9337                    }
 9338                }
 9339            };
 9340            cx.spawn(|editor, mut cx| async move {
 9341                let target = match target_task.await.context("target resolution task")? {
 9342                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9343                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9344                    TargetTaskResult::Location(Some(target)) => target,
 9345                };
 9346
 9347                editor.update(&mut cx, |editor, cx| {
 9348                    let Some(workspace) = editor.workspace() else {
 9349                        return Navigated::No;
 9350                    };
 9351                    let pane = workspace.read(cx).active_pane().clone();
 9352
 9353                    let range = target.range.to_offset(target.buffer.read(cx));
 9354                    let range = editor.range_for_match(&range);
 9355
 9356                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9357                        let buffer = target.buffer.read(cx);
 9358                        let range = check_multiline_range(buffer, range);
 9359                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9360                            s.select_ranges([range]);
 9361                        });
 9362                    } else {
 9363                        cx.window_context().defer(move |cx| {
 9364                            let target_editor: View<Self> =
 9365                                workspace.update(cx, |workspace, cx| {
 9366                                    let pane = if split {
 9367                                        workspace.adjacent_pane(cx)
 9368                                    } else {
 9369                                        workspace.active_pane().clone()
 9370                                    };
 9371
 9372                                    workspace.open_project_item(
 9373                                        pane,
 9374                                        target.buffer.clone(),
 9375                                        true,
 9376                                        true,
 9377                                        cx,
 9378                                    )
 9379                                });
 9380                            target_editor.update(cx, |target_editor, cx| {
 9381                                // When selecting a definition in a different buffer, disable the nav history
 9382                                // to avoid creating a history entry at the previous cursor location.
 9383                                pane.update(cx, |pane, _| pane.disable_history());
 9384                                let buffer = target.buffer.read(cx);
 9385                                let range = check_multiline_range(buffer, range);
 9386                                target_editor.change_selections(
 9387                                    Some(Autoscroll::focused()),
 9388                                    cx,
 9389                                    |s| {
 9390                                        s.select_ranges([range]);
 9391                                    },
 9392                                );
 9393                                pane.update(cx, |pane, _| pane.enable_history());
 9394                            });
 9395                        });
 9396                    }
 9397                    Navigated::Yes
 9398                })
 9399            })
 9400        } else if !definitions.is_empty() {
 9401            cx.spawn(|editor, mut cx| async move {
 9402                let (title, location_tasks, workspace) = editor
 9403                    .update(&mut cx, |editor, cx| {
 9404                        let tab_kind = match kind {
 9405                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9406                            _ => "Definitions",
 9407                        };
 9408                        let title = definitions
 9409                            .iter()
 9410                            .find_map(|definition| match definition {
 9411                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9412                                    let buffer = origin.buffer.read(cx);
 9413                                    format!(
 9414                                        "{} for {}",
 9415                                        tab_kind,
 9416                                        buffer
 9417                                            .text_for_range(origin.range.clone())
 9418                                            .collect::<String>()
 9419                                    )
 9420                                }),
 9421                                HoverLink::InlayHint(_, _) => None,
 9422                                HoverLink::Url(_) => None,
 9423                                HoverLink::File(_) => None,
 9424                            })
 9425                            .unwrap_or(tab_kind.to_string());
 9426                        let location_tasks = definitions
 9427                            .into_iter()
 9428                            .map(|definition| match definition {
 9429                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9430                                HoverLink::InlayHint(lsp_location, server_id) => {
 9431                                    editor.compute_target_location(lsp_location, server_id, cx)
 9432                                }
 9433                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9434                                HoverLink::File(_) => Task::ready(Ok(None)),
 9435                            })
 9436                            .collect::<Vec<_>>();
 9437                        (title, location_tasks, editor.workspace().clone())
 9438                    })
 9439                    .context("location tasks preparation")?;
 9440
 9441                let locations = future::join_all(location_tasks)
 9442                    .await
 9443                    .into_iter()
 9444                    .filter_map(|location| location.transpose())
 9445                    .collect::<Result<_>>()
 9446                    .context("location tasks")?;
 9447
 9448                let Some(workspace) = workspace else {
 9449                    return Ok(Navigated::No);
 9450                };
 9451                let opened = workspace
 9452                    .update(&mut cx, |workspace, cx| {
 9453                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9454                    })
 9455                    .ok();
 9456
 9457                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9458            })
 9459        } else {
 9460            Task::ready(Ok(Navigated::No))
 9461        }
 9462    }
 9463
 9464    fn compute_target_location(
 9465        &self,
 9466        lsp_location: lsp::Location,
 9467        server_id: LanguageServerId,
 9468        cx: &mut ViewContext<Self>,
 9469    ) -> Task<anyhow::Result<Option<Location>>> {
 9470        let Some(project) = self.project.clone() else {
 9471            return Task::Ready(Some(Ok(None)));
 9472        };
 9473
 9474        cx.spawn(move |editor, mut cx| async move {
 9475            let location_task = editor.update(&mut cx, |_, cx| {
 9476                project.update(cx, |project, cx| {
 9477                    let language_server_name = project
 9478                        .language_server_statuses(cx)
 9479                        .find(|(id, _)| server_id == *id)
 9480                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9481                    language_server_name.map(|language_server_name| {
 9482                        project.open_local_buffer_via_lsp(
 9483                            lsp_location.uri.clone(),
 9484                            server_id,
 9485                            language_server_name,
 9486                            cx,
 9487                        )
 9488                    })
 9489                })
 9490            })?;
 9491            let location = match location_task {
 9492                Some(task) => Some({
 9493                    let target_buffer_handle = task.await.context("open local buffer")?;
 9494                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9495                        let target_start = target_buffer
 9496                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9497                        let target_end = target_buffer
 9498                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9499                        target_buffer.anchor_after(target_start)
 9500                            ..target_buffer.anchor_before(target_end)
 9501                    })?;
 9502                    Location {
 9503                        buffer: target_buffer_handle,
 9504                        range,
 9505                    }
 9506                }),
 9507                None => None,
 9508            };
 9509            Ok(location)
 9510        })
 9511    }
 9512
 9513    pub fn find_all_references(
 9514        &mut self,
 9515        _: &FindAllReferences,
 9516        cx: &mut ViewContext<Self>,
 9517    ) -> Option<Task<Result<Navigated>>> {
 9518        let selection = self.selections.newest::<usize>(cx);
 9519        let multi_buffer = self.buffer.read(cx);
 9520        let head = selection.head();
 9521
 9522        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9523        let head_anchor = multi_buffer_snapshot.anchor_at(
 9524            head,
 9525            if head < selection.tail() {
 9526                Bias::Right
 9527            } else {
 9528                Bias::Left
 9529            },
 9530        );
 9531
 9532        match self
 9533            .find_all_references_task_sources
 9534            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9535        {
 9536            Ok(_) => {
 9537                log::info!(
 9538                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9539                );
 9540                return None;
 9541            }
 9542            Err(i) => {
 9543                self.find_all_references_task_sources.insert(i, head_anchor);
 9544            }
 9545        }
 9546
 9547        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9548        let workspace = self.workspace()?;
 9549        let project = workspace.read(cx).project().clone();
 9550        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9551        Some(cx.spawn(|editor, mut cx| async move {
 9552            let _cleanup = defer({
 9553                let mut cx = cx.clone();
 9554                move || {
 9555                    let _ = editor.update(&mut cx, |editor, _| {
 9556                        if let Ok(i) =
 9557                            editor
 9558                                .find_all_references_task_sources
 9559                                .binary_search_by(|anchor| {
 9560                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9561                                })
 9562                        {
 9563                            editor.find_all_references_task_sources.remove(i);
 9564                        }
 9565                    });
 9566                }
 9567            });
 9568
 9569            let locations = references.await?;
 9570            if locations.is_empty() {
 9571                return anyhow::Ok(Navigated::No);
 9572            }
 9573
 9574            workspace.update(&mut cx, |workspace, cx| {
 9575                let title = locations
 9576                    .first()
 9577                    .as_ref()
 9578                    .map(|location| {
 9579                        let buffer = location.buffer.read(cx);
 9580                        format!(
 9581                            "References to `{}`",
 9582                            buffer
 9583                                .text_for_range(location.range.clone())
 9584                                .collect::<String>()
 9585                        )
 9586                    })
 9587                    .unwrap();
 9588                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9589                Navigated::Yes
 9590            })
 9591        }))
 9592    }
 9593
 9594    /// Opens a multibuffer with the given project locations in it
 9595    pub fn open_locations_in_multibuffer(
 9596        workspace: &mut Workspace,
 9597        mut locations: Vec<Location>,
 9598        title: String,
 9599        split: bool,
 9600        cx: &mut ViewContext<Workspace>,
 9601    ) {
 9602        // If there are multiple definitions, open them in a multibuffer
 9603        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9604        let mut locations = locations.into_iter().peekable();
 9605        let mut ranges_to_highlight = Vec::new();
 9606        let capability = workspace.project().read(cx).capability();
 9607
 9608        let excerpt_buffer = cx.new_model(|cx| {
 9609            let mut multibuffer = MultiBuffer::new(capability);
 9610            while let Some(location) = locations.next() {
 9611                let buffer = location.buffer.read(cx);
 9612                let mut ranges_for_buffer = Vec::new();
 9613                let range = location.range.to_offset(buffer);
 9614                ranges_for_buffer.push(range.clone());
 9615
 9616                while let Some(next_location) = locations.peek() {
 9617                    if next_location.buffer == location.buffer {
 9618                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9619                        locations.next();
 9620                    } else {
 9621                        break;
 9622                    }
 9623                }
 9624
 9625                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9626                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9627                    location.buffer.clone(),
 9628                    ranges_for_buffer,
 9629                    DEFAULT_MULTIBUFFER_CONTEXT,
 9630                    cx,
 9631                ))
 9632            }
 9633
 9634            multibuffer.with_title(title)
 9635        });
 9636
 9637        let editor = cx.new_view(|cx| {
 9638            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9639        });
 9640        editor.update(cx, |editor, cx| {
 9641            if let Some(first_range) = ranges_to_highlight.first() {
 9642                editor.change_selections(None, cx, |selections| {
 9643                    selections.clear_disjoint();
 9644                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9645                });
 9646            }
 9647            editor.highlight_background::<Self>(
 9648                &ranges_to_highlight,
 9649                |theme| theme.editor_highlighted_line_background,
 9650                cx,
 9651            );
 9652        });
 9653
 9654        let item = Box::new(editor);
 9655        let item_id = item.item_id();
 9656
 9657        if split {
 9658            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9659        } else {
 9660            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9661                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9662                    pane.close_current_preview_item(cx)
 9663                } else {
 9664                    None
 9665                }
 9666            });
 9667            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9668        }
 9669        workspace.active_pane().update(cx, |pane, cx| {
 9670            pane.set_preview_item_id(Some(item_id), cx);
 9671        });
 9672    }
 9673
 9674    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9675        use language::ToOffset as _;
 9676
 9677        let provider = self.semantics_provider.clone()?;
 9678        let selection = self.selections.newest_anchor().clone();
 9679        let (cursor_buffer, cursor_buffer_position) = self
 9680            .buffer
 9681            .read(cx)
 9682            .text_anchor_for_position(selection.head(), cx)?;
 9683        let (tail_buffer, cursor_buffer_position_end) = self
 9684            .buffer
 9685            .read(cx)
 9686            .text_anchor_for_position(selection.tail(), cx)?;
 9687        if tail_buffer != cursor_buffer {
 9688            return None;
 9689        }
 9690
 9691        let snapshot = cursor_buffer.read(cx).snapshot();
 9692        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9693        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9694        let prepare_rename = provider
 9695            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9696            .unwrap_or_else(|| Task::ready(Ok(None)));
 9697        drop(snapshot);
 9698
 9699        Some(cx.spawn(|this, mut cx| async move {
 9700            let rename_range = if let Some(range) = prepare_rename.await? {
 9701                Some(range)
 9702            } else {
 9703                this.update(&mut cx, |this, cx| {
 9704                    let buffer = this.buffer.read(cx).snapshot(cx);
 9705                    let mut buffer_highlights = this
 9706                        .document_highlights_for_position(selection.head(), &buffer)
 9707                        .filter(|highlight| {
 9708                            highlight.start.excerpt_id == selection.head().excerpt_id
 9709                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9710                        });
 9711                    buffer_highlights
 9712                        .next()
 9713                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9714                })?
 9715            };
 9716            if let Some(rename_range) = rename_range {
 9717                this.update(&mut cx, |this, cx| {
 9718                    let snapshot = cursor_buffer.read(cx).snapshot();
 9719                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9720                    let cursor_offset_in_rename_range =
 9721                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9722                    let cursor_offset_in_rename_range_end =
 9723                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9724
 9725                    this.take_rename(false, cx);
 9726                    let buffer = this.buffer.read(cx).read(cx);
 9727                    let cursor_offset = selection.head().to_offset(&buffer);
 9728                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9729                    let rename_end = rename_start + rename_buffer_range.len();
 9730                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9731                    let mut old_highlight_id = None;
 9732                    let old_name: Arc<str> = buffer
 9733                        .chunks(rename_start..rename_end, true)
 9734                        .map(|chunk| {
 9735                            if old_highlight_id.is_none() {
 9736                                old_highlight_id = chunk.syntax_highlight_id;
 9737                            }
 9738                            chunk.text
 9739                        })
 9740                        .collect::<String>()
 9741                        .into();
 9742
 9743                    drop(buffer);
 9744
 9745                    // Position the selection in the rename editor so that it matches the current selection.
 9746                    this.show_local_selections = false;
 9747                    let rename_editor = cx.new_view(|cx| {
 9748                        let mut editor = Editor::single_line(cx);
 9749                        editor.buffer.update(cx, |buffer, cx| {
 9750                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9751                        });
 9752                        let rename_selection_range = match cursor_offset_in_rename_range
 9753                            .cmp(&cursor_offset_in_rename_range_end)
 9754                        {
 9755                            Ordering::Equal => {
 9756                                editor.select_all(&SelectAll, cx);
 9757                                return editor;
 9758                            }
 9759                            Ordering::Less => {
 9760                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9761                            }
 9762                            Ordering::Greater => {
 9763                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9764                            }
 9765                        };
 9766                        if rename_selection_range.end > old_name.len() {
 9767                            editor.select_all(&SelectAll, cx);
 9768                        } else {
 9769                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9770                                s.select_ranges([rename_selection_range]);
 9771                            });
 9772                        }
 9773                        editor
 9774                    });
 9775                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9776                        if e == &EditorEvent::Focused {
 9777                            cx.emit(EditorEvent::FocusedIn)
 9778                        }
 9779                    })
 9780                    .detach();
 9781
 9782                    let write_highlights =
 9783                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9784                    let read_highlights =
 9785                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9786                    let ranges = write_highlights
 9787                        .iter()
 9788                        .flat_map(|(_, ranges)| ranges.iter())
 9789                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9790                        .cloned()
 9791                        .collect();
 9792
 9793                    this.highlight_text::<Rename>(
 9794                        ranges,
 9795                        HighlightStyle {
 9796                            fade_out: Some(0.6),
 9797                            ..Default::default()
 9798                        },
 9799                        cx,
 9800                    );
 9801                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9802                    cx.focus(&rename_focus_handle);
 9803                    let block_id = this.insert_blocks(
 9804                        [BlockProperties {
 9805                            style: BlockStyle::Flex,
 9806                            placement: BlockPlacement::Below(range.start),
 9807                            height: 1,
 9808                            render: Arc::new({
 9809                                let rename_editor = rename_editor.clone();
 9810                                move |cx: &mut BlockContext| {
 9811                                    let mut text_style = cx.editor_style.text.clone();
 9812                                    if let Some(highlight_style) = old_highlight_id
 9813                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9814                                    {
 9815                                        text_style = text_style.highlight(highlight_style);
 9816                                    }
 9817                                    div()
 9818                                        .block_mouse_down()
 9819                                        .pl(cx.anchor_x)
 9820                                        .child(EditorElement::new(
 9821                                            &rename_editor,
 9822                                            EditorStyle {
 9823                                                background: cx.theme().system().transparent,
 9824                                                local_player: cx.editor_style.local_player,
 9825                                                text: text_style,
 9826                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9827                                                syntax: cx.editor_style.syntax.clone(),
 9828                                                status: cx.editor_style.status.clone(),
 9829                                                inlay_hints_style: HighlightStyle {
 9830                                                    font_weight: Some(FontWeight::BOLD),
 9831                                                    ..make_inlay_hints_style(cx)
 9832                                                },
 9833                                                suggestions_style: HighlightStyle {
 9834                                                    color: Some(cx.theme().status().predictive),
 9835                                                    ..HighlightStyle::default()
 9836                                                },
 9837                                                ..EditorStyle::default()
 9838                                            },
 9839                                        ))
 9840                                        .into_any_element()
 9841                                }
 9842                            }),
 9843                            priority: 0,
 9844                        }],
 9845                        Some(Autoscroll::fit()),
 9846                        cx,
 9847                    )[0];
 9848                    this.pending_rename = Some(RenameState {
 9849                        range,
 9850                        old_name,
 9851                        editor: rename_editor,
 9852                        block_id,
 9853                    });
 9854                })?;
 9855            }
 9856
 9857            Ok(())
 9858        }))
 9859    }
 9860
 9861    pub fn confirm_rename(
 9862        &mut self,
 9863        _: &ConfirmRename,
 9864        cx: &mut ViewContext<Self>,
 9865    ) -> Option<Task<Result<()>>> {
 9866        let rename = self.take_rename(false, cx)?;
 9867        let workspace = self.workspace()?.downgrade();
 9868        let (buffer, start) = self
 9869            .buffer
 9870            .read(cx)
 9871            .text_anchor_for_position(rename.range.start, cx)?;
 9872        let (end_buffer, _) = self
 9873            .buffer
 9874            .read(cx)
 9875            .text_anchor_for_position(rename.range.end, cx)?;
 9876        if buffer != end_buffer {
 9877            return None;
 9878        }
 9879
 9880        let old_name = rename.old_name;
 9881        let new_name = rename.editor.read(cx).text(cx);
 9882
 9883        let rename = self.semantics_provider.as_ref()?.perform_rename(
 9884            &buffer,
 9885            start,
 9886            new_name.clone(),
 9887            cx,
 9888        )?;
 9889
 9890        Some(cx.spawn(|editor, mut cx| async move {
 9891            let project_transaction = rename.await?;
 9892            Self::open_project_transaction(
 9893                &editor,
 9894                workspace,
 9895                project_transaction,
 9896                format!("Rename: {}{}", old_name, new_name),
 9897                cx.clone(),
 9898            )
 9899            .await?;
 9900
 9901            editor.update(&mut cx, |editor, cx| {
 9902                editor.refresh_document_highlights(cx);
 9903            })?;
 9904            Ok(())
 9905        }))
 9906    }
 9907
 9908    fn take_rename(
 9909        &mut self,
 9910        moving_cursor: bool,
 9911        cx: &mut ViewContext<Self>,
 9912    ) -> Option<RenameState> {
 9913        let rename = self.pending_rename.take()?;
 9914        if rename.editor.focus_handle(cx).is_focused(cx) {
 9915            cx.focus(&self.focus_handle);
 9916        }
 9917
 9918        self.remove_blocks(
 9919            [rename.block_id].into_iter().collect(),
 9920            Some(Autoscroll::fit()),
 9921            cx,
 9922        );
 9923        self.clear_highlights::<Rename>(cx);
 9924        self.show_local_selections = true;
 9925
 9926        if moving_cursor {
 9927            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
 9928                editor.selections.newest::<usize>(cx).head()
 9929            });
 9930
 9931            // Update the selection to match the position of the selection inside
 9932            // the rename editor.
 9933            let snapshot = self.buffer.read(cx).read(cx);
 9934            let rename_range = rename.range.to_offset(&snapshot);
 9935            let cursor_in_editor = snapshot
 9936                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9937                .min(rename_range.end);
 9938            drop(snapshot);
 9939
 9940            self.change_selections(None, cx, |s| {
 9941                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9942            });
 9943        } else {
 9944            self.refresh_document_highlights(cx);
 9945        }
 9946
 9947        Some(rename)
 9948    }
 9949
 9950    pub fn pending_rename(&self) -> Option<&RenameState> {
 9951        self.pending_rename.as_ref()
 9952    }
 9953
 9954    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9955        let project = match &self.project {
 9956            Some(project) => project.clone(),
 9957            None => return None,
 9958        };
 9959
 9960        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
 9961    }
 9962
 9963    fn format_selections(
 9964        &mut self,
 9965        _: &FormatSelections,
 9966        cx: &mut ViewContext<Self>,
 9967    ) -> Option<Task<Result<()>>> {
 9968        let project = match &self.project {
 9969            Some(project) => project.clone(),
 9970            None => return None,
 9971        };
 9972
 9973        let selections = self
 9974            .selections
 9975            .all_adjusted(cx)
 9976            .into_iter()
 9977            .filter(|s| !s.is_empty())
 9978            .collect_vec();
 9979
 9980        Some(self.perform_format(
 9981            project,
 9982            FormatTrigger::Manual,
 9983            FormatTarget::Ranges(selections),
 9984            cx,
 9985        ))
 9986    }
 9987
 9988    fn perform_format(
 9989        &mut self,
 9990        project: Model<Project>,
 9991        trigger: FormatTrigger,
 9992        target: FormatTarget,
 9993        cx: &mut ViewContext<Self>,
 9994    ) -> Task<Result<()>> {
 9995        let buffer = self.buffer().clone();
 9996        let mut buffers = buffer.read(cx).all_buffers();
 9997        if trigger == FormatTrigger::Save {
 9998            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9999        }
10000
10001        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10002        let format = project.update(cx, |project, cx| {
10003            project.format(buffers, true, trigger, target, cx)
10004        });
10005
10006        cx.spawn(|_, mut cx| async move {
10007            let transaction = futures::select_biased! {
10008                () = timeout => {
10009                    log::warn!("timed out waiting for formatting");
10010                    None
10011                }
10012                transaction = format.log_err().fuse() => transaction,
10013            };
10014
10015            buffer
10016                .update(&mut cx, |buffer, cx| {
10017                    if let Some(transaction) = transaction {
10018                        if !buffer.is_singleton() {
10019                            buffer.push_transaction(&transaction.0, cx);
10020                        }
10021                    }
10022
10023                    cx.notify();
10024                })
10025                .ok();
10026
10027            Ok(())
10028        })
10029    }
10030
10031    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10032        if let Some(project) = self.project.clone() {
10033            self.buffer.update(cx, |multi_buffer, cx| {
10034                project.update(cx, |project, cx| {
10035                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10036                });
10037            })
10038        }
10039    }
10040
10041    fn cancel_language_server_work(
10042        &mut self,
10043        _: &actions::CancelLanguageServerWork,
10044        cx: &mut ViewContext<Self>,
10045    ) {
10046        if let Some(project) = self.project.clone() {
10047            self.buffer.update(cx, |multi_buffer, cx| {
10048                project.update(cx, |project, cx| {
10049                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10050                });
10051            })
10052        }
10053    }
10054
10055    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10056        cx.show_character_palette();
10057    }
10058
10059    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10060        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10061            let buffer = self.buffer.read(cx).snapshot(cx);
10062            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10063            let is_valid = buffer
10064                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10065                .any(|entry| {
10066                    entry.diagnostic.is_primary
10067                        && !entry.range.is_empty()
10068                        && entry.range.start == primary_range_start
10069                        && entry.diagnostic.message == active_diagnostics.primary_message
10070                });
10071
10072            if is_valid != active_diagnostics.is_valid {
10073                active_diagnostics.is_valid = is_valid;
10074                let mut new_styles = HashMap::default();
10075                for (block_id, diagnostic) in &active_diagnostics.blocks {
10076                    new_styles.insert(
10077                        *block_id,
10078                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10079                    );
10080                }
10081                self.display_map.update(cx, |display_map, _cx| {
10082                    display_map.replace_blocks(new_styles)
10083                });
10084            }
10085        }
10086    }
10087
10088    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10089        self.dismiss_diagnostics(cx);
10090        let snapshot = self.snapshot(cx);
10091        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10092            let buffer = self.buffer.read(cx).snapshot(cx);
10093
10094            let mut primary_range = None;
10095            let mut primary_message = None;
10096            let mut group_end = Point::zero();
10097            let diagnostic_group = buffer
10098                .diagnostic_group::<MultiBufferPoint>(group_id)
10099                .filter_map(|entry| {
10100                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10101                        && (entry.range.start.row == entry.range.end.row
10102                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10103                    {
10104                        return None;
10105                    }
10106                    if entry.range.end > group_end {
10107                        group_end = entry.range.end;
10108                    }
10109                    if entry.diagnostic.is_primary {
10110                        primary_range = Some(entry.range.clone());
10111                        primary_message = Some(entry.diagnostic.message.clone());
10112                    }
10113                    Some(entry)
10114                })
10115                .collect::<Vec<_>>();
10116            let primary_range = primary_range?;
10117            let primary_message = primary_message?;
10118            let primary_range =
10119                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10120
10121            let blocks = display_map
10122                .insert_blocks(
10123                    diagnostic_group.iter().map(|entry| {
10124                        let diagnostic = entry.diagnostic.clone();
10125                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10126                        BlockProperties {
10127                            style: BlockStyle::Fixed,
10128                            placement: BlockPlacement::Below(
10129                                buffer.anchor_after(entry.range.start),
10130                            ),
10131                            height: message_height,
10132                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10133                            priority: 0,
10134                        }
10135                    }),
10136                    cx,
10137                )
10138                .into_iter()
10139                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10140                .collect();
10141
10142            Some(ActiveDiagnosticGroup {
10143                primary_range,
10144                primary_message,
10145                group_id,
10146                blocks,
10147                is_valid: true,
10148            })
10149        });
10150        self.active_diagnostics.is_some()
10151    }
10152
10153    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10154        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10155            self.display_map.update(cx, |display_map, cx| {
10156                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10157            });
10158            cx.notify();
10159        }
10160    }
10161
10162    pub fn set_selections_from_remote(
10163        &mut self,
10164        selections: Vec<Selection<Anchor>>,
10165        pending_selection: Option<Selection<Anchor>>,
10166        cx: &mut ViewContext<Self>,
10167    ) {
10168        let old_cursor_position = self.selections.newest_anchor().head();
10169        self.selections.change_with(cx, |s| {
10170            s.select_anchors(selections);
10171            if let Some(pending_selection) = pending_selection {
10172                s.set_pending(pending_selection, SelectMode::Character);
10173            } else {
10174                s.clear_pending();
10175            }
10176        });
10177        self.selections_did_change(false, &old_cursor_position, true, cx);
10178    }
10179
10180    fn push_to_selection_history(&mut self) {
10181        self.selection_history.push(SelectionHistoryEntry {
10182            selections: self.selections.disjoint_anchors(),
10183            select_next_state: self.select_next_state.clone(),
10184            select_prev_state: self.select_prev_state.clone(),
10185            add_selections_state: self.add_selections_state.clone(),
10186        });
10187    }
10188
10189    pub fn transact(
10190        &mut self,
10191        cx: &mut ViewContext<Self>,
10192        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10193    ) -> Option<TransactionId> {
10194        self.start_transaction_at(Instant::now(), cx);
10195        update(self, cx);
10196        self.end_transaction_at(Instant::now(), cx)
10197    }
10198
10199    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10200        self.end_selection(cx);
10201        if let Some(tx_id) = self
10202            .buffer
10203            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10204        {
10205            self.selection_history
10206                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10207            cx.emit(EditorEvent::TransactionBegun {
10208                transaction_id: tx_id,
10209            })
10210        }
10211    }
10212
10213    fn end_transaction_at(
10214        &mut self,
10215        now: Instant,
10216        cx: &mut ViewContext<Self>,
10217    ) -> Option<TransactionId> {
10218        if let Some(transaction_id) = self
10219            .buffer
10220            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10221        {
10222            if let Some((_, end_selections)) =
10223                self.selection_history.transaction_mut(transaction_id)
10224            {
10225                *end_selections = Some(self.selections.disjoint_anchors());
10226            } else {
10227                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10228            }
10229
10230            cx.emit(EditorEvent::Edited { transaction_id });
10231            Some(transaction_id)
10232        } else {
10233            None
10234        }
10235    }
10236
10237    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10238        let selection = self.selections.newest::<Point>(cx);
10239
10240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10241        let range = if selection.is_empty() {
10242            let point = selection.head().to_display_point(&display_map);
10243            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10244            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10245                .to_point(&display_map);
10246            start..end
10247        } else {
10248            selection.range()
10249        };
10250        if display_map.folds_in_range(range).next().is_some() {
10251            self.unfold_lines(&Default::default(), cx)
10252        } else {
10253            self.fold(&Default::default(), cx)
10254        }
10255    }
10256
10257    pub fn toggle_fold_recursive(
10258        &mut self,
10259        _: &actions::ToggleFoldRecursive,
10260        cx: &mut ViewContext<Self>,
10261    ) {
10262        let selection = self.selections.newest::<Point>(cx);
10263
10264        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10265        let range = if selection.is_empty() {
10266            let point = selection.head().to_display_point(&display_map);
10267            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10268            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10269                .to_point(&display_map);
10270            start..end
10271        } else {
10272            selection.range()
10273        };
10274        if display_map.folds_in_range(range).next().is_some() {
10275            self.unfold_recursive(&Default::default(), cx)
10276        } else {
10277            self.fold_recursive(&Default::default(), cx)
10278        }
10279    }
10280
10281    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10282        let mut to_fold = Vec::new();
10283        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10284        let selections = self.selections.all_adjusted(cx);
10285
10286        for selection in selections {
10287            let range = selection.range().sorted();
10288            let buffer_start_row = range.start.row;
10289
10290            if range.start.row != range.end.row {
10291                let mut found = false;
10292                let mut row = range.start.row;
10293                while row <= range.end.row {
10294                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10295                        found = true;
10296                        row = crease.range().end.row + 1;
10297                        to_fold.push(crease);
10298                    } else {
10299                        row += 1
10300                    }
10301                }
10302                if found {
10303                    continue;
10304                }
10305            }
10306
10307            for row in (0..=range.start.row).rev() {
10308                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10309                    if crease.range().end.row >= buffer_start_row {
10310                        to_fold.push(crease);
10311                        if row <= range.start.row {
10312                            break;
10313                        }
10314                    }
10315                }
10316            }
10317        }
10318
10319        self.fold_creases(to_fold, true, cx);
10320    }
10321
10322    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10323        if !self.buffer.read(cx).is_singleton() {
10324            return;
10325        }
10326
10327        let fold_at_level = fold_at.level;
10328        let snapshot = self.buffer.read(cx).snapshot(cx);
10329        let mut to_fold = Vec::new();
10330        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10331
10332        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10333            while start_row < end_row {
10334                match self
10335                    .snapshot(cx)
10336                    .crease_for_buffer_row(MultiBufferRow(start_row))
10337                {
10338                    Some(crease) => {
10339                        let nested_start_row = crease.range().start.row + 1;
10340                        let nested_end_row = crease.range().end.row;
10341
10342                        if current_level < fold_at_level {
10343                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10344                        } else if current_level == fold_at_level {
10345                            to_fold.push(crease);
10346                        }
10347
10348                        start_row = nested_end_row + 1;
10349                    }
10350                    None => start_row += 1,
10351                }
10352            }
10353        }
10354
10355        self.fold_creases(to_fold, true, cx);
10356    }
10357
10358    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10359        if !self.buffer.read(cx).is_singleton() {
10360            return;
10361        }
10362
10363        let mut fold_ranges = Vec::new();
10364        let snapshot = self.buffer.read(cx).snapshot(cx);
10365
10366        for row in 0..snapshot.max_row().0 {
10367            if let Some(foldable_range) =
10368                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10369            {
10370                fold_ranges.push(foldable_range);
10371            }
10372        }
10373
10374        self.fold_creases(fold_ranges, true, cx);
10375    }
10376
10377    pub fn fold_function_bodies(
10378        &mut self,
10379        _: &actions::FoldFunctionBodies,
10380        cx: &mut ViewContext<Self>,
10381    ) {
10382        let snapshot = self.buffer.read(cx).snapshot(cx);
10383        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10384            return;
10385        };
10386        let creases = buffer
10387            .function_body_fold_ranges(0..buffer.len())
10388            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10389            .collect();
10390
10391        self.fold_creases(creases, true, cx);
10392    }
10393
10394    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10395        let mut to_fold = Vec::new();
10396        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10397        let selections = self.selections.all_adjusted(cx);
10398
10399        for selection in selections {
10400            let range = selection.range().sorted();
10401            let buffer_start_row = range.start.row;
10402
10403            if range.start.row != range.end.row {
10404                let mut found = false;
10405                for row in range.start.row..=range.end.row {
10406                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10407                        found = true;
10408                        to_fold.push(crease);
10409                    }
10410                }
10411                if found {
10412                    continue;
10413                }
10414            }
10415
10416            for row in (0..=range.start.row).rev() {
10417                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10418                    if crease.range().end.row >= buffer_start_row {
10419                        to_fold.push(crease);
10420                    } else {
10421                        break;
10422                    }
10423                }
10424            }
10425        }
10426
10427        self.fold_creases(to_fold, true, cx);
10428    }
10429
10430    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10431        let buffer_row = fold_at.buffer_row;
10432        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10433
10434        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10435            let autoscroll = self
10436                .selections
10437                .all::<Point>(cx)
10438                .iter()
10439                .any(|selection| crease.range().overlaps(&selection.range()));
10440
10441            self.fold_creases(vec![crease], autoscroll, cx);
10442        }
10443    }
10444
10445    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10446        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10447        let buffer = &display_map.buffer_snapshot;
10448        let selections = self.selections.all::<Point>(cx);
10449        let ranges = selections
10450            .iter()
10451            .map(|s| {
10452                let range = s.display_range(&display_map).sorted();
10453                let mut start = range.start.to_point(&display_map);
10454                let mut end = range.end.to_point(&display_map);
10455                start.column = 0;
10456                end.column = buffer.line_len(MultiBufferRow(end.row));
10457                start..end
10458            })
10459            .collect::<Vec<_>>();
10460
10461        self.unfold_ranges(&ranges, true, true, cx);
10462    }
10463
10464    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10465        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10466        let selections = self.selections.all::<Point>(cx);
10467        let ranges = selections
10468            .iter()
10469            .map(|s| {
10470                let mut range = s.display_range(&display_map).sorted();
10471                *range.start.column_mut() = 0;
10472                *range.end.column_mut() = display_map.line_len(range.end.row());
10473                let start = range.start.to_point(&display_map);
10474                let end = range.end.to_point(&display_map);
10475                start..end
10476            })
10477            .collect::<Vec<_>>();
10478
10479        self.unfold_ranges(&ranges, true, true, cx);
10480    }
10481
10482    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10483        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10484
10485        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10486            ..Point::new(
10487                unfold_at.buffer_row.0,
10488                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10489            );
10490
10491        let autoscroll = self
10492            .selections
10493            .all::<Point>(cx)
10494            .iter()
10495            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10496
10497        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10498    }
10499
10500    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10501        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10502        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10503    }
10504
10505    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10506        let selections = self.selections.all::<Point>(cx);
10507        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10508        let line_mode = self.selections.line_mode;
10509        let ranges = selections
10510            .into_iter()
10511            .map(|s| {
10512                if line_mode {
10513                    let start = Point::new(s.start.row, 0);
10514                    let end = Point::new(
10515                        s.end.row,
10516                        display_map
10517                            .buffer_snapshot
10518                            .line_len(MultiBufferRow(s.end.row)),
10519                    );
10520                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10521                } else {
10522                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10523                }
10524            })
10525            .collect::<Vec<_>>();
10526        self.fold_creases(ranges, true, cx);
10527    }
10528
10529    pub fn fold_creases<T: ToOffset + Clone>(
10530        &mut self,
10531        creases: Vec<Crease<T>>,
10532        auto_scroll: bool,
10533        cx: &mut ViewContext<Self>,
10534    ) {
10535        if creases.is_empty() {
10536            return;
10537        }
10538
10539        let mut buffers_affected = HashSet::default();
10540        let multi_buffer = self.buffer().read(cx);
10541        for crease in &creases {
10542            if let Some((_, buffer, _)) =
10543                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10544            {
10545                buffers_affected.insert(buffer.read(cx).remote_id());
10546            };
10547        }
10548
10549        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10550
10551        if auto_scroll {
10552            self.request_autoscroll(Autoscroll::fit(), cx);
10553        }
10554
10555        for buffer_id in buffers_affected {
10556            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10557        }
10558
10559        cx.notify();
10560
10561        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10562            // Clear diagnostics block when folding a range that contains it.
10563            let snapshot = self.snapshot(cx);
10564            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10565                drop(snapshot);
10566                self.active_diagnostics = Some(active_diagnostics);
10567                self.dismiss_diagnostics(cx);
10568            } else {
10569                self.active_diagnostics = Some(active_diagnostics);
10570            }
10571        }
10572
10573        self.scrollbar_marker_state.dirty = true;
10574    }
10575
10576    /// Removes any folds whose ranges intersect any of the given ranges.
10577    pub fn unfold_ranges<T: ToOffset + Clone>(
10578        &mut self,
10579        ranges: &[Range<T>],
10580        inclusive: bool,
10581        auto_scroll: bool,
10582        cx: &mut ViewContext<Self>,
10583    ) {
10584        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10585            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10586        });
10587    }
10588
10589    /// Removes any folds with the given ranges.
10590    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10591        &mut self,
10592        ranges: &[Range<T>],
10593        type_id: TypeId,
10594        auto_scroll: bool,
10595        cx: &mut ViewContext<Self>,
10596    ) {
10597        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10598            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10599        });
10600    }
10601
10602    fn remove_folds_with<T: ToOffset + Clone>(
10603        &mut self,
10604        ranges: &[Range<T>],
10605        auto_scroll: bool,
10606        cx: &mut ViewContext<Self>,
10607        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10608    ) {
10609        if ranges.is_empty() {
10610            return;
10611        }
10612
10613        let mut buffers_affected = HashSet::default();
10614        let multi_buffer = self.buffer().read(cx);
10615        for range in ranges {
10616            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10617                buffers_affected.insert(buffer.read(cx).remote_id());
10618            };
10619        }
10620
10621        self.display_map.update(cx, update);
10622
10623        if auto_scroll {
10624            self.request_autoscroll(Autoscroll::fit(), cx);
10625        }
10626
10627        for buffer_id in buffers_affected {
10628            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10629        }
10630
10631        cx.notify();
10632        self.scrollbar_marker_state.dirty = true;
10633        self.active_indent_guides_state.dirty = true;
10634    }
10635
10636    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10637        self.display_map.read(cx).fold_placeholder.clone()
10638    }
10639
10640    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10641        if hovered != self.gutter_hovered {
10642            self.gutter_hovered = hovered;
10643            cx.notify();
10644        }
10645    }
10646
10647    pub fn insert_blocks(
10648        &mut self,
10649        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10650        autoscroll: Option<Autoscroll>,
10651        cx: &mut ViewContext<Self>,
10652    ) -> Vec<CustomBlockId> {
10653        let blocks = self
10654            .display_map
10655            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10656        if let Some(autoscroll) = autoscroll {
10657            self.request_autoscroll(autoscroll, cx);
10658        }
10659        cx.notify();
10660        blocks
10661    }
10662
10663    pub fn resize_blocks(
10664        &mut self,
10665        heights: HashMap<CustomBlockId, u32>,
10666        autoscroll: Option<Autoscroll>,
10667        cx: &mut ViewContext<Self>,
10668    ) {
10669        self.display_map
10670            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10671        if let Some(autoscroll) = autoscroll {
10672            self.request_autoscroll(autoscroll, cx);
10673        }
10674        cx.notify();
10675    }
10676
10677    pub fn replace_blocks(
10678        &mut self,
10679        renderers: HashMap<CustomBlockId, RenderBlock>,
10680        autoscroll: Option<Autoscroll>,
10681        cx: &mut ViewContext<Self>,
10682    ) {
10683        self.display_map
10684            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10685        if let Some(autoscroll) = autoscroll {
10686            self.request_autoscroll(autoscroll, cx);
10687        }
10688        cx.notify();
10689    }
10690
10691    pub fn remove_blocks(
10692        &mut self,
10693        block_ids: HashSet<CustomBlockId>,
10694        autoscroll: Option<Autoscroll>,
10695        cx: &mut ViewContext<Self>,
10696    ) {
10697        self.display_map.update(cx, |display_map, cx| {
10698            display_map.remove_blocks(block_ids, cx)
10699        });
10700        if let Some(autoscroll) = autoscroll {
10701            self.request_autoscroll(autoscroll, cx);
10702        }
10703        cx.notify();
10704    }
10705
10706    pub fn row_for_block(
10707        &self,
10708        block_id: CustomBlockId,
10709        cx: &mut ViewContext<Self>,
10710    ) -> Option<DisplayRow> {
10711        self.display_map
10712            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10713    }
10714
10715    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10716        self.focused_block = Some(focused_block);
10717    }
10718
10719    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10720        self.focused_block.take()
10721    }
10722
10723    pub fn insert_creases(
10724        &mut self,
10725        creases: impl IntoIterator<Item = Crease<Anchor>>,
10726        cx: &mut ViewContext<Self>,
10727    ) -> Vec<CreaseId> {
10728        self.display_map
10729            .update(cx, |map, cx| map.insert_creases(creases, cx))
10730    }
10731
10732    pub fn remove_creases(
10733        &mut self,
10734        ids: impl IntoIterator<Item = CreaseId>,
10735        cx: &mut ViewContext<Self>,
10736    ) {
10737        self.display_map
10738            .update(cx, |map, cx| map.remove_creases(ids, cx));
10739    }
10740
10741    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10742        self.display_map
10743            .update(cx, |map, cx| map.snapshot(cx))
10744            .longest_row()
10745    }
10746
10747    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10748        self.display_map
10749            .update(cx, |map, cx| map.snapshot(cx))
10750            .max_point()
10751    }
10752
10753    pub fn text(&self, cx: &AppContext) -> String {
10754        self.buffer.read(cx).read(cx).text()
10755    }
10756
10757    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10758        let text = self.text(cx);
10759        let text = text.trim();
10760
10761        if text.is_empty() {
10762            return None;
10763        }
10764
10765        Some(text.to_string())
10766    }
10767
10768    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10769        self.transact(cx, |this, cx| {
10770            this.buffer
10771                .read(cx)
10772                .as_singleton()
10773                .expect("you can only call set_text on editors for singleton buffers")
10774                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10775        });
10776    }
10777
10778    pub fn display_text(&self, cx: &mut AppContext) -> String {
10779        self.display_map
10780            .update(cx, |map, cx| map.snapshot(cx))
10781            .text()
10782    }
10783
10784    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10785        let mut wrap_guides = smallvec::smallvec![];
10786
10787        if self.show_wrap_guides == Some(false) {
10788            return wrap_guides;
10789        }
10790
10791        let settings = self.buffer.read(cx).settings_at(0, cx);
10792        if settings.show_wrap_guides {
10793            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10794                wrap_guides.push((soft_wrap as usize, true));
10795            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10796                wrap_guides.push((soft_wrap as usize, true));
10797            }
10798            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10799        }
10800
10801        wrap_guides
10802    }
10803
10804    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10805        let settings = self.buffer.read(cx).settings_at(0, cx);
10806        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10807        match mode {
10808            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
10809                SoftWrap::None
10810            }
10811            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10812            language_settings::SoftWrap::PreferredLineLength => {
10813                SoftWrap::Column(settings.preferred_line_length)
10814            }
10815            language_settings::SoftWrap::Bounded => {
10816                SoftWrap::Bounded(settings.preferred_line_length)
10817            }
10818        }
10819    }
10820
10821    pub fn set_soft_wrap_mode(
10822        &mut self,
10823        mode: language_settings::SoftWrap,
10824        cx: &mut ViewContext<Self>,
10825    ) {
10826        self.soft_wrap_mode_override = Some(mode);
10827        cx.notify();
10828    }
10829
10830    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
10831        self.text_style_refinement = Some(style);
10832    }
10833
10834    /// called by the Element so we know what style we were most recently rendered with.
10835    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10836        let rem_size = cx.rem_size();
10837        self.display_map.update(cx, |map, cx| {
10838            map.set_font(
10839                style.text.font(),
10840                style.text.font_size.to_pixels(rem_size),
10841                cx,
10842            )
10843        });
10844        self.style = Some(style);
10845    }
10846
10847    pub fn style(&self) -> Option<&EditorStyle> {
10848        self.style.as_ref()
10849    }
10850
10851    // Called by the element. This method is not designed to be called outside of the editor
10852    // element's layout code because it does not notify when rewrapping is computed synchronously.
10853    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10854        self.display_map
10855            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10856    }
10857
10858    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10859        if self.soft_wrap_mode_override.is_some() {
10860            self.soft_wrap_mode_override.take();
10861        } else {
10862            let soft_wrap = match self.soft_wrap_mode(cx) {
10863                SoftWrap::GitDiff => return,
10864                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
10865                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10866                    language_settings::SoftWrap::None
10867                }
10868            };
10869            self.soft_wrap_mode_override = Some(soft_wrap);
10870        }
10871        cx.notify();
10872    }
10873
10874    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10875        let Some(workspace) = self.workspace() else {
10876            return;
10877        };
10878        let fs = workspace.read(cx).app_state().fs.clone();
10879        let current_show = TabBarSettings::get_global(cx).show;
10880        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10881            setting.show = Some(!current_show);
10882        });
10883    }
10884
10885    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10886        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10887            self.buffer
10888                .read(cx)
10889                .settings_at(0, cx)
10890                .indent_guides
10891                .enabled
10892        });
10893        self.show_indent_guides = Some(!currently_enabled);
10894        cx.notify();
10895    }
10896
10897    fn should_show_indent_guides(&self) -> Option<bool> {
10898        self.show_indent_guides
10899    }
10900
10901    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10902        let mut editor_settings = EditorSettings::get_global(cx).clone();
10903        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10904        EditorSettings::override_global(editor_settings, cx);
10905    }
10906
10907    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10908        self.use_relative_line_numbers
10909            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10910    }
10911
10912    pub fn toggle_relative_line_numbers(
10913        &mut self,
10914        _: &ToggleRelativeLineNumbers,
10915        cx: &mut ViewContext<Self>,
10916    ) {
10917        let is_relative = self.should_use_relative_line_numbers(cx);
10918        self.set_relative_line_number(Some(!is_relative), cx)
10919    }
10920
10921    pub fn set_relative_line_number(
10922        &mut self,
10923        is_relative: Option<bool>,
10924        cx: &mut ViewContext<Self>,
10925    ) {
10926        self.use_relative_line_numbers = is_relative;
10927        cx.notify();
10928    }
10929
10930    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10931        self.show_gutter = show_gutter;
10932        cx.notify();
10933    }
10934
10935    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10936        self.show_line_numbers = Some(show_line_numbers);
10937        cx.notify();
10938    }
10939
10940    pub fn set_show_git_diff_gutter(
10941        &mut self,
10942        show_git_diff_gutter: bool,
10943        cx: &mut ViewContext<Self>,
10944    ) {
10945        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10946        cx.notify();
10947    }
10948
10949    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10950        self.show_code_actions = Some(show_code_actions);
10951        cx.notify();
10952    }
10953
10954    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10955        self.show_runnables = Some(show_runnables);
10956        cx.notify();
10957    }
10958
10959    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10960        if self.display_map.read(cx).masked != masked {
10961            self.display_map.update(cx, |map, _| map.masked = masked);
10962        }
10963        cx.notify()
10964    }
10965
10966    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10967        self.show_wrap_guides = Some(show_wrap_guides);
10968        cx.notify();
10969    }
10970
10971    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10972        self.show_indent_guides = Some(show_indent_guides);
10973        cx.notify();
10974    }
10975
10976    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10977        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10978            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10979                if let Some(dir) = file.abs_path(cx).parent() {
10980                    return Some(dir.to_owned());
10981                }
10982            }
10983
10984            if let Some(project_path) = buffer.read(cx).project_path(cx) {
10985                return Some(project_path.path.to_path_buf());
10986            }
10987        }
10988
10989        None
10990    }
10991
10992    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
10993        self.active_excerpt(cx)?
10994            .1
10995            .read(cx)
10996            .file()
10997            .and_then(|f| f.as_local())
10998    }
10999
11000    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11001        if let Some(target) = self.target_file(cx) {
11002            cx.reveal_path(&target.abs_path(cx));
11003        }
11004    }
11005
11006    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11007        if let Some(file) = self.target_file(cx) {
11008            if let Some(path) = file.abs_path(cx).to_str() {
11009                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11010            }
11011        }
11012    }
11013
11014    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11015        if let Some(file) = self.target_file(cx) {
11016            if let Some(path) = file.path().to_str() {
11017                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11018            }
11019        }
11020    }
11021
11022    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11023        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11024
11025        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11026            self.start_git_blame(true, cx);
11027        }
11028
11029        cx.notify();
11030    }
11031
11032    pub fn toggle_git_blame_inline(
11033        &mut self,
11034        _: &ToggleGitBlameInline,
11035        cx: &mut ViewContext<Self>,
11036    ) {
11037        self.toggle_git_blame_inline_internal(true, cx);
11038        cx.notify();
11039    }
11040
11041    pub fn git_blame_inline_enabled(&self) -> bool {
11042        self.git_blame_inline_enabled
11043    }
11044
11045    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11046        self.show_selection_menu = self
11047            .show_selection_menu
11048            .map(|show_selections_menu| !show_selections_menu)
11049            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11050
11051        cx.notify();
11052    }
11053
11054    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11055        self.show_selection_menu
11056            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11057    }
11058
11059    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11060        if let Some(project) = self.project.as_ref() {
11061            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11062                return;
11063            };
11064
11065            if buffer.read(cx).file().is_none() {
11066                return;
11067            }
11068
11069            let focused = self.focus_handle(cx).contains_focused(cx);
11070
11071            let project = project.clone();
11072            let blame =
11073                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11074            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11075            self.blame = Some(blame);
11076        }
11077    }
11078
11079    fn toggle_git_blame_inline_internal(
11080        &mut self,
11081        user_triggered: bool,
11082        cx: &mut ViewContext<Self>,
11083    ) {
11084        if self.git_blame_inline_enabled {
11085            self.git_blame_inline_enabled = false;
11086            self.show_git_blame_inline = false;
11087            self.show_git_blame_inline_delay_task.take();
11088        } else {
11089            self.git_blame_inline_enabled = true;
11090            self.start_git_blame_inline(user_triggered, cx);
11091        }
11092
11093        cx.notify();
11094    }
11095
11096    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11097        self.start_git_blame(user_triggered, cx);
11098
11099        if ProjectSettings::get_global(cx)
11100            .git
11101            .inline_blame_delay()
11102            .is_some()
11103        {
11104            self.start_inline_blame_timer(cx);
11105        } else {
11106            self.show_git_blame_inline = true
11107        }
11108    }
11109
11110    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11111        self.blame.as_ref()
11112    }
11113
11114    pub fn show_git_blame_gutter(&self) -> bool {
11115        self.show_git_blame_gutter
11116    }
11117
11118    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11119        self.show_git_blame_gutter && self.has_blame_entries(cx)
11120    }
11121
11122    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11123        self.show_git_blame_inline
11124            && self.focus_handle.is_focused(cx)
11125            && !self.newest_selection_head_on_empty_line(cx)
11126            && self.has_blame_entries(cx)
11127    }
11128
11129    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11130        self.blame()
11131            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11132    }
11133
11134    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11135        let cursor_anchor = self.selections.newest_anchor().head();
11136
11137        let snapshot = self.buffer.read(cx).snapshot(cx);
11138        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11139
11140        snapshot.line_len(buffer_row) == 0
11141    }
11142
11143    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11144        let buffer_and_selection = maybe!({
11145            let selection = self.selections.newest::<Point>(cx);
11146            let selection_range = selection.range();
11147
11148            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11149                (buffer, selection_range.start.row..selection_range.end.row)
11150            } else {
11151                let buffer_ranges = self
11152                    .buffer()
11153                    .read(cx)
11154                    .range_to_buffer_ranges(selection_range, cx);
11155
11156                let (buffer, range, _) = if selection.reversed {
11157                    buffer_ranges.first()
11158                } else {
11159                    buffer_ranges.last()
11160                }?;
11161
11162                let snapshot = buffer.read(cx).snapshot();
11163                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11164                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11165                (buffer.clone(), selection)
11166            };
11167
11168            Some((buffer, selection))
11169        });
11170
11171        let Some((buffer, selection)) = buffer_and_selection else {
11172            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11173        };
11174
11175        let Some(project) = self.project.as_ref() else {
11176            return Task::ready(Err(anyhow!("editor does not have project")));
11177        };
11178
11179        project.update(cx, |project, cx| {
11180            project.get_permalink_to_line(&buffer, selection, cx)
11181        })
11182    }
11183
11184    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11185        let permalink_task = self.get_permalink_to_line(cx);
11186        let workspace = self.workspace();
11187
11188        cx.spawn(|_, mut cx| async move {
11189            match permalink_task.await {
11190                Ok(permalink) => {
11191                    cx.update(|cx| {
11192                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11193                    })
11194                    .ok();
11195                }
11196                Err(err) => {
11197                    let message = format!("Failed to copy permalink: {err}");
11198
11199                    Err::<(), anyhow::Error>(err).log_err();
11200
11201                    if let Some(workspace) = workspace {
11202                        workspace
11203                            .update(&mut cx, |workspace, cx| {
11204                                struct CopyPermalinkToLine;
11205
11206                                workspace.show_toast(
11207                                    Toast::new(
11208                                        NotificationId::unique::<CopyPermalinkToLine>(),
11209                                        message,
11210                                    ),
11211                                    cx,
11212                                )
11213                            })
11214                            .ok();
11215                    }
11216                }
11217            }
11218        })
11219        .detach();
11220    }
11221
11222    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11223        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11224        if let Some(file) = self.target_file(cx) {
11225            if let Some(path) = file.path().to_str() {
11226                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11227            }
11228        }
11229    }
11230
11231    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11232        let permalink_task = self.get_permalink_to_line(cx);
11233        let workspace = self.workspace();
11234
11235        cx.spawn(|_, mut cx| async move {
11236            match permalink_task.await {
11237                Ok(permalink) => {
11238                    cx.update(|cx| {
11239                        cx.open_url(permalink.as_ref());
11240                    })
11241                    .ok();
11242                }
11243                Err(err) => {
11244                    let message = format!("Failed to open permalink: {err}");
11245
11246                    Err::<(), anyhow::Error>(err).log_err();
11247
11248                    if let Some(workspace) = workspace {
11249                        workspace
11250                            .update(&mut cx, |workspace, cx| {
11251                                struct OpenPermalinkToLine;
11252
11253                                workspace.show_toast(
11254                                    Toast::new(
11255                                        NotificationId::unique::<OpenPermalinkToLine>(),
11256                                        message,
11257                                    ),
11258                                    cx,
11259                                )
11260                            })
11261                            .ok();
11262                    }
11263                }
11264            }
11265        })
11266        .detach();
11267    }
11268
11269    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11270        self.insert_uuid(UuidVersion::V4, cx);
11271    }
11272
11273    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11274        self.insert_uuid(UuidVersion::V7, cx);
11275    }
11276
11277    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11278        self.transact(cx, |this, cx| {
11279            let edits = this
11280                .selections
11281                .all::<Point>(cx)
11282                .into_iter()
11283                .map(|selection| {
11284                    let uuid = match version {
11285                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11286                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11287                    };
11288
11289                    (selection.range(), uuid.to_string())
11290                });
11291            this.edit(edits, cx);
11292            this.refresh_inline_completion(true, false, cx);
11293        });
11294    }
11295
11296    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11297    /// last highlight added will be used.
11298    ///
11299    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11300    pub fn highlight_rows<T: 'static>(
11301        &mut self,
11302        range: Range<Anchor>,
11303        color: Hsla,
11304        should_autoscroll: bool,
11305        cx: &mut ViewContext<Self>,
11306    ) {
11307        let snapshot = self.buffer().read(cx).snapshot(cx);
11308        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11309        let ix = row_highlights.binary_search_by(|highlight| {
11310            Ordering::Equal
11311                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11312                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11313        });
11314
11315        if let Err(mut ix) = ix {
11316            let index = post_inc(&mut self.highlight_order);
11317
11318            // If this range intersects with the preceding highlight, then merge it with
11319            // the preceding highlight. Otherwise insert a new highlight.
11320            let mut merged = false;
11321            if ix > 0 {
11322                let prev_highlight = &mut row_highlights[ix - 1];
11323                if prev_highlight
11324                    .range
11325                    .end
11326                    .cmp(&range.start, &snapshot)
11327                    .is_ge()
11328                {
11329                    ix -= 1;
11330                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11331                        prev_highlight.range.end = range.end;
11332                    }
11333                    merged = true;
11334                    prev_highlight.index = index;
11335                    prev_highlight.color = color;
11336                    prev_highlight.should_autoscroll = should_autoscroll;
11337                }
11338            }
11339
11340            if !merged {
11341                row_highlights.insert(
11342                    ix,
11343                    RowHighlight {
11344                        range: range.clone(),
11345                        index,
11346                        color,
11347                        should_autoscroll,
11348                    },
11349                );
11350            }
11351
11352            // If any of the following highlights intersect with this one, merge them.
11353            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11354                let highlight = &row_highlights[ix];
11355                if next_highlight
11356                    .range
11357                    .start
11358                    .cmp(&highlight.range.end, &snapshot)
11359                    .is_le()
11360                {
11361                    if next_highlight
11362                        .range
11363                        .end
11364                        .cmp(&highlight.range.end, &snapshot)
11365                        .is_gt()
11366                    {
11367                        row_highlights[ix].range.end = next_highlight.range.end;
11368                    }
11369                    row_highlights.remove(ix + 1);
11370                } else {
11371                    break;
11372                }
11373            }
11374        }
11375    }
11376
11377    /// Remove any highlighted row ranges of the given type that intersect the
11378    /// given ranges.
11379    pub fn remove_highlighted_rows<T: 'static>(
11380        &mut self,
11381        ranges_to_remove: Vec<Range<Anchor>>,
11382        cx: &mut ViewContext<Self>,
11383    ) {
11384        let snapshot = self.buffer().read(cx).snapshot(cx);
11385        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11386        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11387        row_highlights.retain(|highlight| {
11388            while let Some(range_to_remove) = ranges_to_remove.peek() {
11389                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11390                    Ordering::Less | Ordering::Equal => {
11391                        ranges_to_remove.next();
11392                    }
11393                    Ordering::Greater => {
11394                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11395                            Ordering::Less | Ordering::Equal => {
11396                                return false;
11397                            }
11398                            Ordering::Greater => break,
11399                        }
11400                    }
11401                }
11402            }
11403
11404            true
11405        })
11406    }
11407
11408    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11409    pub fn clear_row_highlights<T: 'static>(&mut self) {
11410        self.highlighted_rows.remove(&TypeId::of::<T>());
11411    }
11412
11413    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11414    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11415        self.highlighted_rows
11416            .get(&TypeId::of::<T>())
11417            .map_or(&[] as &[_], |vec| vec.as_slice())
11418            .iter()
11419            .map(|highlight| (highlight.range.clone(), highlight.color))
11420    }
11421
11422    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11423    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11424    /// Allows to ignore certain kinds of highlights.
11425    pub fn highlighted_display_rows(
11426        &mut self,
11427        cx: &mut WindowContext,
11428    ) -> BTreeMap<DisplayRow, Hsla> {
11429        let snapshot = self.snapshot(cx);
11430        let mut used_highlight_orders = HashMap::default();
11431        self.highlighted_rows
11432            .iter()
11433            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11434            .fold(
11435                BTreeMap::<DisplayRow, Hsla>::new(),
11436                |mut unique_rows, highlight| {
11437                    let start = highlight.range.start.to_display_point(&snapshot);
11438                    let end = highlight.range.end.to_display_point(&snapshot);
11439                    let start_row = start.row().0;
11440                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11441                        && end.column() == 0
11442                    {
11443                        end.row().0.saturating_sub(1)
11444                    } else {
11445                        end.row().0
11446                    };
11447                    for row in start_row..=end_row {
11448                        let used_index =
11449                            used_highlight_orders.entry(row).or_insert(highlight.index);
11450                        if highlight.index >= *used_index {
11451                            *used_index = highlight.index;
11452                            unique_rows.insert(DisplayRow(row), highlight.color);
11453                        }
11454                    }
11455                    unique_rows
11456                },
11457            )
11458    }
11459
11460    pub fn highlighted_display_row_for_autoscroll(
11461        &self,
11462        snapshot: &DisplaySnapshot,
11463    ) -> Option<DisplayRow> {
11464        self.highlighted_rows
11465            .values()
11466            .flat_map(|highlighted_rows| highlighted_rows.iter())
11467            .filter_map(|highlight| {
11468                if highlight.should_autoscroll {
11469                    Some(highlight.range.start.to_display_point(snapshot).row())
11470                } else {
11471                    None
11472                }
11473            })
11474            .min()
11475    }
11476
11477    pub fn set_search_within_ranges(
11478        &mut self,
11479        ranges: &[Range<Anchor>],
11480        cx: &mut ViewContext<Self>,
11481    ) {
11482        self.highlight_background::<SearchWithinRange>(
11483            ranges,
11484            |colors| colors.editor_document_highlight_read_background,
11485            cx,
11486        )
11487    }
11488
11489    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11490        self.breadcrumb_header = Some(new_header);
11491    }
11492
11493    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11494        self.clear_background_highlights::<SearchWithinRange>(cx);
11495    }
11496
11497    pub fn highlight_background<T: 'static>(
11498        &mut self,
11499        ranges: &[Range<Anchor>],
11500        color_fetcher: fn(&ThemeColors) -> Hsla,
11501        cx: &mut ViewContext<Self>,
11502    ) {
11503        self.background_highlights
11504            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11505        self.scrollbar_marker_state.dirty = true;
11506        cx.notify();
11507    }
11508
11509    pub fn clear_background_highlights<T: 'static>(
11510        &mut self,
11511        cx: &mut ViewContext<Self>,
11512    ) -> Option<BackgroundHighlight> {
11513        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11514        if !text_highlights.1.is_empty() {
11515            self.scrollbar_marker_state.dirty = true;
11516            cx.notify();
11517        }
11518        Some(text_highlights)
11519    }
11520
11521    pub fn highlight_gutter<T: 'static>(
11522        &mut self,
11523        ranges: &[Range<Anchor>],
11524        color_fetcher: fn(&AppContext) -> Hsla,
11525        cx: &mut ViewContext<Self>,
11526    ) {
11527        self.gutter_highlights
11528            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11529        cx.notify();
11530    }
11531
11532    pub fn clear_gutter_highlights<T: 'static>(
11533        &mut self,
11534        cx: &mut ViewContext<Self>,
11535    ) -> Option<GutterHighlight> {
11536        cx.notify();
11537        self.gutter_highlights.remove(&TypeId::of::<T>())
11538    }
11539
11540    #[cfg(feature = "test-support")]
11541    pub fn all_text_background_highlights(
11542        &mut self,
11543        cx: &mut ViewContext<Self>,
11544    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11545        let snapshot = self.snapshot(cx);
11546        let buffer = &snapshot.buffer_snapshot;
11547        let start = buffer.anchor_before(0);
11548        let end = buffer.anchor_after(buffer.len());
11549        let theme = cx.theme().colors();
11550        self.background_highlights_in_range(start..end, &snapshot, theme)
11551    }
11552
11553    #[cfg(feature = "test-support")]
11554    pub fn search_background_highlights(
11555        &mut self,
11556        cx: &mut ViewContext<Self>,
11557    ) -> Vec<Range<Point>> {
11558        let snapshot = self.buffer().read(cx).snapshot(cx);
11559
11560        let highlights = self
11561            .background_highlights
11562            .get(&TypeId::of::<items::BufferSearchHighlights>());
11563
11564        if let Some((_color, ranges)) = highlights {
11565            ranges
11566                .iter()
11567                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11568                .collect_vec()
11569        } else {
11570            vec![]
11571        }
11572    }
11573
11574    fn document_highlights_for_position<'a>(
11575        &'a self,
11576        position: Anchor,
11577        buffer: &'a MultiBufferSnapshot,
11578    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11579        let read_highlights = self
11580            .background_highlights
11581            .get(&TypeId::of::<DocumentHighlightRead>())
11582            .map(|h| &h.1);
11583        let write_highlights = self
11584            .background_highlights
11585            .get(&TypeId::of::<DocumentHighlightWrite>())
11586            .map(|h| &h.1);
11587        let left_position = position.bias_left(buffer);
11588        let right_position = position.bias_right(buffer);
11589        read_highlights
11590            .into_iter()
11591            .chain(write_highlights)
11592            .flat_map(move |ranges| {
11593                let start_ix = match ranges.binary_search_by(|probe| {
11594                    let cmp = probe.end.cmp(&left_position, buffer);
11595                    if cmp.is_ge() {
11596                        Ordering::Greater
11597                    } else {
11598                        Ordering::Less
11599                    }
11600                }) {
11601                    Ok(i) | Err(i) => i,
11602                };
11603
11604                ranges[start_ix..]
11605                    .iter()
11606                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11607            })
11608    }
11609
11610    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11611        self.background_highlights
11612            .get(&TypeId::of::<T>())
11613            .map_or(false, |(_, highlights)| !highlights.is_empty())
11614    }
11615
11616    pub fn background_highlights_in_range(
11617        &self,
11618        search_range: Range<Anchor>,
11619        display_snapshot: &DisplaySnapshot,
11620        theme: &ThemeColors,
11621    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11622        let mut results = Vec::new();
11623        for (color_fetcher, ranges) in self.background_highlights.values() {
11624            let color = color_fetcher(theme);
11625            let start_ix = match ranges.binary_search_by(|probe| {
11626                let cmp = probe
11627                    .end
11628                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11629                if cmp.is_gt() {
11630                    Ordering::Greater
11631                } else {
11632                    Ordering::Less
11633                }
11634            }) {
11635                Ok(i) | Err(i) => i,
11636            };
11637            for range in &ranges[start_ix..] {
11638                if range
11639                    .start
11640                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11641                    .is_ge()
11642                {
11643                    break;
11644                }
11645
11646                let start = range.start.to_display_point(display_snapshot);
11647                let end = range.end.to_display_point(display_snapshot);
11648                results.push((start..end, color))
11649            }
11650        }
11651        results
11652    }
11653
11654    pub fn background_highlight_row_ranges<T: 'static>(
11655        &self,
11656        search_range: Range<Anchor>,
11657        display_snapshot: &DisplaySnapshot,
11658        count: usize,
11659    ) -> Vec<RangeInclusive<DisplayPoint>> {
11660        let mut results = Vec::new();
11661        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11662            return vec![];
11663        };
11664
11665        let start_ix = match ranges.binary_search_by(|probe| {
11666            let cmp = probe
11667                .end
11668                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11669            if cmp.is_gt() {
11670                Ordering::Greater
11671            } else {
11672                Ordering::Less
11673            }
11674        }) {
11675            Ok(i) | Err(i) => i,
11676        };
11677        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11678            if let (Some(start_display), Some(end_display)) = (start, end) {
11679                results.push(
11680                    start_display.to_display_point(display_snapshot)
11681                        ..=end_display.to_display_point(display_snapshot),
11682                );
11683            }
11684        };
11685        let mut start_row: Option<Point> = None;
11686        let mut end_row: Option<Point> = None;
11687        if ranges.len() > count {
11688            return Vec::new();
11689        }
11690        for range in &ranges[start_ix..] {
11691            if range
11692                .start
11693                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11694                .is_ge()
11695            {
11696                break;
11697            }
11698            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11699            if let Some(current_row) = &end_row {
11700                if end.row == current_row.row {
11701                    continue;
11702                }
11703            }
11704            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11705            if start_row.is_none() {
11706                assert_eq!(end_row, None);
11707                start_row = Some(start);
11708                end_row = Some(end);
11709                continue;
11710            }
11711            if let Some(current_end) = end_row.as_mut() {
11712                if start.row > current_end.row + 1 {
11713                    push_region(start_row, end_row);
11714                    start_row = Some(start);
11715                    end_row = Some(end);
11716                } else {
11717                    // Merge two hunks.
11718                    *current_end = end;
11719                }
11720            } else {
11721                unreachable!();
11722            }
11723        }
11724        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11725        push_region(start_row, end_row);
11726        results
11727    }
11728
11729    pub fn gutter_highlights_in_range(
11730        &self,
11731        search_range: Range<Anchor>,
11732        display_snapshot: &DisplaySnapshot,
11733        cx: &AppContext,
11734    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11735        let mut results = Vec::new();
11736        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11737            let color = color_fetcher(cx);
11738            let start_ix = match ranges.binary_search_by(|probe| {
11739                let cmp = probe
11740                    .end
11741                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11742                if cmp.is_gt() {
11743                    Ordering::Greater
11744                } else {
11745                    Ordering::Less
11746                }
11747            }) {
11748                Ok(i) | Err(i) => i,
11749            };
11750            for range in &ranges[start_ix..] {
11751                if range
11752                    .start
11753                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11754                    .is_ge()
11755                {
11756                    break;
11757                }
11758
11759                let start = range.start.to_display_point(display_snapshot);
11760                let end = range.end.to_display_point(display_snapshot);
11761                results.push((start..end, color))
11762            }
11763        }
11764        results
11765    }
11766
11767    /// Get the text ranges corresponding to the redaction query
11768    pub fn redacted_ranges(
11769        &self,
11770        search_range: Range<Anchor>,
11771        display_snapshot: &DisplaySnapshot,
11772        cx: &WindowContext,
11773    ) -> Vec<Range<DisplayPoint>> {
11774        display_snapshot
11775            .buffer_snapshot
11776            .redacted_ranges(search_range, |file| {
11777                if let Some(file) = file {
11778                    file.is_private()
11779                        && EditorSettings::get(
11780                            Some(SettingsLocation {
11781                                worktree_id: file.worktree_id(cx),
11782                                path: file.path().as_ref(),
11783                            }),
11784                            cx,
11785                        )
11786                        .redact_private_values
11787                } else {
11788                    false
11789                }
11790            })
11791            .map(|range| {
11792                range.start.to_display_point(display_snapshot)
11793                    ..range.end.to_display_point(display_snapshot)
11794            })
11795            .collect()
11796    }
11797
11798    pub fn highlight_text<T: 'static>(
11799        &mut self,
11800        ranges: Vec<Range<Anchor>>,
11801        style: HighlightStyle,
11802        cx: &mut ViewContext<Self>,
11803    ) {
11804        self.display_map.update(cx, |map, _| {
11805            map.highlight_text(TypeId::of::<T>(), ranges, style)
11806        });
11807        cx.notify();
11808    }
11809
11810    pub(crate) fn highlight_inlays<T: 'static>(
11811        &mut self,
11812        highlights: Vec<InlayHighlight>,
11813        style: HighlightStyle,
11814        cx: &mut ViewContext<Self>,
11815    ) {
11816        self.display_map.update(cx, |map, _| {
11817            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11818        });
11819        cx.notify();
11820    }
11821
11822    pub fn text_highlights<'a, T: 'static>(
11823        &'a self,
11824        cx: &'a AppContext,
11825    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11826        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11827    }
11828
11829    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11830        let cleared = self
11831            .display_map
11832            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11833        if cleared {
11834            cx.notify();
11835        }
11836    }
11837
11838    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11839        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11840            && self.focus_handle.is_focused(cx)
11841    }
11842
11843    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11844        self.show_cursor_when_unfocused = is_enabled;
11845        cx.notify();
11846    }
11847
11848    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11849        cx.notify();
11850    }
11851
11852    fn on_buffer_event(
11853        &mut self,
11854        multibuffer: Model<MultiBuffer>,
11855        event: &multi_buffer::Event,
11856        cx: &mut ViewContext<Self>,
11857    ) {
11858        match event {
11859            multi_buffer::Event::Edited {
11860                singleton_buffer_edited,
11861            } => {
11862                self.scrollbar_marker_state.dirty = true;
11863                self.active_indent_guides_state.dirty = true;
11864                self.refresh_active_diagnostics(cx);
11865                self.refresh_code_actions(cx);
11866                if self.has_active_inline_completion() {
11867                    self.update_visible_inline_completion(cx);
11868                }
11869                cx.emit(EditorEvent::BufferEdited);
11870                cx.emit(SearchEvent::MatchesInvalidated);
11871                if *singleton_buffer_edited {
11872                    if let Some(project) = &self.project {
11873                        let project = project.read(cx);
11874                        #[allow(clippy::mutable_key_type)]
11875                        let languages_affected = multibuffer
11876                            .read(cx)
11877                            .all_buffers()
11878                            .into_iter()
11879                            .filter_map(|buffer| {
11880                                let buffer = buffer.read(cx);
11881                                let language = buffer.language()?;
11882                                if project.is_local()
11883                                    && project
11884                                        .language_servers_for_local_buffer(buffer, cx)
11885                                        .count()
11886                                        == 0
11887                                {
11888                                    None
11889                                } else {
11890                                    Some(language)
11891                                }
11892                            })
11893                            .cloned()
11894                            .collect::<HashSet<_>>();
11895                        if !languages_affected.is_empty() {
11896                            self.refresh_inlay_hints(
11897                                InlayHintRefreshReason::BufferEdited(languages_affected),
11898                                cx,
11899                            );
11900                        }
11901                    }
11902                }
11903
11904                let Some(project) = &self.project else { return };
11905                let (telemetry, is_via_ssh) = {
11906                    let project = project.read(cx);
11907                    let telemetry = project.client().telemetry().clone();
11908                    let is_via_ssh = project.is_via_ssh();
11909                    (telemetry, is_via_ssh)
11910                };
11911                refresh_linked_ranges(self, cx);
11912                telemetry.log_edit_event("editor", is_via_ssh);
11913            }
11914            multi_buffer::Event::ExcerptsAdded {
11915                buffer,
11916                predecessor,
11917                excerpts,
11918            } => {
11919                self.tasks_update_task = Some(self.refresh_runnables(cx));
11920                let buffer_id = buffer.read(cx).remote_id();
11921                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
11922                    if let Some(project) = &self.project {
11923                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
11924                    }
11925                }
11926                cx.emit(EditorEvent::ExcerptsAdded {
11927                    buffer: buffer.clone(),
11928                    predecessor: *predecessor,
11929                    excerpts: excerpts.clone(),
11930                });
11931                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11932            }
11933            multi_buffer::Event::ExcerptsRemoved { ids } => {
11934                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11935                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11936            }
11937            multi_buffer::Event::ExcerptsEdited { ids } => {
11938                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11939            }
11940            multi_buffer::Event::ExcerptsExpanded { ids } => {
11941                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11942            }
11943            multi_buffer::Event::Reparsed(buffer_id) => {
11944                self.tasks_update_task = Some(self.refresh_runnables(cx));
11945
11946                cx.emit(EditorEvent::Reparsed(*buffer_id));
11947            }
11948            multi_buffer::Event::LanguageChanged(buffer_id) => {
11949                linked_editing_ranges::refresh_linked_ranges(self, cx);
11950                cx.emit(EditorEvent::Reparsed(*buffer_id));
11951                cx.notify();
11952            }
11953            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11954            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11955            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11956                cx.emit(EditorEvent::TitleChanged)
11957            }
11958            // multi_buffer::Event::DiffBaseChanged => {
11959            //     self.scrollbar_marker_state.dirty = true;
11960            //     cx.emit(EditorEvent::DiffBaseChanged);
11961            //     cx.notify();
11962            // }
11963            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11964            multi_buffer::Event::DiagnosticsUpdated => {
11965                self.refresh_active_diagnostics(cx);
11966                self.scrollbar_marker_state.dirty = true;
11967                cx.notify();
11968            }
11969            _ => {}
11970        };
11971    }
11972
11973    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11974        cx.notify();
11975    }
11976
11977    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11978        self.tasks_update_task = Some(self.refresh_runnables(cx));
11979        self.refresh_inline_completion(true, false, cx);
11980        self.refresh_inlay_hints(
11981            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11982                self.selections.newest_anchor().head(),
11983                &self.buffer.read(cx).snapshot(cx),
11984                cx,
11985            )),
11986            cx,
11987        );
11988
11989        let old_cursor_shape = self.cursor_shape;
11990
11991        {
11992            let editor_settings = EditorSettings::get_global(cx);
11993            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11994            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11995            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
11996        }
11997
11998        if old_cursor_shape != self.cursor_shape {
11999            cx.emit(EditorEvent::CursorShapeChanged);
12000        }
12001
12002        let project_settings = ProjectSettings::get_global(cx);
12003        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12004
12005        if self.mode == EditorMode::Full {
12006            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12007            if self.git_blame_inline_enabled != inline_blame_enabled {
12008                self.toggle_git_blame_inline_internal(false, cx);
12009            }
12010        }
12011
12012        cx.notify();
12013    }
12014
12015    pub fn set_searchable(&mut self, searchable: bool) {
12016        self.searchable = searchable;
12017    }
12018
12019    pub fn searchable(&self) -> bool {
12020        self.searchable
12021    }
12022
12023    fn open_proposed_changes_editor(
12024        &mut self,
12025        _: &OpenProposedChangesEditor,
12026        cx: &mut ViewContext<Self>,
12027    ) {
12028        let Some(workspace) = self.workspace() else {
12029            cx.propagate();
12030            return;
12031        };
12032
12033        let selections = self.selections.all::<usize>(cx);
12034        let buffer = self.buffer.read(cx);
12035        let mut new_selections_by_buffer = HashMap::default();
12036        for selection in selections {
12037            for (buffer, range, _) in
12038                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12039            {
12040                let mut range = range.to_point(buffer.read(cx));
12041                range.start.column = 0;
12042                range.end.column = buffer.read(cx).line_len(range.end.row);
12043                new_selections_by_buffer
12044                    .entry(buffer)
12045                    .or_insert(Vec::new())
12046                    .push(range)
12047            }
12048        }
12049
12050        let proposed_changes_buffers = new_selections_by_buffer
12051            .into_iter()
12052            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12053            .collect::<Vec<_>>();
12054        let proposed_changes_editor = cx.new_view(|cx| {
12055            ProposedChangesEditor::new(
12056                "Proposed changes",
12057                proposed_changes_buffers,
12058                self.project.clone(),
12059                cx,
12060            )
12061        });
12062
12063        cx.window_context().defer(move |cx| {
12064            workspace.update(cx, |workspace, cx| {
12065                workspace.active_pane().update(cx, |pane, cx| {
12066                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12067                });
12068            });
12069        });
12070    }
12071
12072    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12073        self.open_excerpts_common(None, true, cx)
12074    }
12075
12076    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12077        self.open_excerpts_common(None, false, cx)
12078    }
12079
12080    fn open_excerpts_common(
12081        &mut self,
12082        jump_data: Option<JumpData>,
12083        split: bool,
12084        cx: &mut ViewContext<Self>,
12085    ) {
12086        let Some(workspace) = self.workspace() else {
12087            cx.propagate();
12088            return;
12089        };
12090
12091        if self.buffer.read(cx).is_singleton() {
12092            cx.propagate();
12093            return;
12094        }
12095
12096        let mut new_selections_by_buffer = HashMap::default();
12097        match &jump_data {
12098            Some(jump_data) => {
12099                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12100                if let Some(buffer) = multi_buffer_snapshot
12101                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12102                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12103                {
12104                    let buffer_snapshot = buffer.read(cx).snapshot();
12105                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12106                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12107                    } else {
12108                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12109                    };
12110                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12111                    new_selections_by_buffer.insert(
12112                        buffer,
12113                        (
12114                            vec![jump_to_offset..jump_to_offset],
12115                            Some(jump_data.line_offset_from_top),
12116                        ),
12117                    );
12118                }
12119            }
12120            None => {
12121                let selections = self.selections.all::<usize>(cx);
12122                let buffer = self.buffer.read(cx);
12123                for selection in selections {
12124                    for (mut buffer_handle, mut range, _) in
12125                        buffer.range_to_buffer_ranges(selection.range(), cx)
12126                    {
12127                        // When editing branch buffers, jump to the corresponding location
12128                        // in their base buffer.
12129                        let buffer = buffer_handle.read(cx);
12130                        if let Some(base_buffer) = buffer.base_buffer() {
12131                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12132                            buffer_handle = base_buffer;
12133                        }
12134
12135                        if selection.reversed {
12136                            mem::swap(&mut range.start, &mut range.end);
12137                        }
12138                        new_selections_by_buffer
12139                            .entry(buffer_handle)
12140                            .or_insert((Vec::new(), None))
12141                            .0
12142                            .push(range)
12143                    }
12144                }
12145            }
12146        }
12147
12148        if new_selections_by_buffer.is_empty() {
12149            return;
12150        }
12151
12152        // We defer the pane interaction because we ourselves are a workspace item
12153        // and activating a new item causes the pane to call a method on us reentrantly,
12154        // which panics if we're on the stack.
12155        cx.window_context().defer(move |cx| {
12156            workspace.update(cx, |workspace, cx| {
12157                let pane = if split {
12158                    workspace.adjacent_pane(cx)
12159                } else {
12160                    workspace.active_pane().clone()
12161                };
12162
12163                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12164                    let editor = buffer
12165                        .read(cx)
12166                        .file()
12167                        .is_none()
12168                        .then(|| {
12169                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12170                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12171                            // Instead, we try to activate the existing editor in the pane first.
12172                            let (editor, pane_item_index) =
12173                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12174                                    let editor = item.downcast::<Editor>()?;
12175                                    let singleton_buffer =
12176                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12177                                    if singleton_buffer == buffer {
12178                                        Some((editor, i))
12179                                    } else {
12180                                        None
12181                                    }
12182                                })?;
12183                            pane.update(cx, |pane, cx| {
12184                                pane.activate_item(pane_item_index, true, true, cx)
12185                            });
12186                            Some(editor)
12187                        })
12188                        .flatten()
12189                        .unwrap_or_else(|| {
12190                            workspace.open_project_item::<Self>(
12191                                pane.clone(),
12192                                buffer,
12193                                true,
12194                                true,
12195                                cx,
12196                            )
12197                        });
12198
12199                    editor.update(cx, |editor, cx| {
12200                        let autoscroll = match scroll_offset {
12201                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12202                            None => Autoscroll::newest(),
12203                        };
12204                        let nav_history = editor.nav_history.take();
12205                        editor.change_selections(Some(autoscroll), cx, |s| {
12206                            s.select_ranges(ranges);
12207                        });
12208                        editor.nav_history = nav_history;
12209                    });
12210                }
12211            })
12212        });
12213    }
12214
12215    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12216        let snapshot = self.buffer.read(cx).read(cx);
12217        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12218        Some(
12219            ranges
12220                .iter()
12221                .map(move |range| {
12222                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12223                })
12224                .collect(),
12225        )
12226    }
12227
12228    fn selection_replacement_ranges(
12229        &self,
12230        range: Range<OffsetUtf16>,
12231        cx: &mut AppContext,
12232    ) -> Vec<Range<OffsetUtf16>> {
12233        let selections = self.selections.all::<OffsetUtf16>(cx);
12234        let newest_selection = selections
12235            .iter()
12236            .max_by_key(|selection| selection.id)
12237            .unwrap();
12238        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12239        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12240        let snapshot = self.buffer.read(cx).read(cx);
12241        selections
12242            .into_iter()
12243            .map(|mut selection| {
12244                selection.start.0 =
12245                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12246                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12247                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12248                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12249            })
12250            .collect()
12251    }
12252
12253    fn report_editor_event(
12254        &self,
12255        operation: &'static str,
12256        file_extension: Option<String>,
12257        cx: &AppContext,
12258    ) {
12259        if cfg!(any(test, feature = "test-support")) {
12260            return;
12261        }
12262
12263        let Some(project) = &self.project else { return };
12264
12265        // If None, we are in a file without an extension
12266        let file = self
12267            .buffer
12268            .read(cx)
12269            .as_singleton()
12270            .and_then(|b| b.read(cx).file());
12271        let file_extension = file_extension.or(file
12272            .as_ref()
12273            .and_then(|file| Path::new(file.file_name(cx)).extension())
12274            .and_then(|e| e.to_str())
12275            .map(|a| a.to_string()));
12276
12277        let vim_mode = cx
12278            .global::<SettingsStore>()
12279            .raw_user_settings()
12280            .get("vim_mode")
12281            == Some(&serde_json::Value::Bool(true));
12282
12283        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12284            == language::language_settings::InlineCompletionProvider::Copilot;
12285        let copilot_enabled_for_language = self
12286            .buffer
12287            .read(cx)
12288            .settings_at(0, cx)
12289            .show_inline_completions;
12290
12291        let project = project.read(cx);
12292        let telemetry = project.client().telemetry().clone();
12293        telemetry.report_editor_event(
12294            file_extension,
12295            vim_mode,
12296            operation,
12297            copilot_enabled,
12298            copilot_enabled_for_language,
12299            project.is_via_ssh(),
12300        )
12301    }
12302
12303    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12304    /// with each line being an array of {text, highlight} objects.
12305    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12306        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12307            return;
12308        };
12309
12310        #[derive(Serialize)]
12311        struct Chunk<'a> {
12312            text: String,
12313            highlight: Option<&'a str>,
12314        }
12315
12316        let snapshot = buffer.read(cx).snapshot();
12317        let range = self
12318            .selected_text_range(false, cx)
12319            .and_then(|selection| {
12320                if selection.range.is_empty() {
12321                    None
12322                } else {
12323                    Some(selection.range)
12324                }
12325            })
12326            .unwrap_or_else(|| 0..snapshot.len());
12327
12328        let chunks = snapshot.chunks(range, true);
12329        let mut lines = Vec::new();
12330        let mut line: VecDeque<Chunk> = VecDeque::new();
12331
12332        let Some(style) = self.style.as_ref() else {
12333            return;
12334        };
12335
12336        for chunk in chunks {
12337            let highlight = chunk
12338                .syntax_highlight_id
12339                .and_then(|id| id.name(&style.syntax));
12340            let mut chunk_lines = chunk.text.split('\n').peekable();
12341            while let Some(text) = chunk_lines.next() {
12342                let mut merged_with_last_token = false;
12343                if let Some(last_token) = line.back_mut() {
12344                    if last_token.highlight == highlight {
12345                        last_token.text.push_str(text);
12346                        merged_with_last_token = true;
12347                    }
12348                }
12349
12350                if !merged_with_last_token {
12351                    line.push_back(Chunk {
12352                        text: text.into(),
12353                        highlight,
12354                    });
12355                }
12356
12357                if chunk_lines.peek().is_some() {
12358                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12359                        line.pop_front();
12360                    }
12361                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12362                        line.pop_back();
12363                    }
12364
12365                    lines.push(mem::take(&mut line));
12366                }
12367            }
12368        }
12369
12370        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12371            return;
12372        };
12373        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12374    }
12375
12376    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12377        self.request_autoscroll(Autoscroll::newest(), cx);
12378        let position = self.selections.newest_display(cx).start;
12379        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12380    }
12381
12382    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12383        &self.inlay_hint_cache
12384    }
12385
12386    pub fn replay_insert_event(
12387        &mut self,
12388        text: &str,
12389        relative_utf16_range: Option<Range<isize>>,
12390        cx: &mut ViewContext<Self>,
12391    ) {
12392        if !self.input_enabled {
12393            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12394            return;
12395        }
12396        if let Some(relative_utf16_range) = relative_utf16_range {
12397            let selections = self.selections.all::<OffsetUtf16>(cx);
12398            self.change_selections(None, cx, |s| {
12399                let new_ranges = selections.into_iter().map(|range| {
12400                    let start = OffsetUtf16(
12401                        range
12402                            .head()
12403                            .0
12404                            .saturating_add_signed(relative_utf16_range.start),
12405                    );
12406                    let end = OffsetUtf16(
12407                        range
12408                            .head()
12409                            .0
12410                            .saturating_add_signed(relative_utf16_range.end),
12411                    );
12412                    start..end
12413                });
12414                s.select_ranges(new_ranges);
12415            });
12416        }
12417
12418        self.handle_input(text, cx);
12419    }
12420
12421    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12422        let Some(provider) = self.semantics_provider.as_ref() else {
12423            return false;
12424        };
12425
12426        let mut supports = false;
12427        self.buffer().read(cx).for_each_buffer(|buffer| {
12428            supports |= provider.supports_inlay_hints(buffer, cx);
12429        });
12430        supports
12431    }
12432
12433    pub fn focus(&self, cx: &mut WindowContext) {
12434        cx.focus(&self.focus_handle)
12435    }
12436
12437    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12438        self.focus_handle.is_focused(cx)
12439    }
12440
12441    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12442        cx.emit(EditorEvent::Focused);
12443
12444        if let Some(descendant) = self
12445            .last_focused_descendant
12446            .take()
12447            .and_then(|descendant| descendant.upgrade())
12448        {
12449            cx.focus(&descendant);
12450        } else {
12451            if let Some(blame) = self.blame.as_ref() {
12452                blame.update(cx, GitBlame::focus)
12453            }
12454
12455            self.blink_manager.update(cx, BlinkManager::enable);
12456            self.show_cursor_names(cx);
12457            self.buffer.update(cx, |buffer, cx| {
12458                buffer.finalize_last_transaction(cx);
12459                if self.leader_peer_id.is_none() {
12460                    buffer.set_active_selections(
12461                        &self.selections.disjoint_anchors(),
12462                        self.selections.line_mode,
12463                        self.cursor_shape,
12464                        cx,
12465                    );
12466                }
12467            });
12468        }
12469    }
12470
12471    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12472        cx.emit(EditorEvent::FocusedIn)
12473    }
12474
12475    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12476        if event.blurred != self.focus_handle {
12477            self.last_focused_descendant = Some(event.blurred);
12478        }
12479    }
12480
12481    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12482        self.blink_manager.update(cx, BlinkManager::disable);
12483        self.buffer
12484            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12485
12486        if let Some(blame) = self.blame.as_ref() {
12487            blame.update(cx, GitBlame::blur)
12488        }
12489        if !self.hover_state.focused(cx) {
12490            hide_hover(self, cx);
12491        }
12492
12493        self.hide_context_menu(cx);
12494        cx.emit(EditorEvent::Blurred);
12495        cx.notify();
12496    }
12497
12498    pub fn register_action<A: Action>(
12499        &mut self,
12500        listener: impl Fn(&A, &mut WindowContext) + 'static,
12501    ) -> Subscription {
12502        let id = self.next_editor_action_id.post_inc();
12503        let listener = Arc::new(listener);
12504        self.editor_actions.borrow_mut().insert(
12505            id,
12506            Box::new(move |cx| {
12507                let cx = cx.window_context();
12508                let listener = listener.clone();
12509                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12510                    let action = action.downcast_ref().unwrap();
12511                    if phase == DispatchPhase::Bubble {
12512                        listener(action, cx)
12513                    }
12514                })
12515            }),
12516        );
12517
12518        let editor_actions = self.editor_actions.clone();
12519        Subscription::new(move || {
12520            editor_actions.borrow_mut().remove(&id);
12521        })
12522    }
12523
12524    pub fn file_header_size(&self) -> u32 {
12525        FILE_HEADER_HEIGHT
12526    }
12527
12528    pub fn revert(
12529        &mut self,
12530        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12531        cx: &mut ViewContext<Self>,
12532    ) {
12533        self.buffer().update(cx, |multi_buffer, cx| {
12534            for (buffer_id, changes) in revert_changes {
12535                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12536                    buffer.update(cx, |buffer, cx| {
12537                        buffer.edit(
12538                            changes.into_iter().map(|(range, text)| {
12539                                (range, text.to_string().map(Arc::<str>::from))
12540                            }),
12541                            None,
12542                            cx,
12543                        );
12544                    });
12545                }
12546            }
12547        });
12548        self.change_selections(None, cx, |selections| selections.refresh());
12549    }
12550
12551    pub fn to_pixel_point(
12552        &mut self,
12553        source: multi_buffer::Anchor,
12554        editor_snapshot: &EditorSnapshot,
12555        cx: &mut ViewContext<Self>,
12556    ) -> Option<gpui::Point<Pixels>> {
12557        let source_point = source.to_display_point(editor_snapshot);
12558        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12559    }
12560
12561    pub fn display_to_pixel_point(
12562        &self,
12563        source: DisplayPoint,
12564        editor_snapshot: &EditorSnapshot,
12565        cx: &WindowContext,
12566    ) -> Option<gpui::Point<Pixels>> {
12567        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12568        let text_layout_details = self.text_layout_details(cx);
12569        let scroll_top = text_layout_details
12570            .scroll_anchor
12571            .scroll_position(editor_snapshot)
12572            .y;
12573
12574        if source.row().as_f32() < scroll_top.floor() {
12575            return None;
12576        }
12577        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12578        let source_y = line_height * (source.row().as_f32() - scroll_top);
12579        Some(gpui::Point::new(source_x, source_y))
12580    }
12581
12582    pub fn has_active_completions_menu(&self) -> bool {
12583        self.context_menu.read().as_ref().map_or(false, |menu| {
12584            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12585        })
12586    }
12587
12588    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12589        self.addons
12590            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12591    }
12592
12593    pub fn unregister_addon<T: Addon>(&mut self) {
12594        self.addons.remove(&std::any::TypeId::of::<T>());
12595    }
12596
12597    pub fn addon<T: Addon>(&self) -> Option<&T> {
12598        let type_id = std::any::TypeId::of::<T>();
12599        self.addons
12600            .get(&type_id)
12601            .and_then(|item| item.to_any().downcast_ref::<T>())
12602    }
12603
12604    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12605        let text_layout_details = self.text_layout_details(cx);
12606        let style = &text_layout_details.editor_style;
12607        let font_id = cx.text_system().resolve_font(&style.text.font());
12608        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12609        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12610
12611        let em_width = cx
12612            .text_system()
12613            .typographic_bounds(font_id, font_size, 'm')
12614            .unwrap()
12615            .size
12616            .width;
12617
12618        gpui::Point::new(em_width, line_height)
12619    }
12620}
12621
12622fn get_unstaged_changes_for_buffers(
12623    project: &Model<Project>,
12624    buffers: impl IntoIterator<Item = Model<Buffer>>,
12625    cx: &mut ViewContext<Editor>,
12626) {
12627    let mut tasks = Vec::new();
12628    project.update(cx, |project, cx| {
12629        for buffer in buffers {
12630            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12631        }
12632    });
12633    cx.spawn(|this, mut cx| async move {
12634        let change_sets = futures::future::join_all(tasks).await;
12635        this.update(&mut cx, |this, cx| {
12636            for change_set in change_sets {
12637                if let Some(change_set) = change_set.log_err() {
12638                    this.diff_map.add_change_set(change_set, cx);
12639                }
12640            }
12641        })
12642        .ok();
12643    })
12644    .detach();
12645}
12646
12647fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12648    let tab_size = tab_size.get() as usize;
12649    let mut width = offset;
12650
12651    for ch in text.chars() {
12652        width += if ch == '\t' {
12653            tab_size - (width % tab_size)
12654        } else {
12655            1
12656        };
12657    }
12658
12659    width - offset
12660}
12661
12662#[cfg(test)]
12663mod tests {
12664    use super::*;
12665
12666    #[test]
12667    fn test_string_size_with_expanded_tabs() {
12668        let nz = |val| NonZeroU32::new(val).unwrap();
12669        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12670        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12671        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12672        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12673        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12674        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12675        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12676        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12677    }
12678}
12679
12680/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12681struct WordBreakingTokenizer<'a> {
12682    input: &'a str,
12683}
12684
12685impl<'a> WordBreakingTokenizer<'a> {
12686    fn new(input: &'a str) -> Self {
12687        Self { input }
12688    }
12689}
12690
12691fn is_char_ideographic(ch: char) -> bool {
12692    use unicode_script::Script::*;
12693    use unicode_script::UnicodeScript;
12694    matches!(ch.script(), Han | Tangut | Yi)
12695}
12696
12697fn is_grapheme_ideographic(text: &str) -> bool {
12698    text.chars().any(is_char_ideographic)
12699}
12700
12701fn is_grapheme_whitespace(text: &str) -> bool {
12702    text.chars().any(|x| x.is_whitespace())
12703}
12704
12705fn should_stay_with_preceding_ideograph(text: &str) -> bool {
12706    text.chars().next().map_or(false, |ch| {
12707        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
12708    })
12709}
12710
12711#[derive(PartialEq, Eq, Debug, Clone, Copy)]
12712struct WordBreakToken<'a> {
12713    token: &'a str,
12714    grapheme_len: usize,
12715    is_whitespace: bool,
12716}
12717
12718impl<'a> Iterator for WordBreakingTokenizer<'a> {
12719    /// Yields a span, the count of graphemes in the token, and whether it was
12720    /// whitespace. Note that it also breaks at word boundaries.
12721    type Item = WordBreakToken<'a>;
12722
12723    fn next(&mut self) -> Option<Self::Item> {
12724        use unicode_segmentation::UnicodeSegmentation;
12725        if self.input.is_empty() {
12726            return None;
12727        }
12728
12729        let mut iter = self.input.graphemes(true).peekable();
12730        let mut offset = 0;
12731        let mut graphemes = 0;
12732        if let Some(first_grapheme) = iter.next() {
12733            let is_whitespace = is_grapheme_whitespace(first_grapheme);
12734            offset += first_grapheme.len();
12735            graphemes += 1;
12736            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
12737                if let Some(grapheme) = iter.peek().copied() {
12738                    if should_stay_with_preceding_ideograph(grapheme) {
12739                        offset += grapheme.len();
12740                        graphemes += 1;
12741                    }
12742                }
12743            } else {
12744                let mut words = self.input[offset..].split_word_bound_indices().peekable();
12745                let mut next_word_bound = words.peek().copied();
12746                if next_word_bound.map_or(false, |(i, _)| i == 0) {
12747                    next_word_bound = words.next();
12748                }
12749                while let Some(grapheme) = iter.peek().copied() {
12750                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
12751                        break;
12752                    };
12753                    if is_grapheme_whitespace(grapheme) != is_whitespace {
12754                        break;
12755                    };
12756                    offset += grapheme.len();
12757                    graphemes += 1;
12758                    iter.next();
12759                }
12760            }
12761            let token = &self.input[..offset];
12762            self.input = &self.input[offset..];
12763            if is_whitespace {
12764                Some(WordBreakToken {
12765                    token: " ",
12766                    grapheme_len: 1,
12767                    is_whitespace: true,
12768                })
12769            } else {
12770                Some(WordBreakToken {
12771                    token,
12772                    grapheme_len: graphemes,
12773                    is_whitespace: false,
12774                })
12775            }
12776        } else {
12777            None
12778        }
12779    }
12780}
12781
12782#[test]
12783fn test_word_breaking_tokenizer() {
12784    let tests: &[(&str, &[(&str, usize, bool)])] = &[
12785        ("", &[]),
12786        ("  ", &[(" ", 1, true)]),
12787        ("Ʒ", &[("Ʒ", 1, false)]),
12788        ("Ǽ", &[("Ǽ", 1, false)]),
12789        ("", &[("", 1, false)]),
12790        ("⋑⋑", &[("⋑⋑", 2, false)]),
12791        (
12792            "原理,进而",
12793            &[
12794                ("", 1, false),
12795                ("理,", 2, false),
12796                ("", 1, false),
12797                ("", 1, false),
12798            ],
12799        ),
12800        (
12801            "hello world",
12802            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
12803        ),
12804        (
12805            "hello, world",
12806            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
12807        ),
12808        (
12809            "  hello world",
12810            &[
12811                (" ", 1, true),
12812                ("hello", 5, false),
12813                (" ", 1, true),
12814                ("world", 5, false),
12815            ],
12816        ),
12817        (
12818            "这是什么 \n 钢笔",
12819            &[
12820                ("", 1, false),
12821                ("", 1, false),
12822                ("", 1, false),
12823                ("", 1, false),
12824                (" ", 1, true),
12825                ("", 1, false),
12826                ("", 1, false),
12827            ],
12828        ),
12829        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
12830    ];
12831
12832    for (input, result) in tests {
12833        assert_eq!(
12834            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
12835            result
12836                .iter()
12837                .copied()
12838                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
12839                    token,
12840                    grapheme_len,
12841                    is_whitespace,
12842                })
12843                .collect::<Vec<_>>()
12844        );
12845    }
12846}
12847
12848fn wrap_with_prefix(
12849    line_prefix: String,
12850    unwrapped_text: String,
12851    wrap_column: usize,
12852    tab_size: NonZeroU32,
12853) -> String {
12854    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
12855    let mut wrapped_text = String::new();
12856    let mut current_line = line_prefix.clone();
12857
12858    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
12859    let mut current_line_len = line_prefix_len;
12860    for WordBreakToken {
12861        token,
12862        grapheme_len,
12863        is_whitespace,
12864    } in tokenizer
12865    {
12866        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
12867            wrapped_text.push_str(current_line.trim_end());
12868            wrapped_text.push('\n');
12869            current_line.truncate(line_prefix.len());
12870            current_line_len = line_prefix_len;
12871            if !is_whitespace {
12872                current_line.push_str(token);
12873                current_line_len += grapheme_len;
12874            }
12875        } else if !is_whitespace {
12876            current_line.push_str(token);
12877            current_line_len += grapheme_len;
12878        } else if current_line_len != line_prefix_len {
12879            current_line.push(' ');
12880            current_line_len += 1;
12881        }
12882    }
12883
12884    if !current_line.is_empty() {
12885        wrapped_text.push_str(&current_line);
12886    }
12887    wrapped_text
12888}
12889
12890#[test]
12891fn test_wrap_with_prefix() {
12892    assert_eq!(
12893        wrap_with_prefix(
12894            "# ".to_string(),
12895            "abcdefg".to_string(),
12896            4,
12897            NonZeroU32::new(4).unwrap()
12898        ),
12899        "# abcdefg"
12900    );
12901    assert_eq!(
12902        wrap_with_prefix(
12903            "".to_string(),
12904            "\thello world".to_string(),
12905            8,
12906            NonZeroU32::new(4).unwrap()
12907        ),
12908        "hello\nworld"
12909    );
12910    assert_eq!(
12911        wrap_with_prefix(
12912            "// ".to_string(),
12913            "xx \nyy zz aa bb cc".to_string(),
12914            12,
12915            NonZeroU32::new(4).unwrap()
12916        ),
12917        "// xx yy zz\n// aa bb cc"
12918    );
12919    assert_eq!(
12920        wrap_with_prefix(
12921            String::new(),
12922            "这是什么 \n 钢笔".to_string(),
12923            3,
12924            NonZeroU32::new(4).unwrap()
12925        ),
12926        "这是什\n么 钢\n"
12927    );
12928}
12929
12930fn hunks_for_selections(
12931    snapshot: &EditorSnapshot,
12932    selections: &[Selection<Point>],
12933) -> Vec<MultiBufferDiffHunk> {
12934    hunks_for_ranges(
12935        selections.iter().map(|selection| selection.range()),
12936        snapshot,
12937    )
12938}
12939
12940pub fn hunks_for_ranges(
12941    ranges: impl Iterator<Item = Range<Point>>,
12942    snapshot: &EditorSnapshot,
12943) -> Vec<MultiBufferDiffHunk> {
12944    let mut hunks = Vec::new();
12945    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12946        HashMap::default();
12947    for query_range in ranges {
12948        let query_rows =
12949            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
12950        for hunk in snapshot.diff_map.diff_hunks_in_range(
12951            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
12952            &snapshot.buffer_snapshot,
12953        ) {
12954            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12955            // when the caret is just above or just below the deleted hunk.
12956            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12957            let related_to_selection = if allow_adjacent {
12958                hunk.row_range.overlaps(&query_rows)
12959                    || hunk.row_range.start == query_rows.end
12960                    || hunk.row_range.end == query_rows.start
12961            } else {
12962                hunk.row_range.overlaps(&query_rows)
12963            };
12964            if related_to_selection {
12965                if !processed_buffer_rows
12966                    .entry(hunk.buffer_id)
12967                    .or_default()
12968                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12969                {
12970                    continue;
12971                }
12972                hunks.push(hunk);
12973            }
12974        }
12975    }
12976
12977    hunks
12978}
12979
12980pub trait CollaborationHub {
12981    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12982    fn user_participant_indices<'a>(
12983        &self,
12984        cx: &'a AppContext,
12985    ) -> &'a HashMap<u64, ParticipantIndex>;
12986    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12987}
12988
12989impl CollaborationHub for Model<Project> {
12990    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12991        self.read(cx).collaborators()
12992    }
12993
12994    fn user_participant_indices<'a>(
12995        &self,
12996        cx: &'a AppContext,
12997    ) -> &'a HashMap<u64, ParticipantIndex> {
12998        self.read(cx).user_store().read(cx).participant_indices()
12999    }
13000
13001    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13002        let this = self.read(cx);
13003        let user_ids = this.collaborators().values().map(|c| c.user_id);
13004        this.user_store().read_with(cx, |user_store, cx| {
13005            user_store.participant_names(user_ids, cx)
13006        })
13007    }
13008}
13009
13010pub trait SemanticsProvider {
13011    fn hover(
13012        &self,
13013        buffer: &Model<Buffer>,
13014        position: text::Anchor,
13015        cx: &mut AppContext,
13016    ) -> Option<Task<Vec<project::Hover>>>;
13017
13018    fn inlay_hints(
13019        &self,
13020        buffer_handle: Model<Buffer>,
13021        range: Range<text::Anchor>,
13022        cx: &mut AppContext,
13023    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13024
13025    fn resolve_inlay_hint(
13026        &self,
13027        hint: InlayHint,
13028        buffer_handle: Model<Buffer>,
13029        server_id: LanguageServerId,
13030        cx: &mut AppContext,
13031    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13032
13033    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13034
13035    fn document_highlights(
13036        &self,
13037        buffer: &Model<Buffer>,
13038        position: text::Anchor,
13039        cx: &mut AppContext,
13040    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13041
13042    fn definitions(
13043        &self,
13044        buffer: &Model<Buffer>,
13045        position: text::Anchor,
13046        kind: GotoDefinitionKind,
13047        cx: &mut AppContext,
13048    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13049
13050    fn range_for_rename(
13051        &self,
13052        buffer: &Model<Buffer>,
13053        position: text::Anchor,
13054        cx: &mut AppContext,
13055    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13056
13057    fn perform_rename(
13058        &self,
13059        buffer: &Model<Buffer>,
13060        position: text::Anchor,
13061        new_name: String,
13062        cx: &mut AppContext,
13063    ) -> Option<Task<Result<ProjectTransaction>>>;
13064}
13065
13066pub trait CompletionProvider {
13067    fn completions(
13068        &self,
13069        buffer: &Model<Buffer>,
13070        buffer_position: text::Anchor,
13071        trigger: CompletionContext,
13072        cx: &mut ViewContext<Editor>,
13073    ) -> Task<Result<Vec<Completion>>>;
13074
13075    fn resolve_completions(
13076        &self,
13077        buffer: Model<Buffer>,
13078        completion_indices: Vec<usize>,
13079        completions: Arc<RwLock<Box<[Completion]>>>,
13080        cx: &mut ViewContext<Editor>,
13081    ) -> Task<Result<bool>>;
13082
13083    fn apply_additional_edits_for_completion(
13084        &self,
13085        buffer: Model<Buffer>,
13086        completion: Completion,
13087        push_to_history: bool,
13088        cx: &mut ViewContext<Editor>,
13089    ) -> Task<Result<Option<language::Transaction>>>;
13090
13091    fn is_completion_trigger(
13092        &self,
13093        buffer: &Model<Buffer>,
13094        position: language::Anchor,
13095        text: &str,
13096        trigger_in_words: bool,
13097        cx: &mut ViewContext<Editor>,
13098    ) -> bool;
13099
13100    fn sort_completions(&self) -> bool {
13101        true
13102    }
13103}
13104
13105pub trait CodeActionProvider {
13106    fn code_actions(
13107        &self,
13108        buffer: &Model<Buffer>,
13109        range: Range<text::Anchor>,
13110        cx: &mut WindowContext,
13111    ) -> Task<Result<Vec<CodeAction>>>;
13112
13113    fn apply_code_action(
13114        &self,
13115        buffer_handle: Model<Buffer>,
13116        action: CodeAction,
13117        excerpt_id: ExcerptId,
13118        push_to_history: bool,
13119        cx: &mut WindowContext,
13120    ) -> Task<Result<ProjectTransaction>>;
13121}
13122
13123impl CodeActionProvider for Model<Project> {
13124    fn code_actions(
13125        &self,
13126        buffer: &Model<Buffer>,
13127        range: Range<text::Anchor>,
13128        cx: &mut WindowContext,
13129    ) -> Task<Result<Vec<CodeAction>>> {
13130        self.update(cx, |project, cx| {
13131            project.code_actions(buffer, range, None, cx)
13132        })
13133    }
13134
13135    fn apply_code_action(
13136        &self,
13137        buffer_handle: Model<Buffer>,
13138        action: CodeAction,
13139        _excerpt_id: ExcerptId,
13140        push_to_history: bool,
13141        cx: &mut WindowContext,
13142    ) -> Task<Result<ProjectTransaction>> {
13143        self.update(cx, |project, cx| {
13144            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13145        })
13146    }
13147}
13148
13149fn snippet_completions(
13150    project: &Project,
13151    buffer: &Model<Buffer>,
13152    buffer_position: text::Anchor,
13153    cx: &mut AppContext,
13154) -> Task<Result<Vec<Completion>>> {
13155    let language = buffer.read(cx).language_at(buffer_position);
13156    let language_name = language.as_ref().map(|language| language.lsp_id());
13157    let snippet_store = project.snippets().read(cx);
13158    let snippets = snippet_store.snippets_for(language_name, cx);
13159
13160    if snippets.is_empty() {
13161        return Task::ready(Ok(vec![]));
13162    }
13163    let snapshot = buffer.read(cx).text_snapshot();
13164    let chars: String = snapshot
13165        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13166        .collect();
13167
13168    let scope = language.map(|language| language.default_scope());
13169    let executor = cx.background_executor().clone();
13170
13171    cx.background_executor().spawn(async move {
13172        let classifier = CharClassifier::new(scope).for_completion(true);
13173        let mut last_word = chars
13174            .chars()
13175            .take_while(|c| classifier.is_word(*c))
13176            .collect::<String>();
13177        last_word = last_word.chars().rev().collect();
13178
13179        if last_word.is_empty() {
13180            return Ok(vec![]);
13181        }
13182
13183        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13184        let to_lsp = |point: &text::Anchor| {
13185            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13186            point_to_lsp(end)
13187        };
13188        let lsp_end = to_lsp(&buffer_position);
13189
13190        let candidates = snippets
13191            .iter()
13192            .enumerate()
13193            .flat_map(|(ix, snippet)| {
13194                snippet
13195                    .prefix
13196                    .iter()
13197                    .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
13198            })
13199            .collect::<Vec<StringMatchCandidate>>();
13200
13201        let mut matches = fuzzy::match_strings(
13202            &candidates,
13203            &last_word,
13204            last_word.chars().any(|c| c.is_uppercase()),
13205            100,
13206            &Default::default(),
13207            executor,
13208        )
13209        .await;
13210
13211        // Remove all candidates where the query's start does not match the start of any word in the candidate
13212        if let Some(query_start) = last_word.chars().next() {
13213            matches.retain(|string_match| {
13214                split_words(&string_match.string).any(|word| {
13215                    // Check that the first codepoint of the word as lowercase matches the first
13216                    // codepoint of the query as lowercase
13217                    word.chars()
13218                        .flat_map(|codepoint| codepoint.to_lowercase())
13219                        .zip(query_start.to_lowercase())
13220                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13221                })
13222            });
13223        }
13224
13225        let matched_strings = matches
13226            .into_iter()
13227            .map(|m| m.string)
13228            .collect::<HashSet<_>>();
13229
13230        let result: Vec<Completion> = snippets
13231            .into_iter()
13232            .filter_map(|snippet| {
13233                let matching_prefix = snippet
13234                    .prefix
13235                    .iter()
13236                    .find(|prefix| matched_strings.contains(*prefix))?;
13237                let start = as_offset - last_word.len();
13238                let start = snapshot.anchor_before(start);
13239                let range = start..buffer_position;
13240                let lsp_start = to_lsp(&start);
13241                let lsp_range = lsp::Range {
13242                    start: lsp_start,
13243                    end: lsp_end,
13244                };
13245                Some(Completion {
13246                    old_range: range,
13247                    new_text: snippet.body.clone(),
13248                    label: CodeLabel {
13249                        text: matching_prefix.clone(),
13250                        runs: vec![],
13251                        filter_range: 0..matching_prefix.len(),
13252                    },
13253                    server_id: LanguageServerId(usize::MAX),
13254                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13255                    lsp_completion: lsp::CompletionItem {
13256                        label: snippet.prefix.first().unwrap().clone(),
13257                        kind: Some(CompletionItemKind::SNIPPET),
13258                        label_details: snippet.description.as_ref().map(|description| {
13259                            lsp::CompletionItemLabelDetails {
13260                                detail: Some(description.clone()),
13261                                description: None,
13262                            }
13263                        }),
13264                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13265                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13266                            lsp::InsertReplaceEdit {
13267                                new_text: snippet.body.clone(),
13268                                insert: lsp_range,
13269                                replace: lsp_range,
13270                            },
13271                        )),
13272                        filter_text: Some(snippet.body.clone()),
13273                        sort_text: Some(char::MAX.to_string()),
13274                        ..Default::default()
13275                    },
13276                    confirm: None,
13277                })
13278            })
13279            .collect();
13280
13281        Ok(result)
13282    })
13283}
13284
13285impl CompletionProvider for Model<Project> {
13286    fn completions(
13287        &self,
13288        buffer: &Model<Buffer>,
13289        buffer_position: text::Anchor,
13290        options: CompletionContext,
13291        cx: &mut ViewContext<Editor>,
13292    ) -> Task<Result<Vec<Completion>>> {
13293        self.update(cx, |project, cx| {
13294            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13295            let project_completions = project.completions(buffer, buffer_position, options, cx);
13296            cx.background_executor().spawn(async move {
13297                let mut completions = project_completions.await?;
13298                let snippets_completions = snippets.await?;
13299                completions.extend(snippets_completions);
13300                Ok(completions)
13301            })
13302        })
13303    }
13304
13305    fn resolve_completions(
13306        &self,
13307        buffer: Model<Buffer>,
13308        completion_indices: Vec<usize>,
13309        completions: Arc<RwLock<Box<[Completion]>>>,
13310        cx: &mut ViewContext<Editor>,
13311    ) -> Task<Result<bool>> {
13312        self.update(cx, |project, cx| {
13313            project.resolve_completions(buffer, completion_indices, completions, cx)
13314        })
13315    }
13316
13317    fn apply_additional_edits_for_completion(
13318        &self,
13319        buffer: Model<Buffer>,
13320        completion: Completion,
13321        push_to_history: bool,
13322        cx: &mut ViewContext<Editor>,
13323    ) -> Task<Result<Option<language::Transaction>>> {
13324        self.update(cx, |project, cx| {
13325            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13326        })
13327    }
13328
13329    fn is_completion_trigger(
13330        &self,
13331        buffer: &Model<Buffer>,
13332        position: language::Anchor,
13333        text: &str,
13334        trigger_in_words: bool,
13335        cx: &mut ViewContext<Editor>,
13336    ) -> bool {
13337        let mut chars = text.chars();
13338        let char = if let Some(char) = chars.next() {
13339            char
13340        } else {
13341            return false;
13342        };
13343        if chars.next().is_some() {
13344            return false;
13345        }
13346
13347        let buffer = buffer.read(cx);
13348        let snapshot = buffer.snapshot();
13349        if !snapshot.settings_at(position, cx).show_completions_on_input {
13350            return false;
13351        }
13352        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13353        if trigger_in_words && classifier.is_word(char) {
13354            return true;
13355        }
13356
13357        buffer.completion_triggers().contains(text)
13358    }
13359}
13360
13361impl SemanticsProvider for Model<Project> {
13362    fn hover(
13363        &self,
13364        buffer: &Model<Buffer>,
13365        position: text::Anchor,
13366        cx: &mut AppContext,
13367    ) -> Option<Task<Vec<project::Hover>>> {
13368        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13369    }
13370
13371    fn document_highlights(
13372        &self,
13373        buffer: &Model<Buffer>,
13374        position: text::Anchor,
13375        cx: &mut AppContext,
13376    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13377        Some(self.update(cx, |project, cx| {
13378            project.document_highlights(buffer, position, cx)
13379        }))
13380    }
13381
13382    fn definitions(
13383        &self,
13384        buffer: &Model<Buffer>,
13385        position: text::Anchor,
13386        kind: GotoDefinitionKind,
13387        cx: &mut AppContext,
13388    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13389        Some(self.update(cx, |project, cx| match kind {
13390            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13391            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13392            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13393            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13394        }))
13395    }
13396
13397    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13398        // TODO: make this work for remote projects
13399        self.read(cx)
13400            .language_servers_for_local_buffer(buffer.read(cx), cx)
13401            .any(
13402                |(_, server)| match server.capabilities().inlay_hint_provider {
13403                    Some(lsp::OneOf::Left(enabled)) => enabled,
13404                    Some(lsp::OneOf::Right(_)) => true,
13405                    None => false,
13406                },
13407            )
13408    }
13409
13410    fn inlay_hints(
13411        &self,
13412        buffer_handle: Model<Buffer>,
13413        range: Range<text::Anchor>,
13414        cx: &mut AppContext,
13415    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13416        Some(self.update(cx, |project, cx| {
13417            project.inlay_hints(buffer_handle, range, cx)
13418        }))
13419    }
13420
13421    fn resolve_inlay_hint(
13422        &self,
13423        hint: InlayHint,
13424        buffer_handle: Model<Buffer>,
13425        server_id: LanguageServerId,
13426        cx: &mut AppContext,
13427    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13428        Some(self.update(cx, |project, cx| {
13429            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13430        }))
13431    }
13432
13433    fn range_for_rename(
13434        &self,
13435        buffer: &Model<Buffer>,
13436        position: text::Anchor,
13437        cx: &mut AppContext,
13438    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13439        Some(self.update(cx, |project, cx| {
13440            project.prepare_rename(buffer.clone(), position, cx)
13441        }))
13442    }
13443
13444    fn perform_rename(
13445        &self,
13446        buffer: &Model<Buffer>,
13447        position: text::Anchor,
13448        new_name: String,
13449        cx: &mut AppContext,
13450    ) -> Option<Task<Result<ProjectTransaction>>> {
13451        Some(self.update(cx, |project, cx| {
13452            project.perform_rename(buffer.clone(), position, new_name, cx)
13453        }))
13454    }
13455}
13456
13457fn inlay_hint_settings(
13458    location: Anchor,
13459    snapshot: &MultiBufferSnapshot,
13460    cx: &mut ViewContext<'_, Editor>,
13461) -> InlayHintSettings {
13462    let file = snapshot.file_at(location);
13463    let language = snapshot.language_at(location).map(|l| l.name());
13464    language_settings(language, file, cx).inlay_hints
13465}
13466
13467fn consume_contiguous_rows(
13468    contiguous_row_selections: &mut Vec<Selection<Point>>,
13469    selection: &Selection<Point>,
13470    display_map: &DisplaySnapshot,
13471    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13472) -> (MultiBufferRow, MultiBufferRow) {
13473    contiguous_row_selections.push(selection.clone());
13474    let start_row = MultiBufferRow(selection.start.row);
13475    let mut end_row = ending_row(selection, display_map);
13476
13477    while let Some(next_selection) = selections.peek() {
13478        if next_selection.start.row <= end_row.0 {
13479            end_row = ending_row(next_selection, display_map);
13480            contiguous_row_selections.push(selections.next().unwrap().clone());
13481        } else {
13482            break;
13483        }
13484    }
13485    (start_row, end_row)
13486}
13487
13488fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13489    if next_selection.end.column > 0 || next_selection.is_empty() {
13490        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13491    } else {
13492        MultiBufferRow(next_selection.end.row)
13493    }
13494}
13495
13496impl EditorSnapshot {
13497    pub fn remote_selections_in_range<'a>(
13498        &'a self,
13499        range: &'a Range<Anchor>,
13500        collaboration_hub: &dyn CollaborationHub,
13501        cx: &'a AppContext,
13502    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13503        let participant_names = collaboration_hub.user_names(cx);
13504        let participant_indices = collaboration_hub.user_participant_indices(cx);
13505        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13506        let collaborators_by_replica_id = collaborators_by_peer_id
13507            .iter()
13508            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13509            .collect::<HashMap<_, _>>();
13510        self.buffer_snapshot
13511            .selections_in_range(range, false)
13512            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13513                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13514                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13515                let user_name = participant_names.get(&collaborator.user_id).cloned();
13516                Some(RemoteSelection {
13517                    replica_id,
13518                    selection,
13519                    cursor_shape,
13520                    line_mode,
13521                    participant_index,
13522                    peer_id: collaborator.peer_id,
13523                    user_name,
13524                })
13525            })
13526    }
13527
13528    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13529        self.display_snapshot.buffer_snapshot.language_at(position)
13530    }
13531
13532    pub fn is_focused(&self) -> bool {
13533        self.is_focused
13534    }
13535
13536    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13537        self.placeholder_text.as_ref()
13538    }
13539
13540    pub fn scroll_position(&self) -> gpui::Point<f32> {
13541        self.scroll_anchor.scroll_position(&self.display_snapshot)
13542    }
13543
13544    fn gutter_dimensions(
13545        &self,
13546        font_id: FontId,
13547        font_size: Pixels,
13548        em_width: Pixels,
13549        em_advance: Pixels,
13550        max_line_number_width: Pixels,
13551        cx: &AppContext,
13552    ) -> GutterDimensions {
13553        if !self.show_gutter {
13554            return GutterDimensions::default();
13555        }
13556        let descent = cx.text_system().descent(font_id, font_size);
13557
13558        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13559            matches!(
13560                ProjectSettings::get_global(cx).git.git_gutter,
13561                Some(GitGutterSetting::TrackedFiles)
13562            )
13563        });
13564        let gutter_settings = EditorSettings::get_global(cx).gutter;
13565        let show_line_numbers = self
13566            .show_line_numbers
13567            .unwrap_or(gutter_settings.line_numbers);
13568        let line_gutter_width = if show_line_numbers {
13569            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13570            let min_width_for_number_on_gutter = em_advance * 4.0;
13571            max_line_number_width.max(min_width_for_number_on_gutter)
13572        } else {
13573            0.0.into()
13574        };
13575
13576        let show_code_actions = self
13577            .show_code_actions
13578            .unwrap_or(gutter_settings.code_actions);
13579
13580        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13581
13582        let git_blame_entries_width =
13583            self.git_blame_gutter_max_author_length
13584                .map(|max_author_length| {
13585                    // Length of the author name, but also space for the commit hash,
13586                    // the spacing and the timestamp.
13587                    let max_char_count = max_author_length
13588                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13589                        + 7 // length of commit sha
13590                        + 14 // length of max relative timestamp ("60 minutes ago")
13591                        + 4; // gaps and margins
13592
13593                    em_advance * max_char_count
13594                });
13595
13596        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13597        left_padding += if show_code_actions || show_runnables {
13598            em_width * 3.0
13599        } else if show_git_gutter && show_line_numbers {
13600            em_width * 2.0
13601        } else if show_git_gutter || show_line_numbers {
13602            em_width
13603        } else {
13604            px(0.)
13605        };
13606
13607        let right_padding = if gutter_settings.folds && show_line_numbers {
13608            em_width * 4.0
13609        } else if gutter_settings.folds {
13610            em_width * 3.0
13611        } else if show_line_numbers {
13612            em_width
13613        } else {
13614            px(0.)
13615        };
13616
13617        GutterDimensions {
13618            left_padding,
13619            right_padding,
13620            width: line_gutter_width + left_padding + right_padding,
13621            margin: -descent,
13622            git_blame_entries_width,
13623        }
13624    }
13625
13626    pub fn render_crease_toggle(
13627        &self,
13628        buffer_row: MultiBufferRow,
13629        row_contains_cursor: bool,
13630        editor: View<Editor>,
13631        cx: &mut WindowContext,
13632    ) -> Option<AnyElement> {
13633        let folded = self.is_line_folded(buffer_row);
13634        let mut is_foldable = false;
13635
13636        if let Some(crease) = self
13637            .crease_snapshot
13638            .query_row(buffer_row, &self.buffer_snapshot)
13639        {
13640            is_foldable = true;
13641            match crease {
13642                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13643                    if let Some(render_toggle) = render_toggle {
13644                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13645                            if folded {
13646                                editor.update(cx, |editor, cx| {
13647                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13648                                });
13649                            } else {
13650                                editor.update(cx, |editor, cx| {
13651                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13652                                });
13653                            }
13654                        });
13655                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13656                    }
13657                }
13658            }
13659        }
13660
13661        is_foldable |= self.starts_indent(buffer_row);
13662
13663        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13664            Some(
13665                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13666                    .selected(folded)
13667                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13668                        if folded {
13669                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13670                        } else {
13671                            this.fold_at(&FoldAt { buffer_row }, cx);
13672                        }
13673                    }))
13674                    .into_any_element(),
13675            )
13676        } else {
13677            None
13678        }
13679    }
13680
13681    pub fn render_crease_trailer(
13682        &self,
13683        buffer_row: MultiBufferRow,
13684        cx: &mut WindowContext,
13685    ) -> Option<AnyElement> {
13686        let folded = self.is_line_folded(buffer_row);
13687        if let Crease::Inline { render_trailer, .. } = self
13688            .crease_snapshot
13689            .query_row(buffer_row, &self.buffer_snapshot)?
13690        {
13691            let render_trailer = render_trailer.as_ref()?;
13692            Some(render_trailer(buffer_row, folded, cx))
13693        } else {
13694            None
13695        }
13696    }
13697}
13698
13699impl Deref for EditorSnapshot {
13700    type Target = DisplaySnapshot;
13701
13702    fn deref(&self) -> &Self::Target {
13703        &self.display_snapshot
13704    }
13705}
13706
13707#[derive(Clone, Debug, PartialEq, Eq)]
13708pub enum EditorEvent {
13709    InputIgnored {
13710        text: Arc<str>,
13711    },
13712    InputHandled {
13713        utf16_range_to_replace: Option<Range<isize>>,
13714        text: Arc<str>,
13715    },
13716    ExcerptsAdded {
13717        buffer: Model<Buffer>,
13718        predecessor: ExcerptId,
13719        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13720    },
13721    ExcerptsRemoved {
13722        ids: Vec<ExcerptId>,
13723    },
13724    ExcerptsEdited {
13725        ids: Vec<ExcerptId>,
13726    },
13727    ExcerptsExpanded {
13728        ids: Vec<ExcerptId>,
13729    },
13730    BufferEdited,
13731    Edited {
13732        transaction_id: clock::Lamport,
13733    },
13734    Reparsed(BufferId),
13735    Focused,
13736    FocusedIn,
13737    Blurred,
13738    DirtyChanged,
13739    Saved,
13740    TitleChanged,
13741    DiffBaseChanged,
13742    SelectionsChanged {
13743        local: bool,
13744    },
13745    ScrollPositionChanged {
13746        local: bool,
13747        autoscroll: bool,
13748    },
13749    Closed,
13750    TransactionUndone {
13751        transaction_id: clock::Lamport,
13752    },
13753    TransactionBegun {
13754        transaction_id: clock::Lamport,
13755    },
13756    Reloaded,
13757    CursorShapeChanged,
13758}
13759
13760impl EventEmitter<EditorEvent> for Editor {}
13761
13762impl FocusableView for Editor {
13763    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13764        self.focus_handle.clone()
13765    }
13766}
13767
13768impl Render for Editor {
13769    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13770        let settings = ThemeSettings::get_global(cx);
13771
13772        let mut text_style = match self.mode {
13773            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13774                color: cx.theme().colors().editor_foreground,
13775                font_family: settings.ui_font.family.clone(),
13776                font_features: settings.ui_font.features.clone(),
13777                font_fallbacks: settings.ui_font.fallbacks.clone(),
13778                font_size: rems(0.875).into(),
13779                font_weight: settings.ui_font.weight,
13780                line_height: relative(settings.buffer_line_height.value()),
13781                ..Default::default()
13782            },
13783            EditorMode::Full => TextStyle {
13784                color: cx.theme().colors().editor_foreground,
13785                font_family: settings.buffer_font.family.clone(),
13786                font_features: settings.buffer_font.features.clone(),
13787                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13788                font_size: settings.buffer_font_size(cx).into(),
13789                font_weight: settings.buffer_font.weight,
13790                line_height: relative(settings.buffer_line_height.value()),
13791                ..Default::default()
13792            },
13793        };
13794        if let Some(text_style_refinement) = &self.text_style_refinement {
13795            text_style.refine(text_style_refinement)
13796        }
13797
13798        let background = match self.mode {
13799            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13800            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13801            EditorMode::Full => cx.theme().colors().editor_background,
13802        };
13803
13804        EditorElement::new(
13805            cx.view(),
13806            EditorStyle {
13807                background,
13808                local_player: cx.theme().players().local(),
13809                text: text_style,
13810                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13811                syntax: cx.theme().syntax().clone(),
13812                status: cx.theme().status().clone(),
13813                inlay_hints_style: make_inlay_hints_style(cx),
13814                suggestions_style: HighlightStyle {
13815                    color: Some(cx.theme().status().predictive),
13816                    ..HighlightStyle::default()
13817                },
13818                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13819            },
13820        )
13821    }
13822}
13823
13824impl ViewInputHandler for Editor {
13825    fn text_for_range(
13826        &mut self,
13827        range_utf16: Range<usize>,
13828        adjusted_range: &mut Option<Range<usize>>,
13829        cx: &mut ViewContext<Self>,
13830    ) -> Option<String> {
13831        let snapshot = self.buffer.read(cx).read(cx);
13832        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
13833        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
13834        if (start.0..end.0) != range_utf16 {
13835            adjusted_range.replace(start.0..end.0);
13836        }
13837        Some(snapshot.text_for_range(start..end).collect())
13838    }
13839
13840    fn selected_text_range(
13841        &mut self,
13842        ignore_disabled_input: bool,
13843        cx: &mut ViewContext<Self>,
13844    ) -> Option<UTF16Selection> {
13845        // Prevent the IME menu from appearing when holding down an alphabetic key
13846        // while input is disabled.
13847        if !ignore_disabled_input && !self.input_enabled {
13848            return None;
13849        }
13850
13851        let selection = self.selections.newest::<OffsetUtf16>(cx);
13852        let range = selection.range();
13853
13854        Some(UTF16Selection {
13855            range: range.start.0..range.end.0,
13856            reversed: selection.reversed,
13857        })
13858    }
13859
13860    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13861        let snapshot = self.buffer.read(cx).read(cx);
13862        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13863        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13864    }
13865
13866    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13867        self.clear_highlights::<InputComposition>(cx);
13868        self.ime_transaction.take();
13869    }
13870
13871    fn replace_text_in_range(
13872        &mut self,
13873        range_utf16: Option<Range<usize>>,
13874        text: &str,
13875        cx: &mut ViewContext<Self>,
13876    ) {
13877        if !self.input_enabled {
13878            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13879            return;
13880        }
13881
13882        self.transact(cx, |this, cx| {
13883            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13884                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13885                Some(this.selection_replacement_ranges(range_utf16, cx))
13886            } else {
13887                this.marked_text_ranges(cx)
13888            };
13889
13890            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13891                let newest_selection_id = this.selections.newest_anchor().id;
13892                this.selections
13893                    .all::<OffsetUtf16>(cx)
13894                    .iter()
13895                    .zip(ranges_to_replace.iter())
13896                    .find_map(|(selection, range)| {
13897                        if selection.id == newest_selection_id {
13898                            Some(
13899                                (range.start.0 as isize - selection.head().0 as isize)
13900                                    ..(range.end.0 as isize - selection.head().0 as isize),
13901                            )
13902                        } else {
13903                            None
13904                        }
13905                    })
13906            });
13907
13908            cx.emit(EditorEvent::InputHandled {
13909                utf16_range_to_replace: range_to_replace,
13910                text: text.into(),
13911            });
13912
13913            if let Some(new_selected_ranges) = new_selected_ranges {
13914                this.change_selections(None, cx, |selections| {
13915                    selections.select_ranges(new_selected_ranges)
13916                });
13917                this.backspace(&Default::default(), cx);
13918            }
13919
13920            this.handle_input(text, cx);
13921        });
13922
13923        if let Some(transaction) = self.ime_transaction {
13924            self.buffer.update(cx, |buffer, cx| {
13925                buffer.group_until_transaction(transaction, cx);
13926            });
13927        }
13928
13929        self.unmark_text(cx);
13930    }
13931
13932    fn replace_and_mark_text_in_range(
13933        &mut self,
13934        range_utf16: Option<Range<usize>>,
13935        text: &str,
13936        new_selected_range_utf16: Option<Range<usize>>,
13937        cx: &mut ViewContext<Self>,
13938    ) {
13939        if !self.input_enabled {
13940            return;
13941        }
13942
13943        let transaction = self.transact(cx, |this, cx| {
13944            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13945                let snapshot = this.buffer.read(cx).read(cx);
13946                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13947                    for marked_range in &mut marked_ranges {
13948                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13949                        marked_range.start.0 += relative_range_utf16.start;
13950                        marked_range.start =
13951                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13952                        marked_range.end =
13953                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13954                    }
13955                }
13956                Some(marked_ranges)
13957            } else if let Some(range_utf16) = range_utf16 {
13958                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13959                Some(this.selection_replacement_ranges(range_utf16, cx))
13960            } else {
13961                None
13962            };
13963
13964            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13965                let newest_selection_id = this.selections.newest_anchor().id;
13966                this.selections
13967                    .all::<OffsetUtf16>(cx)
13968                    .iter()
13969                    .zip(ranges_to_replace.iter())
13970                    .find_map(|(selection, range)| {
13971                        if selection.id == newest_selection_id {
13972                            Some(
13973                                (range.start.0 as isize - selection.head().0 as isize)
13974                                    ..(range.end.0 as isize - selection.head().0 as isize),
13975                            )
13976                        } else {
13977                            None
13978                        }
13979                    })
13980            });
13981
13982            cx.emit(EditorEvent::InputHandled {
13983                utf16_range_to_replace: range_to_replace,
13984                text: text.into(),
13985            });
13986
13987            if let Some(ranges) = ranges_to_replace {
13988                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13989            }
13990
13991            let marked_ranges = {
13992                let snapshot = this.buffer.read(cx).read(cx);
13993                this.selections
13994                    .disjoint_anchors()
13995                    .iter()
13996                    .map(|selection| {
13997                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13998                    })
13999                    .collect::<Vec<_>>()
14000            };
14001
14002            if text.is_empty() {
14003                this.unmark_text(cx);
14004            } else {
14005                this.highlight_text::<InputComposition>(
14006                    marked_ranges.clone(),
14007                    HighlightStyle {
14008                        underline: Some(UnderlineStyle {
14009                            thickness: px(1.),
14010                            color: None,
14011                            wavy: false,
14012                        }),
14013                        ..Default::default()
14014                    },
14015                    cx,
14016                );
14017            }
14018
14019            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14020            let use_autoclose = this.use_autoclose;
14021            let use_auto_surround = this.use_auto_surround;
14022            this.set_use_autoclose(false);
14023            this.set_use_auto_surround(false);
14024            this.handle_input(text, cx);
14025            this.set_use_autoclose(use_autoclose);
14026            this.set_use_auto_surround(use_auto_surround);
14027
14028            if let Some(new_selected_range) = new_selected_range_utf16 {
14029                let snapshot = this.buffer.read(cx).read(cx);
14030                let new_selected_ranges = marked_ranges
14031                    .into_iter()
14032                    .map(|marked_range| {
14033                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14034                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14035                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14036                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14037                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14038                    })
14039                    .collect::<Vec<_>>();
14040
14041                drop(snapshot);
14042                this.change_selections(None, cx, |selections| {
14043                    selections.select_ranges(new_selected_ranges)
14044                });
14045            }
14046        });
14047
14048        self.ime_transaction = self.ime_transaction.or(transaction);
14049        if let Some(transaction) = self.ime_transaction {
14050            self.buffer.update(cx, |buffer, cx| {
14051                buffer.group_until_transaction(transaction, cx);
14052            });
14053        }
14054
14055        if self.text_highlights::<InputComposition>(cx).is_none() {
14056            self.ime_transaction.take();
14057        }
14058    }
14059
14060    fn bounds_for_range(
14061        &mut self,
14062        range_utf16: Range<usize>,
14063        element_bounds: gpui::Bounds<Pixels>,
14064        cx: &mut ViewContext<Self>,
14065    ) -> Option<gpui::Bounds<Pixels>> {
14066        let text_layout_details = self.text_layout_details(cx);
14067        let gpui::Point {
14068            x: em_width,
14069            y: line_height,
14070        } = self.character_size(cx);
14071
14072        let snapshot = self.snapshot(cx);
14073        let scroll_position = snapshot.scroll_position();
14074        let scroll_left = scroll_position.x * em_width;
14075
14076        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14077        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14078            + self.gutter_dimensions.width
14079            + self.gutter_dimensions.margin;
14080        let y = line_height * (start.row().as_f32() - scroll_position.y);
14081
14082        Some(Bounds {
14083            origin: element_bounds.origin + point(x, y),
14084            size: size(em_width, line_height),
14085        })
14086    }
14087}
14088
14089trait SelectionExt {
14090    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14091    fn spanned_rows(
14092        &self,
14093        include_end_if_at_line_start: bool,
14094        map: &DisplaySnapshot,
14095    ) -> Range<MultiBufferRow>;
14096}
14097
14098impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14099    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14100        let start = self
14101            .start
14102            .to_point(&map.buffer_snapshot)
14103            .to_display_point(map);
14104        let end = self
14105            .end
14106            .to_point(&map.buffer_snapshot)
14107            .to_display_point(map);
14108        if self.reversed {
14109            end..start
14110        } else {
14111            start..end
14112        }
14113    }
14114
14115    fn spanned_rows(
14116        &self,
14117        include_end_if_at_line_start: bool,
14118        map: &DisplaySnapshot,
14119    ) -> Range<MultiBufferRow> {
14120        let start = self.start.to_point(&map.buffer_snapshot);
14121        let mut end = self.end.to_point(&map.buffer_snapshot);
14122        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14123            end.row -= 1;
14124        }
14125
14126        let buffer_start = map.prev_line_boundary(start).0;
14127        let buffer_end = map.next_line_boundary(end).0;
14128        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14129    }
14130}
14131
14132impl<T: InvalidationRegion> InvalidationStack<T> {
14133    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14134    where
14135        S: Clone + ToOffset,
14136    {
14137        while let Some(region) = self.last() {
14138            let all_selections_inside_invalidation_ranges =
14139                if selections.len() == region.ranges().len() {
14140                    selections
14141                        .iter()
14142                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14143                        .all(|(selection, invalidation_range)| {
14144                            let head = selection.head().to_offset(buffer);
14145                            invalidation_range.start <= head && invalidation_range.end >= head
14146                        })
14147                } else {
14148                    false
14149                };
14150
14151            if all_selections_inside_invalidation_ranges {
14152                break;
14153            } else {
14154                self.pop();
14155            }
14156        }
14157    }
14158}
14159
14160impl<T> Default for InvalidationStack<T> {
14161    fn default() -> Self {
14162        Self(Default::default())
14163    }
14164}
14165
14166impl<T> Deref for InvalidationStack<T> {
14167    type Target = Vec<T>;
14168
14169    fn deref(&self) -> &Self::Target {
14170        &self.0
14171    }
14172}
14173
14174impl<T> DerefMut for InvalidationStack<T> {
14175    fn deref_mut(&mut self) -> &mut Self::Target {
14176        &mut self.0
14177    }
14178}
14179
14180impl InvalidationRegion for SnippetState {
14181    fn ranges(&self) -> &[Range<Anchor>] {
14182        &self.ranges[self.active_index]
14183    }
14184}
14185
14186pub fn diagnostic_block_renderer(
14187    diagnostic: Diagnostic,
14188    max_message_rows: Option<u8>,
14189    allow_closing: bool,
14190    _is_valid: bool,
14191) -> RenderBlock {
14192    let (text_without_backticks, code_ranges) =
14193        highlight_diagnostic_message(&diagnostic, max_message_rows);
14194
14195    Arc::new(move |cx: &mut BlockContext| {
14196        let group_id: SharedString = cx.block_id.to_string().into();
14197
14198        let mut text_style = cx.text_style().clone();
14199        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14200        let theme_settings = ThemeSettings::get_global(cx);
14201        text_style.font_family = theme_settings.buffer_font.family.clone();
14202        text_style.font_style = theme_settings.buffer_font.style;
14203        text_style.font_features = theme_settings.buffer_font.features.clone();
14204        text_style.font_weight = theme_settings.buffer_font.weight;
14205
14206        let multi_line_diagnostic = diagnostic.message.contains('\n');
14207
14208        let buttons = |diagnostic: &Diagnostic| {
14209            if multi_line_diagnostic {
14210                v_flex()
14211            } else {
14212                h_flex()
14213            }
14214            .when(allow_closing, |div| {
14215                div.children(diagnostic.is_primary.then(|| {
14216                    IconButton::new("close-block", IconName::XCircle)
14217                        .icon_color(Color::Muted)
14218                        .size(ButtonSize::Compact)
14219                        .style(ButtonStyle::Transparent)
14220                        .visible_on_hover(group_id.clone())
14221                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14222                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14223                }))
14224            })
14225            .child(
14226                IconButton::new("copy-block", IconName::Copy)
14227                    .icon_color(Color::Muted)
14228                    .size(ButtonSize::Compact)
14229                    .style(ButtonStyle::Transparent)
14230                    .visible_on_hover(group_id.clone())
14231                    .on_click({
14232                        let message = diagnostic.message.clone();
14233                        move |_click, cx| {
14234                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14235                        }
14236                    })
14237                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14238            )
14239        };
14240
14241        let icon_size = buttons(&diagnostic)
14242            .into_any_element()
14243            .layout_as_root(AvailableSpace::min_size(), cx);
14244
14245        h_flex()
14246            .id(cx.block_id)
14247            .group(group_id.clone())
14248            .relative()
14249            .size_full()
14250            .block_mouse_down()
14251            .pl(cx.gutter_dimensions.width)
14252            .w(cx.max_width - cx.gutter_dimensions.full_width())
14253            .child(
14254                div()
14255                    .flex()
14256                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14257                    .flex_shrink(),
14258            )
14259            .child(buttons(&diagnostic))
14260            .child(div().flex().flex_shrink_0().child(
14261                StyledText::new(text_without_backticks.clone()).with_highlights(
14262                    &text_style,
14263                    code_ranges.iter().map(|range| {
14264                        (
14265                            range.clone(),
14266                            HighlightStyle {
14267                                font_weight: Some(FontWeight::BOLD),
14268                                ..Default::default()
14269                            },
14270                        )
14271                    }),
14272                ),
14273            ))
14274            .into_any_element()
14275    })
14276}
14277
14278pub fn highlight_diagnostic_message(
14279    diagnostic: &Diagnostic,
14280    mut max_message_rows: Option<u8>,
14281) -> (SharedString, Vec<Range<usize>>) {
14282    let mut text_without_backticks = String::new();
14283    let mut code_ranges = Vec::new();
14284
14285    if let Some(source) = &diagnostic.source {
14286        text_without_backticks.push_str(source);
14287        code_ranges.push(0..source.len());
14288        text_without_backticks.push_str(": ");
14289    }
14290
14291    let mut prev_offset = 0;
14292    let mut in_code_block = false;
14293    let has_row_limit = max_message_rows.is_some();
14294    let mut newline_indices = diagnostic
14295        .message
14296        .match_indices('\n')
14297        .filter(|_| has_row_limit)
14298        .map(|(ix, _)| ix)
14299        .fuse()
14300        .peekable();
14301
14302    for (quote_ix, _) in diagnostic
14303        .message
14304        .match_indices('`')
14305        .chain([(diagnostic.message.len(), "")])
14306    {
14307        let mut first_newline_ix = None;
14308        let mut last_newline_ix = None;
14309        while let Some(newline_ix) = newline_indices.peek() {
14310            if *newline_ix < quote_ix {
14311                if first_newline_ix.is_none() {
14312                    first_newline_ix = Some(*newline_ix);
14313                }
14314                last_newline_ix = Some(*newline_ix);
14315
14316                if let Some(rows_left) = &mut max_message_rows {
14317                    if *rows_left == 0 {
14318                        break;
14319                    } else {
14320                        *rows_left -= 1;
14321                    }
14322                }
14323                let _ = newline_indices.next();
14324            } else {
14325                break;
14326            }
14327        }
14328        let prev_len = text_without_backticks.len();
14329        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14330        text_without_backticks.push_str(new_text);
14331        if in_code_block {
14332            code_ranges.push(prev_len..text_without_backticks.len());
14333        }
14334        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14335        in_code_block = !in_code_block;
14336        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14337            text_without_backticks.push_str("...");
14338            break;
14339        }
14340    }
14341
14342    (text_without_backticks.into(), code_ranges)
14343}
14344
14345fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14346    match severity {
14347        DiagnosticSeverity::ERROR => colors.error,
14348        DiagnosticSeverity::WARNING => colors.warning,
14349        DiagnosticSeverity::INFORMATION => colors.info,
14350        DiagnosticSeverity::HINT => colors.info,
14351        _ => colors.ignored,
14352    }
14353}
14354
14355pub fn styled_runs_for_code_label<'a>(
14356    label: &'a CodeLabel,
14357    syntax_theme: &'a theme::SyntaxTheme,
14358) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14359    let fade_out = HighlightStyle {
14360        fade_out: Some(0.35),
14361        ..Default::default()
14362    };
14363
14364    let mut prev_end = label.filter_range.end;
14365    label
14366        .runs
14367        .iter()
14368        .enumerate()
14369        .flat_map(move |(ix, (range, highlight_id))| {
14370            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14371                style
14372            } else {
14373                return Default::default();
14374            };
14375            let mut muted_style = style;
14376            muted_style.highlight(fade_out);
14377
14378            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14379            if range.start >= label.filter_range.end {
14380                if range.start > prev_end {
14381                    runs.push((prev_end..range.start, fade_out));
14382                }
14383                runs.push((range.clone(), muted_style));
14384            } else if range.end <= label.filter_range.end {
14385                runs.push((range.clone(), style));
14386            } else {
14387                runs.push((range.start..label.filter_range.end, style));
14388                runs.push((label.filter_range.end..range.end, muted_style));
14389            }
14390            prev_end = cmp::max(prev_end, range.end);
14391
14392            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14393                runs.push((prev_end..label.text.len(), fade_out));
14394            }
14395
14396            runs
14397        })
14398}
14399
14400pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14401    let mut prev_index = 0;
14402    let mut prev_codepoint: Option<char> = None;
14403    text.char_indices()
14404        .chain([(text.len(), '\0')])
14405        .filter_map(move |(index, codepoint)| {
14406            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14407            let is_boundary = index == text.len()
14408                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14409                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14410            if is_boundary {
14411                let chunk = &text[prev_index..index];
14412                prev_index = index;
14413                Some(chunk)
14414            } else {
14415                None
14416            }
14417        })
14418}
14419
14420pub trait RangeToAnchorExt: Sized {
14421    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14422
14423    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14424        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14425        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14426    }
14427}
14428
14429impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14430    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14431        let start_offset = self.start.to_offset(snapshot);
14432        let end_offset = self.end.to_offset(snapshot);
14433        if start_offset == end_offset {
14434            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14435        } else {
14436            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14437        }
14438    }
14439}
14440
14441pub trait RowExt {
14442    fn as_f32(&self) -> f32;
14443
14444    fn next_row(&self) -> Self;
14445
14446    fn previous_row(&self) -> Self;
14447
14448    fn minus(&self, other: Self) -> u32;
14449}
14450
14451impl RowExt for DisplayRow {
14452    fn as_f32(&self) -> f32 {
14453        self.0 as f32
14454    }
14455
14456    fn next_row(&self) -> Self {
14457        Self(self.0 + 1)
14458    }
14459
14460    fn previous_row(&self) -> Self {
14461        Self(self.0.saturating_sub(1))
14462    }
14463
14464    fn minus(&self, other: Self) -> u32 {
14465        self.0 - other.0
14466    }
14467}
14468
14469impl RowExt for MultiBufferRow {
14470    fn as_f32(&self) -> f32 {
14471        self.0 as f32
14472    }
14473
14474    fn next_row(&self) -> Self {
14475        Self(self.0 + 1)
14476    }
14477
14478    fn previous_row(&self) -> Self {
14479        Self(self.0.saturating_sub(1))
14480    }
14481
14482    fn minus(&self, other: Self) -> u32 {
14483        self.0 - other.0
14484    }
14485}
14486
14487trait RowRangeExt {
14488    type Row;
14489
14490    fn len(&self) -> usize;
14491
14492    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14493}
14494
14495impl RowRangeExt for Range<MultiBufferRow> {
14496    type Row = MultiBufferRow;
14497
14498    fn len(&self) -> usize {
14499        (self.end.0 - self.start.0) as usize
14500    }
14501
14502    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14503        (self.start.0..self.end.0).map(MultiBufferRow)
14504    }
14505}
14506
14507impl RowRangeExt for Range<DisplayRow> {
14508    type Row = DisplayRow;
14509
14510    fn len(&self) -> usize {
14511        (self.end.0 - self.start.0) as usize
14512    }
14513
14514    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14515        (self.start.0..self.end.0).map(DisplayRow)
14516    }
14517}
14518
14519fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14520    if hunk.diff_base_byte_range.is_empty() {
14521        DiffHunkStatus::Added
14522    } else if hunk.row_range.is_empty() {
14523        DiffHunkStatus::Removed
14524    } else {
14525        DiffHunkStatus::Modified
14526    }
14527}
14528
14529/// If select range has more than one line, we
14530/// just point the cursor to range.start.
14531fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14532    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14533        range
14534    } else {
14535        range.start..range.start
14536    }
14537}
14538
14539pub struct KillRing(ClipboardItem);
14540impl Global for KillRing {}
14541
14542const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);