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