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, OpenLspBufferHandle},
  133    project_settings::{GitGutterSetting, ProjectSettings},
  134    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  135    LspStore, 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
  194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  196
  197pub fn render_parsed_markdown(
  198    element_id: impl Into<ElementId>,
  199    parsed: &language::ParsedMarkdown,
  200    editor_style: &EditorStyle,
  201    workspace: Option<WeakView<Workspace>>,
  202    cx: &mut WindowContext,
  203) -> InteractiveText {
  204    let code_span_background_color = cx
  205        .theme()
  206        .colors()
  207        .editor_document_highlight_read_background;
  208
  209    let highlights = gpui::combine_highlights(
  210        parsed.highlights.iter().filter_map(|(range, highlight)| {
  211            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  212            Some((range.clone(), highlight))
  213        }),
  214        parsed
  215            .regions
  216            .iter()
  217            .zip(&parsed.region_ranges)
  218            .filter_map(|(region, range)| {
  219                if region.code {
  220                    Some((
  221                        range.clone(),
  222                        HighlightStyle {
  223                            background_color: Some(code_span_background_color),
  224                            ..Default::default()
  225                        },
  226                    ))
  227                } else {
  228                    None
  229                }
  230            }),
  231    );
  232
  233    let mut links = Vec::new();
  234    let mut link_ranges = Vec::new();
  235    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  236        if let Some(link) = region.link.clone() {
  237            links.push(link);
  238            link_ranges.push(range.clone());
  239        }
  240    }
  241
  242    InteractiveText::new(
  243        element_id,
  244        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  245    )
  246    .on_click(link_ranges, move |clicked_range_ix, cx| {
  247        match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace.open_abs_path(path.clone(), false, cx).detach();
  253                    });
  254                }
  255            }
  256        }
  257    })
  258}
  259
  260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  261pub(crate) enum InlayId {
  262    Suggestion(usize),
  263    Hint(usize),
  264}
  265
  266impl InlayId {
  267    fn id(&self) -> usize {
  268        match self {
  269            Self::Suggestion(id) => *id,
  270            Self::Hint(id) => *id,
  271        }
  272    }
  273}
  274
  275enum DiffRowHighlight {}
  276enum DocumentHighlightRead {}
  277enum DocumentHighlightWrite {}
  278enum InputComposition {}
  279
  280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  281pub enum Navigated {
  282    Yes,
  283    No,
  284}
  285
  286impl Navigated {
  287    pub fn from_bool(yes: bool) -> Navigated {
  288        if yes {
  289            Navigated::Yes
  290        } else {
  291            Navigated::No
  292        }
  293    }
  294}
  295
  296pub fn init_settings(cx: &mut AppContext) {
  297    EditorSettings::register(cx);
  298}
  299
  300pub fn init(cx: &mut AppContext) {
  301    init_settings(cx);
  302
  303    workspace::register_project_item::<Editor>(cx);
  304    workspace::FollowableViewRegistry::register::<Editor>(cx);
  305    workspace::register_serializable_item::<Editor>(cx);
  306
  307    cx.observe_new_views(
  308        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  309            workspace.register_action(Editor::new_file);
  310            workspace.register_action(Editor::new_file_vertical);
  311            workspace.register_action(Editor::new_file_horizontal);
  312        },
  313    )
  314    .detach();
  315
  316    cx.on_action(move |_: &workspace::NewFile, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  329                Editor::new_file(workspace, &Default::default(), cx)
  330            })
  331            .detach();
  332        }
  333    });
  334    git::project_diff::init(cx);
  335}
  336
  337pub struct SearchWithinRange;
  338
  339trait InvalidationRegion {
  340    fn ranges(&self) -> &[Range<Anchor>];
  341}
  342
  343#[derive(Clone, Debug, PartialEq)]
  344pub enum SelectPhase {
  345    Begin {
  346        position: DisplayPoint,
  347        add: bool,
  348        click_count: usize,
  349    },
  350    BeginColumnar {
  351        position: DisplayPoint,
  352        reset: bool,
  353        goal_column: u32,
  354    },
  355    Extend {
  356        position: DisplayPoint,
  357        click_count: usize,
  358    },
  359    Update {
  360        position: DisplayPoint,
  361        goal_column: u32,
  362        scroll_delta: gpui::Point<f32>,
  363    },
  364    End,
  365}
  366
  367#[derive(Clone, Debug)]
  368pub enum SelectMode {
  369    Character,
  370    Word(Range<Anchor>),
  371    Line(Range<Anchor>),
  372    All,
  373}
  374
  375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  376pub enum EditorMode {
  377    SingleLine { auto_width: bool },
  378    AutoHeight { max_lines: usize },
  379    Full,
  380}
  381
  382#[derive(Copy, Clone, Debug)]
  383pub enum SoftWrap {
  384    /// Prefer not to wrap at all.
  385    ///
  386    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  387    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  388    GitDiff,
  389    /// Prefer a single line generally, unless an overly long line is encountered.
  390    None,
  391    /// Soft wrap lines that exceed the editor width.
  392    EditorWidth,
  393    /// Soft wrap lines at the preferred line length.
  394    Column(u32),
  395    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  396    Bounded(u32),
  397}
  398
  399#[derive(Clone)]
  400pub struct EditorStyle {
  401    pub background: Hsla,
  402    pub local_player: PlayerColor,
  403    pub text: TextStyle,
  404    pub scrollbar_width: Pixels,
  405    pub syntax: Arc<SyntaxTheme>,
  406    pub status: StatusColors,
  407    pub inlay_hints_style: HighlightStyle,
  408    pub suggestions_style: HighlightStyle,
  409    pub unnecessary_code_fade: f32,
  410}
  411
  412impl Default for EditorStyle {
  413    fn default() -> Self {
  414        Self {
  415            background: Hsla::default(),
  416            local_player: PlayerColor::default(),
  417            text: TextStyle::default(),
  418            scrollbar_width: Pixels::default(),
  419            syntax: Default::default(),
  420            // HACK: Status colors don't have a real default.
  421            // We should look into removing the status colors from the editor
  422            // style and retrieve them directly from the theme.
  423            status: StatusColors::dark(),
  424            inlay_hints_style: HighlightStyle::default(),
  425            suggestions_style: HighlightStyle::default(),
  426            unnecessary_code_fade: Default::default(),
  427        }
  428    }
  429}
  430
  431pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  432    let show_background = language_settings::language_settings(None, None, cx)
  433        .inlay_hints
  434        .show_background;
  435
  436    HighlightStyle {
  437        color: Some(cx.theme().status().hint),
  438        background_color: show_background.then(|| cx.theme().status().hint_background),
  439        ..HighlightStyle::default()
  440    }
  441}
  442
  443type CompletionId = usize;
  444
  445enum InlineCompletion {
  446    Edit(Vec<(Range<Anchor>, String)>),
  447    Move(Anchor),
  448}
  449
  450struct InlineCompletionState {
  451    inlay_ids: Vec<InlayId>,
  452    completion: InlineCompletion,
  453    invalidation_range: Range<Anchor>,
  454}
  455
  456enum InlineCompletionHighlight {}
  457
  458#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  459struct EditorActionId(usize);
  460
  461impl EditorActionId {
  462    pub fn post_inc(&mut self) -> Self {
  463        let answer = self.0;
  464
  465        *self = Self(answer + 1);
  466
  467        Self(answer)
  468    }
  469}
  470
  471// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  472// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  473
  474type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  475type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  476
  477#[derive(Default)]
  478struct ScrollbarMarkerState {
  479    scrollbar_size: Size<Pixels>,
  480    dirty: bool,
  481    markers: Arc<[PaintQuad]>,
  482    pending_refresh: Option<Task<Result<()>>>,
  483}
  484
  485impl ScrollbarMarkerState {
  486    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  487        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  488    }
  489}
  490
  491#[derive(Clone, Debug)]
  492struct RunnableTasks {
  493    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  494    offset: MultiBufferOffset,
  495    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  496    column: u32,
  497    // Values of all named captures, including those starting with '_'
  498    extra_variables: HashMap<String, String>,
  499    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  500    context_range: Range<BufferOffset>,
  501}
  502
  503impl RunnableTasks {
  504    fn resolve<'a>(
  505        &'a self,
  506        cx: &'a task::TaskContext,
  507    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  508        self.templates.iter().filter_map(|(kind, template)| {
  509            template
  510                .resolve_task(&kind.to_id_base(), cx)
  511                .map(|task| (kind.clone(), task))
  512        })
  513    }
  514}
  515
  516#[derive(Clone)]
  517struct ResolvedTasks {
  518    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  519    position: Anchor,
  520}
  521#[derive(Copy, Clone, Debug)]
  522struct MultiBufferOffset(usize);
  523#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  524struct BufferOffset(usize);
  525
  526// Addons allow storing per-editor state in other crates (e.g. Vim)
  527pub trait Addon: 'static {
  528    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  529
  530    fn to_any(&self) -> &dyn std::any::Any;
  531}
  532
  533#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  534pub enum IsVimMode {
  535    Yes,
  536    No,
  537}
  538
  539/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  540///
  541/// See the [module level documentation](self) for more information.
  542pub struct Editor {
  543    focus_handle: FocusHandle,
  544    last_focused_descendant: Option<WeakFocusHandle>,
  545    /// The text buffer being edited
  546    buffer: Model<MultiBuffer>,
  547    /// Map of how text in the buffer should be displayed.
  548    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  549    pub display_map: Model<DisplayMap>,
  550    pub selections: SelectionsCollection,
  551    pub scroll_manager: ScrollManager,
  552    /// When inline assist editors are linked, they all render cursors because
  553    /// typing enters text into each of them, even the ones that aren't focused.
  554    pub(crate) show_cursor_when_unfocused: bool,
  555    columnar_selection_tail: Option<Anchor>,
  556    add_selections_state: Option<AddSelectionsState>,
  557    select_next_state: Option<SelectNextState>,
  558    select_prev_state: Option<SelectNextState>,
  559    selection_history: SelectionHistory,
  560    autoclose_regions: Vec<AutocloseRegion>,
  561    snippet_stack: InvalidationStack<SnippetState>,
  562    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  563    ime_transaction: Option<TransactionId>,
  564    active_diagnostics: Option<ActiveDiagnosticGroup>,
  565    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  566
  567    project: Option<Model<Project>>,
  568    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  569    completion_provider: Option<Box<dyn CompletionProvider>>,
  570    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  571    blink_manager: Model<BlinkManager>,
  572    show_cursor_names: bool,
  573    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  574    pub show_local_selections: bool,
  575    mode: EditorMode,
  576    show_breadcrumbs: bool,
  577    show_gutter: bool,
  578    show_line_numbers: Option<bool>,
  579    use_relative_line_numbers: Option<bool>,
  580    show_git_diff_gutter: Option<bool>,
  581    show_code_actions: Option<bool>,
  582    show_runnables: Option<bool>,
  583    show_wrap_guides: Option<bool>,
  584    show_indent_guides: Option<bool>,
  585    placeholder_text: Option<Arc<str>>,
  586    highlight_order: usize,
  587    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  588    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  589    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  590    scrollbar_marker_state: ScrollbarMarkerState,
  591    active_indent_guides_state: ActiveIndentGuidesState,
  592    nav_history: Option<ItemNavHistory>,
  593    context_menu: RwLock<Option<CodeContextMenu>>,
  594    mouse_context_menu: Option<MouseContextMenu>,
  595    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  596    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  597    signature_help_state: SignatureHelpState,
  598    auto_signature_help: Option<bool>,
  599    find_all_references_task_sources: Vec<Anchor>,
  600    next_completion_id: CompletionId,
  601    available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
  602    code_actions_task: Option<Task<Result<()>>>,
  603    document_highlights_task: Option<Task<()>>,
  604    linked_editing_range_task: Option<Task<Option<()>>>,
  605    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  606    pending_rename: Option<RenameState>,
  607    searchable: bool,
  608    cursor_shape: CursorShape,
  609    current_line_highlight: Option<CurrentLineHighlight>,
  610    collapse_matches: bool,
  611    autoindent_mode: Option<AutoindentMode>,
  612    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  613    input_enabled: bool,
  614    use_modal_editing: bool,
  615    read_only: bool,
  616    leader_peer_id: Option<PeerId>,
  617    remote_id: Option<ViewId>,
  618    hover_state: HoverState,
  619    gutter_hovered: bool,
  620    hovered_link_state: Option<HoveredLinkState>,
  621    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  622    code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
  623    active_inline_completion: Option<InlineCompletionState>,
  624    // enable_inline_completions is a switch that Vim can use to disable
  625    // inline completions based on its mode.
  626    enable_inline_completions: bool,
  627    show_inline_completions_override: Option<bool>,
  628    inlay_hint_cache: InlayHintCache,
  629    diff_map: DiffMap,
  630    next_inlay_id: usize,
  631    _subscriptions: Vec<Subscription>,
  632    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  633    gutter_dimensions: GutterDimensions,
  634    style: Option<EditorStyle>,
  635    text_style_refinement: Option<TextStyleRefinement>,
  636    next_editor_action_id: EditorActionId,
  637    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  638    use_autoclose: bool,
  639    use_auto_surround: bool,
  640    auto_replace_emoji_shortcode: bool,
  641    show_git_blame_gutter: bool,
  642    show_git_blame_inline: bool,
  643    show_git_blame_inline_delay_task: Option<Task<()>>,
  644    git_blame_inline_enabled: bool,
  645    serialize_dirty_buffers: bool,
  646    show_selection_menu: Option<bool>,
  647    blame: Option<Model<GitBlame>>,
  648    blame_subscription: Option<Subscription>,
  649    custom_context_menu: Option<
  650        Box<
  651            dyn 'static
  652                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  653        >,
  654    >,
  655    last_bounds: Option<Bounds<Pixels>>,
  656    expect_bounds_change: Option<Bounds<Pixels>>,
  657    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  658    tasks_update_task: Option<Task<()>>,
  659    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  660    breadcrumb_header: Option<String>,
  661    focused_block: Option<FocusedBlock>,
  662    next_scroll_position: NextScrollCursorCenterTopBottom,
  663    addons: HashMap<TypeId, Box<dyn Addon>>,
  664    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  665    _scroll_cursor_center_top_bottom_task: Task<()>,
  666}
  667
  668#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  669enum NextScrollCursorCenterTopBottom {
  670    #[default]
  671    Center,
  672    Top,
  673    Bottom,
  674}
  675
  676impl NextScrollCursorCenterTopBottom {
  677    fn next(&self) -> Self {
  678        match self {
  679            Self::Center => Self::Top,
  680            Self::Top => Self::Bottom,
  681            Self::Bottom => Self::Center,
  682        }
  683    }
  684}
  685
  686#[derive(Clone)]
  687pub struct EditorSnapshot {
  688    pub mode: EditorMode,
  689    show_gutter: bool,
  690    show_line_numbers: Option<bool>,
  691    show_git_diff_gutter: Option<bool>,
  692    show_code_actions: Option<bool>,
  693    show_runnables: Option<bool>,
  694    git_blame_gutter_max_author_length: Option<usize>,
  695    pub display_snapshot: DisplaySnapshot,
  696    pub placeholder_text: Option<Arc<str>>,
  697    diff_map: DiffMapSnapshot,
  698    is_focused: bool,
  699    scroll_anchor: ScrollAnchor,
  700    ongoing_scroll: OngoingScroll,
  701    current_line_highlight: CurrentLineHighlight,
  702    gutter_hovered: bool,
  703}
  704
  705const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  706
  707#[derive(Default, Debug, Clone, Copy)]
  708pub struct GutterDimensions {
  709    pub left_padding: Pixels,
  710    pub right_padding: Pixels,
  711    pub width: Pixels,
  712    pub margin: Pixels,
  713    pub git_blame_entries_width: Option<Pixels>,
  714}
  715
  716impl GutterDimensions {
  717    /// The full width of the space taken up by the gutter.
  718    pub fn full_width(&self) -> Pixels {
  719        self.margin + self.width
  720    }
  721
  722    /// The width of the space reserved for the fold indicators,
  723    /// use alongside 'justify_end' and `gutter_width` to
  724    /// right align content with the line numbers
  725    pub fn fold_area_width(&self) -> Pixels {
  726        self.margin + self.right_padding
  727    }
  728}
  729
  730#[derive(Debug)]
  731pub struct RemoteSelection {
  732    pub replica_id: ReplicaId,
  733    pub selection: Selection<Anchor>,
  734    pub cursor_shape: CursorShape,
  735    pub peer_id: PeerId,
  736    pub line_mode: bool,
  737    pub participant_index: Option<ParticipantIndex>,
  738    pub user_name: Option<SharedString>,
  739}
  740
  741#[derive(Clone, Debug)]
  742struct SelectionHistoryEntry {
  743    selections: Arc<[Selection<Anchor>]>,
  744    select_next_state: Option<SelectNextState>,
  745    select_prev_state: Option<SelectNextState>,
  746    add_selections_state: Option<AddSelectionsState>,
  747}
  748
  749enum SelectionHistoryMode {
  750    Normal,
  751    Undoing,
  752    Redoing,
  753}
  754
  755#[derive(Clone, PartialEq, Eq, Hash)]
  756struct HoveredCursor {
  757    replica_id: u16,
  758    selection_id: usize,
  759}
  760
  761impl Default for SelectionHistoryMode {
  762    fn default() -> Self {
  763        Self::Normal
  764    }
  765}
  766
  767#[derive(Default)]
  768struct SelectionHistory {
  769    #[allow(clippy::type_complexity)]
  770    selections_by_transaction:
  771        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  772    mode: SelectionHistoryMode,
  773    undo_stack: VecDeque<SelectionHistoryEntry>,
  774    redo_stack: VecDeque<SelectionHistoryEntry>,
  775}
  776
  777impl SelectionHistory {
  778    fn insert_transaction(
  779        &mut self,
  780        transaction_id: TransactionId,
  781        selections: Arc<[Selection<Anchor>]>,
  782    ) {
  783        self.selections_by_transaction
  784            .insert(transaction_id, (selections, None));
  785    }
  786
  787    #[allow(clippy::type_complexity)]
  788    fn transaction(
  789        &self,
  790        transaction_id: TransactionId,
  791    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  792        self.selections_by_transaction.get(&transaction_id)
  793    }
  794
  795    #[allow(clippy::type_complexity)]
  796    fn transaction_mut(
  797        &mut self,
  798        transaction_id: TransactionId,
  799    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  800        self.selections_by_transaction.get_mut(&transaction_id)
  801    }
  802
  803    fn push(&mut self, entry: SelectionHistoryEntry) {
  804        if !entry.selections.is_empty() {
  805            match self.mode {
  806                SelectionHistoryMode::Normal => {
  807                    self.push_undo(entry);
  808                    self.redo_stack.clear();
  809                }
  810                SelectionHistoryMode::Undoing => self.push_redo(entry),
  811                SelectionHistoryMode::Redoing => self.push_undo(entry),
  812            }
  813        }
  814    }
  815
  816    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  817        if self
  818            .undo_stack
  819            .back()
  820            .map_or(true, |e| e.selections != entry.selections)
  821        {
  822            self.undo_stack.push_back(entry);
  823            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  824                self.undo_stack.pop_front();
  825            }
  826        }
  827    }
  828
  829    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  830        if self
  831            .redo_stack
  832            .back()
  833            .map_or(true, |e| e.selections != entry.selections)
  834        {
  835            self.redo_stack.push_back(entry);
  836            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  837                self.redo_stack.pop_front();
  838            }
  839        }
  840    }
  841}
  842
  843struct RowHighlight {
  844    index: usize,
  845    range: Range<Anchor>,
  846    color: Hsla,
  847    should_autoscroll: bool,
  848}
  849
  850#[derive(Clone, Debug)]
  851struct AddSelectionsState {
  852    above: bool,
  853    stack: Vec<usize>,
  854}
  855
  856#[derive(Clone)]
  857struct SelectNextState {
  858    query: AhoCorasick,
  859    wordwise: bool,
  860    done: bool,
  861}
  862
  863impl std::fmt::Debug for SelectNextState {
  864    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  865        f.debug_struct(std::any::type_name::<Self>())
  866            .field("wordwise", &self.wordwise)
  867            .field("done", &self.done)
  868            .finish()
  869    }
  870}
  871
  872#[derive(Debug)]
  873struct AutocloseRegion {
  874    selection_id: usize,
  875    range: Range<Anchor>,
  876    pair: BracketPair,
  877}
  878
  879#[derive(Debug)]
  880struct SnippetState {
  881    ranges: Vec<Vec<Range<Anchor>>>,
  882    active_index: usize,
  883    choices: Vec<Option<Vec<String>>>,
  884}
  885
  886#[doc(hidden)]
  887pub struct RenameState {
  888    pub range: Range<Anchor>,
  889    pub old_name: Arc<str>,
  890    pub editor: View<Editor>,
  891    block_id: CustomBlockId,
  892}
  893
  894struct InvalidationStack<T>(Vec<T>);
  895
  896struct RegisteredInlineCompletionProvider {
  897    provider: Arc<dyn InlineCompletionProviderHandle>,
  898    _subscription: Subscription,
  899}
  900
  901#[derive(Debug)]
  902struct ActiveDiagnosticGroup {
  903    primary_range: Range<Anchor>,
  904    primary_message: String,
  905    group_id: usize,
  906    blocks: HashMap<CustomBlockId, Diagnostic>,
  907    is_valid: bool,
  908}
  909
  910#[derive(Serialize, Deserialize, Clone, Debug)]
  911pub struct ClipboardSelection {
  912    pub len: usize,
  913    pub is_entire_line: bool,
  914    pub first_line_indent: u32,
  915}
  916
  917#[derive(Debug)]
  918pub(crate) struct NavigationData {
  919    cursor_anchor: Anchor,
  920    cursor_position: Point,
  921    scroll_anchor: ScrollAnchor,
  922    scroll_top_row: u32,
  923}
  924
  925#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  926pub enum GotoDefinitionKind {
  927    Symbol,
  928    Declaration,
  929    Type,
  930    Implementation,
  931}
  932
  933#[derive(Debug, Clone)]
  934enum InlayHintRefreshReason {
  935    Toggle(bool),
  936    SettingsChange(InlayHintSettings),
  937    NewLinesShown,
  938    BufferEdited(HashSet<Arc<Language>>),
  939    RefreshRequested,
  940    ExcerptsRemoved(Vec<ExcerptId>),
  941}
  942
  943impl InlayHintRefreshReason {
  944    fn description(&self) -> &'static str {
  945        match self {
  946            Self::Toggle(_) => "toggle",
  947            Self::SettingsChange(_) => "settings change",
  948            Self::NewLinesShown => "new lines shown",
  949            Self::BufferEdited(_) => "buffer edited",
  950            Self::RefreshRequested => "refresh requested",
  951            Self::ExcerptsRemoved(_) => "excerpts removed",
  952        }
  953    }
  954}
  955
  956pub(crate) struct FocusedBlock {
  957    id: BlockId,
  958    focus_handle: WeakFocusHandle,
  959}
  960
  961#[derive(Clone)]
  962struct JumpData {
  963    excerpt_id: ExcerptId,
  964    position: Point,
  965    anchor: text::Anchor,
  966    path: Option<project::ProjectPath>,
  967    line_offset_from_top: u32,
  968}
  969
  970impl Editor {
  971    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
  972        let buffer = cx.new_model(|cx| Buffer::local("", cx));
  973        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
  974        Self::new(
  975            EditorMode::SingleLine { auto_width: false },
  976            buffer,
  977            None,
  978            false,
  979            cx,
  980        )
  981    }
  982
  983    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
  984        let buffer = cx.new_model(|cx| Buffer::local("", cx));
  985        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
  986        Self::new(EditorMode::Full, buffer, None, false, cx)
  987    }
  988
  989    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
  990        let buffer = cx.new_model(|cx| Buffer::local("", cx));
  991        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
  992        Self::new(
  993            EditorMode::SingleLine { auto_width: true },
  994            buffer,
  995            None,
  996            false,
  997            cx,
  998        )
  999    }
 1000
 1001    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1002        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1003        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1004        Self::new(
 1005            EditorMode::AutoHeight { max_lines },
 1006            buffer,
 1007            None,
 1008            false,
 1009            cx,
 1010        )
 1011    }
 1012
 1013    pub fn for_buffer(
 1014        buffer: Model<Buffer>,
 1015        project: Option<Model<Project>>,
 1016        cx: &mut ViewContext<Self>,
 1017    ) -> Self {
 1018        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1019        Self::new(EditorMode::Full, buffer, project, false, cx)
 1020    }
 1021
 1022    pub fn for_multibuffer(
 1023        buffer: Model<MultiBuffer>,
 1024        project: Option<Model<Project>>,
 1025        show_excerpt_controls: bool,
 1026        cx: &mut ViewContext<Self>,
 1027    ) -> Self {
 1028        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1029    }
 1030
 1031    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1032        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1033        let mut clone = Self::new(
 1034            self.mode,
 1035            self.buffer.clone(),
 1036            self.project.clone(),
 1037            show_excerpt_controls,
 1038            cx,
 1039        );
 1040        self.display_map.update(cx, |display_map, cx| {
 1041            let snapshot = display_map.snapshot(cx);
 1042            clone.display_map.update(cx, |display_map, cx| {
 1043                display_map.set_state(&snapshot, cx);
 1044            });
 1045        });
 1046        clone.selections.clone_state(&self.selections);
 1047        clone.scroll_manager.clone_state(&self.scroll_manager);
 1048        clone.searchable = self.searchable;
 1049        clone
 1050    }
 1051
 1052    pub fn new(
 1053        mode: EditorMode,
 1054        buffer: Model<MultiBuffer>,
 1055        project: Option<Model<Project>>,
 1056        show_excerpt_controls: bool,
 1057        cx: &mut ViewContext<Self>,
 1058    ) -> Self {
 1059        let style = cx.text_style();
 1060        let font_size = style.font_size.to_pixels(cx.rem_size());
 1061        let editor = cx.view().downgrade();
 1062        let fold_placeholder = FoldPlaceholder {
 1063            constrain_width: true,
 1064            render: Arc::new(move |fold_id, fold_range, cx| {
 1065                let editor = editor.clone();
 1066                div()
 1067                    .id(fold_id)
 1068                    .bg(cx.theme().colors().ghost_element_background)
 1069                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1070                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1071                    .rounded_sm()
 1072                    .size_full()
 1073                    .cursor_pointer()
 1074                    .child("")
 1075                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1076                    .on_click(move |_, cx| {
 1077                        editor
 1078                            .update(cx, |editor, cx| {
 1079                                editor.unfold_ranges(
 1080                                    &[fold_range.start..fold_range.end],
 1081                                    true,
 1082                                    false,
 1083                                    cx,
 1084                                );
 1085                                cx.stop_propagation();
 1086                            })
 1087                            .ok();
 1088                    })
 1089                    .into_any()
 1090            }),
 1091            merge_adjacent: true,
 1092            ..Default::default()
 1093        };
 1094        let display_map = cx.new_model(|cx| {
 1095            DisplayMap::new(
 1096                buffer.clone(),
 1097                style.font(),
 1098                font_size,
 1099                None,
 1100                show_excerpt_controls,
 1101                FILE_HEADER_HEIGHT,
 1102                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1103                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1104                fold_placeholder,
 1105                cx,
 1106            )
 1107        });
 1108
 1109        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1110
 1111        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1112
 1113        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1114            .then(|| language_settings::SoftWrap::None);
 1115
 1116        let mut project_subscriptions = Vec::new();
 1117        if mode == EditorMode::Full {
 1118            if let Some(project) = project.as_ref() {
 1119                if buffer.read(cx).is_singleton() {
 1120                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1121                        cx.emit(EditorEvent::TitleChanged);
 1122                    }));
 1123                }
 1124                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1125                    if let project::Event::RefreshInlayHints = event {
 1126                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1127                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1128                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1129                            let focus_handle = editor.focus_handle(cx);
 1130                            if focus_handle.is_focused(cx) {
 1131                                let snapshot = buffer.read(cx).snapshot();
 1132                                for (range, snippet) in snippet_edits {
 1133                                    let editor_range =
 1134                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1135                                    editor
 1136                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1137                                        .ok();
 1138                                }
 1139                            }
 1140                        }
 1141                    }
 1142                }));
 1143                if let Some(task_inventory) = project
 1144                    .read(cx)
 1145                    .task_store()
 1146                    .read(cx)
 1147                    .task_inventory()
 1148                    .cloned()
 1149                {
 1150                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1151                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1152                    }));
 1153                }
 1154            }
 1155        }
 1156
 1157        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1158
 1159        let inlay_hint_settings =
 1160            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1161        let focus_handle = cx.focus_handle();
 1162        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1163        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1164            .detach();
 1165        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1166            .detach();
 1167        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1168
 1169        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1170            Some(false)
 1171        } else {
 1172            None
 1173        };
 1174
 1175        let mut code_action_providers = Vec::new();
 1176        if let Some(project) = project.clone() {
 1177            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1178            code_action_providers.push(Arc::new(project) as Arc<_>);
 1179        }
 1180
 1181        let mut this = Self {
 1182            focus_handle,
 1183            show_cursor_when_unfocused: false,
 1184            last_focused_descendant: None,
 1185            buffer: buffer.clone(),
 1186            display_map: display_map.clone(),
 1187            selections,
 1188            scroll_manager: ScrollManager::new(cx),
 1189            columnar_selection_tail: None,
 1190            add_selections_state: None,
 1191            select_next_state: None,
 1192            select_prev_state: None,
 1193            selection_history: Default::default(),
 1194            autoclose_regions: Default::default(),
 1195            snippet_stack: Default::default(),
 1196            select_larger_syntax_node_stack: Vec::new(),
 1197            ime_transaction: Default::default(),
 1198            active_diagnostics: None,
 1199            soft_wrap_mode_override,
 1200            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1201            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1202            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1203            project,
 1204            blink_manager: blink_manager.clone(),
 1205            show_local_selections: true,
 1206            mode,
 1207            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1208            show_gutter: mode == EditorMode::Full,
 1209            show_line_numbers: None,
 1210            use_relative_line_numbers: None,
 1211            show_git_diff_gutter: None,
 1212            show_code_actions: None,
 1213            show_runnables: None,
 1214            show_wrap_guides: None,
 1215            show_indent_guides,
 1216            placeholder_text: None,
 1217            highlight_order: 0,
 1218            highlighted_rows: HashMap::default(),
 1219            background_highlights: Default::default(),
 1220            gutter_highlights: TreeMap::default(),
 1221            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1222            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1223            nav_history: None,
 1224            context_menu: RwLock::new(None),
 1225            mouse_context_menu: None,
 1226            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1227            completion_tasks: Default::default(),
 1228            signature_help_state: SignatureHelpState::default(),
 1229            auto_signature_help: None,
 1230            find_all_references_task_sources: Vec::new(),
 1231            next_completion_id: 0,
 1232            next_inlay_id: 0,
 1233            code_action_providers,
 1234            available_code_actions: Default::default(),
 1235            code_actions_task: Default::default(),
 1236            document_highlights_task: Default::default(),
 1237            linked_editing_range_task: Default::default(),
 1238            pending_rename: Default::default(),
 1239            searchable: true,
 1240            cursor_shape: EditorSettings::get_global(cx)
 1241                .cursor_shape
 1242                .unwrap_or_default(),
 1243            current_line_highlight: None,
 1244            autoindent_mode: Some(AutoindentMode::EachLine),
 1245            collapse_matches: false,
 1246            workspace: None,
 1247            input_enabled: true,
 1248            use_modal_editing: mode == EditorMode::Full,
 1249            read_only: false,
 1250            use_autoclose: true,
 1251            use_auto_surround: true,
 1252            auto_replace_emoji_shortcode: false,
 1253            leader_peer_id: None,
 1254            remote_id: None,
 1255            hover_state: Default::default(),
 1256            hovered_link_state: Default::default(),
 1257            inline_completion_provider: None,
 1258            active_inline_completion: None,
 1259            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1260            diff_map: DiffMap::default(),
 1261            gutter_hovered: false,
 1262            pixel_position_of_newest_cursor: None,
 1263            last_bounds: None,
 1264            expect_bounds_change: None,
 1265            gutter_dimensions: GutterDimensions::default(),
 1266            style: None,
 1267            show_cursor_names: false,
 1268            hovered_cursors: Default::default(),
 1269            next_editor_action_id: EditorActionId::default(),
 1270            editor_actions: Rc::default(),
 1271            show_inline_completions_override: None,
 1272            enable_inline_completions: true,
 1273            custom_context_menu: None,
 1274            show_git_blame_gutter: false,
 1275            show_git_blame_inline: false,
 1276            show_selection_menu: None,
 1277            show_git_blame_inline_delay_task: None,
 1278            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1279            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1280                .session
 1281                .restore_unsaved_buffers,
 1282            blame: None,
 1283            blame_subscription: None,
 1284            tasks: Default::default(),
 1285            _subscriptions: vec![
 1286                cx.observe(&buffer, Self::on_buffer_changed),
 1287                cx.subscribe(&buffer, Self::on_buffer_event),
 1288                cx.observe(&display_map, Self::on_display_map_changed),
 1289                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1290                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1291                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1292                cx.observe_window_activation(|editor, cx| {
 1293                    let active = cx.is_window_active();
 1294                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1295                        if active {
 1296                            blink_manager.enable(cx);
 1297                        } else {
 1298                            blink_manager.disable(cx);
 1299                        }
 1300                    });
 1301                }),
 1302            ],
 1303            tasks_update_task: None,
 1304            linked_edit_ranges: Default::default(),
 1305            previous_search_ranges: None,
 1306            breadcrumb_header: None,
 1307            focused_block: None,
 1308            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1309            addons: HashMap::default(),
 1310            registered_buffers: 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            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1330                if let Some(project) = this.project.as_ref() {
 1331                    let lsp_store = project.read(cx).lsp_store();
 1332                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1333                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1334                    });
 1335                    this.registered_buffers
 1336                        .insert(buffer.read(cx).remote_id(), handle);
 1337                }
 1338            }
 1339        }
 1340
 1341        this.report_editor_event("open", None, cx);
 1342        this
 1343    }
 1344
 1345    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1346        self.mouse_context_menu
 1347            .as_ref()
 1348            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1349    }
 1350
 1351    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1352        let mut key_context = KeyContext::new_with_defaults();
 1353        key_context.add("Editor");
 1354        let mode = match self.mode {
 1355            EditorMode::SingleLine { .. } => "single_line",
 1356            EditorMode::AutoHeight { .. } => "auto_height",
 1357            EditorMode::Full => "full",
 1358        };
 1359
 1360        if EditorSettings::jupyter_enabled(cx) {
 1361            key_context.add("jupyter");
 1362        }
 1363
 1364        key_context.set("mode", mode);
 1365        if self.pending_rename.is_some() {
 1366            key_context.add("renaming");
 1367        }
 1368        if self.context_menu_visible() {
 1369            match self.context_menu.read().as_ref() {
 1370                Some(CodeContextMenu::Completions(_)) => {
 1371                    key_context.add("menu");
 1372                    key_context.add("showing_completions")
 1373                }
 1374                Some(CodeContextMenu::CodeActions(_)) => {
 1375                    key_context.add("menu");
 1376                    key_context.add("showing_code_actions")
 1377                }
 1378                None => {}
 1379            }
 1380        }
 1381
 1382        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1383        if !self.focus_handle(cx).contains_focused(cx)
 1384            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1385        {
 1386            for addon in self.addons.values() {
 1387                addon.extend_key_context(&mut key_context, cx)
 1388            }
 1389        }
 1390
 1391        if let Some(extension) = self
 1392            .buffer
 1393            .read(cx)
 1394            .as_singleton()
 1395            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1396        {
 1397            key_context.set("extension", extension.to_string());
 1398        }
 1399
 1400        if self.has_active_inline_completion() {
 1401            key_context.add("copilot_suggestion");
 1402            key_context.add("inline_completion");
 1403        }
 1404
 1405        if !self
 1406            .selections
 1407            .disjoint
 1408            .iter()
 1409            .all(|selection| selection.start == selection.end)
 1410        {
 1411            key_context.add("selection");
 1412        }
 1413
 1414        key_context
 1415    }
 1416
 1417    pub fn new_file(
 1418        workspace: &mut Workspace,
 1419        _: &workspace::NewFile,
 1420        cx: &mut ViewContext<Workspace>,
 1421    ) {
 1422        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1423            "Failed to create buffer",
 1424            cx,
 1425            |e, _| match e.error_code() {
 1426                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1427                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1428                e.error_tag("required").unwrap_or("the latest version")
 1429            )),
 1430                _ => None,
 1431            },
 1432        );
 1433    }
 1434
 1435    pub fn new_in_workspace(
 1436        workspace: &mut Workspace,
 1437        cx: &mut ViewContext<Workspace>,
 1438    ) -> Task<Result<View<Editor>>> {
 1439        let project = workspace.project().clone();
 1440        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1441
 1442        cx.spawn(|workspace, mut cx| async move {
 1443            let buffer = create.await?;
 1444            workspace.update(&mut cx, |workspace, cx| {
 1445                let editor =
 1446                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1447                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1448                editor
 1449            })
 1450        })
 1451    }
 1452
 1453    fn new_file_vertical(
 1454        workspace: &mut Workspace,
 1455        _: &workspace::NewFileSplitVertical,
 1456        cx: &mut ViewContext<Workspace>,
 1457    ) {
 1458        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1459    }
 1460
 1461    fn new_file_horizontal(
 1462        workspace: &mut Workspace,
 1463        _: &workspace::NewFileSplitHorizontal,
 1464        cx: &mut ViewContext<Workspace>,
 1465    ) {
 1466        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1467    }
 1468
 1469    fn new_file_in_direction(
 1470        workspace: &mut Workspace,
 1471        direction: SplitDirection,
 1472        cx: &mut ViewContext<Workspace>,
 1473    ) {
 1474        let project = workspace.project().clone();
 1475        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1476
 1477        cx.spawn(|workspace, mut cx| async move {
 1478            let buffer = create.await?;
 1479            workspace.update(&mut cx, move |workspace, cx| {
 1480                workspace.split_item(
 1481                    direction,
 1482                    Box::new(
 1483                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1484                    ),
 1485                    cx,
 1486                )
 1487            })?;
 1488            anyhow::Ok(())
 1489        })
 1490        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1491            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1492                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1493                e.error_tag("required").unwrap_or("the latest version")
 1494            )),
 1495            _ => None,
 1496        });
 1497    }
 1498
 1499    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1500        self.leader_peer_id
 1501    }
 1502
 1503    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1504        &self.buffer
 1505    }
 1506
 1507    pub fn workspace(&self) -> Option<View<Workspace>> {
 1508        self.workspace.as_ref()?.0.upgrade()
 1509    }
 1510
 1511    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1512        self.buffer().read(cx).title(cx)
 1513    }
 1514
 1515    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1516        let git_blame_gutter_max_author_length = self
 1517            .render_git_blame_gutter(cx)
 1518            .then(|| {
 1519                if let Some(blame) = self.blame.as_ref() {
 1520                    let max_author_length =
 1521                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1522                    Some(max_author_length)
 1523                } else {
 1524                    None
 1525                }
 1526            })
 1527            .flatten();
 1528
 1529        EditorSnapshot {
 1530            mode: self.mode,
 1531            show_gutter: self.show_gutter,
 1532            show_line_numbers: self.show_line_numbers,
 1533            show_git_diff_gutter: self.show_git_diff_gutter,
 1534            show_code_actions: self.show_code_actions,
 1535            show_runnables: self.show_runnables,
 1536            git_blame_gutter_max_author_length,
 1537            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1538            scroll_anchor: self.scroll_manager.anchor(),
 1539            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1540            placeholder_text: self.placeholder_text.clone(),
 1541            diff_map: self.diff_map.snapshot(),
 1542            is_focused: self.focus_handle.is_focused(cx),
 1543            current_line_highlight: self
 1544                .current_line_highlight
 1545                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1546            gutter_hovered: self.gutter_hovered,
 1547        }
 1548    }
 1549
 1550    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1551        self.buffer.read(cx).language_at(point, cx)
 1552    }
 1553
 1554    pub fn file_at<T: ToOffset>(
 1555        &self,
 1556        point: T,
 1557        cx: &AppContext,
 1558    ) -> Option<Arc<dyn language::File>> {
 1559        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1560    }
 1561
 1562    pub fn active_excerpt(
 1563        &self,
 1564        cx: &AppContext,
 1565    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1566        self.buffer
 1567            .read(cx)
 1568            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1569    }
 1570
 1571    pub fn mode(&self) -> EditorMode {
 1572        self.mode
 1573    }
 1574
 1575    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1576        self.collaboration_hub.as_deref()
 1577    }
 1578
 1579    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1580        self.collaboration_hub = Some(hub);
 1581    }
 1582
 1583    pub fn set_custom_context_menu(
 1584        &mut self,
 1585        f: impl 'static
 1586            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1587    ) {
 1588        self.custom_context_menu = Some(Box::new(f))
 1589    }
 1590
 1591    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1592        self.completion_provider = provider;
 1593    }
 1594
 1595    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1596        self.semantics_provider.clone()
 1597    }
 1598
 1599    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1600        self.semantics_provider = provider;
 1601    }
 1602
 1603    pub fn set_inline_completion_provider<T>(
 1604        &mut self,
 1605        provider: Option<Model<T>>,
 1606        cx: &mut ViewContext<Self>,
 1607    ) where
 1608        T: InlineCompletionProvider,
 1609    {
 1610        self.inline_completion_provider =
 1611            provider.map(|provider| RegisteredInlineCompletionProvider {
 1612                _subscription: cx.observe(&provider, |this, _, cx| {
 1613                    if this.focus_handle.is_focused(cx) {
 1614                        this.update_visible_inline_completion(cx);
 1615                    }
 1616                }),
 1617                provider: Arc::new(provider),
 1618            });
 1619        self.refresh_inline_completion(false, false, cx);
 1620    }
 1621
 1622    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1623        self.placeholder_text.as_deref()
 1624    }
 1625
 1626    pub fn set_placeholder_text(
 1627        &mut self,
 1628        placeholder_text: impl Into<Arc<str>>,
 1629        cx: &mut ViewContext<Self>,
 1630    ) {
 1631        let placeholder_text = Some(placeholder_text.into());
 1632        if self.placeholder_text != placeholder_text {
 1633            self.placeholder_text = placeholder_text;
 1634            cx.notify();
 1635        }
 1636    }
 1637
 1638    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1639        self.cursor_shape = cursor_shape;
 1640
 1641        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1642        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1643
 1644        cx.notify();
 1645    }
 1646
 1647    pub fn set_current_line_highlight(
 1648        &mut self,
 1649        current_line_highlight: Option<CurrentLineHighlight>,
 1650    ) {
 1651        self.current_line_highlight = current_line_highlight;
 1652    }
 1653
 1654    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1655        self.collapse_matches = collapse_matches;
 1656    }
 1657
 1658    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1659        let buffers = self.buffer.read(cx).all_buffers();
 1660        let Some(lsp_store) = self.lsp_store(cx) else {
 1661            return;
 1662        };
 1663        lsp_store.update(cx, |lsp_store, cx| {
 1664            for buffer in buffers {
 1665                self.registered_buffers
 1666                    .entry(buffer.read(cx).remote_id())
 1667                    .or_insert_with(|| {
 1668                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1669                    });
 1670            }
 1671        })
 1672    }
 1673
 1674    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1675        if self.collapse_matches {
 1676            return range.start..range.start;
 1677        }
 1678        range.clone()
 1679    }
 1680
 1681    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1682        if self.display_map.read(cx).clip_at_line_ends != clip {
 1683            self.display_map
 1684                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1685        }
 1686    }
 1687
 1688    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1689        self.input_enabled = input_enabled;
 1690    }
 1691
 1692    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1693        self.enable_inline_completions = enabled;
 1694    }
 1695
 1696    pub fn set_autoindent(&mut self, autoindent: bool) {
 1697        if autoindent {
 1698            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1699        } else {
 1700            self.autoindent_mode = None;
 1701        }
 1702    }
 1703
 1704    pub fn read_only(&self, cx: &AppContext) -> bool {
 1705        self.read_only || self.buffer.read(cx).read_only()
 1706    }
 1707
 1708    pub fn set_read_only(&mut self, read_only: bool) {
 1709        self.read_only = read_only;
 1710    }
 1711
 1712    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1713        self.use_autoclose = autoclose;
 1714    }
 1715
 1716    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1717        self.use_auto_surround = auto_surround;
 1718    }
 1719
 1720    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1721        self.auto_replace_emoji_shortcode = auto_replace;
 1722    }
 1723
 1724    pub fn toggle_inline_completions(
 1725        &mut self,
 1726        _: &ToggleInlineCompletions,
 1727        cx: &mut ViewContext<Self>,
 1728    ) {
 1729        if self.show_inline_completions_override.is_some() {
 1730            self.set_show_inline_completions(None, cx);
 1731        } else {
 1732            let cursor = self.selections.newest_anchor().head();
 1733            if let Some((buffer, cursor_buffer_position)) =
 1734                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1735            {
 1736                let show_inline_completions =
 1737                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1738                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1739            }
 1740        }
 1741    }
 1742
 1743    pub fn set_show_inline_completions(
 1744        &mut self,
 1745        show_inline_completions: Option<bool>,
 1746        cx: &mut ViewContext<Self>,
 1747    ) {
 1748        self.show_inline_completions_override = show_inline_completions;
 1749        self.refresh_inline_completion(false, true, cx);
 1750    }
 1751
 1752    fn should_show_inline_completions(
 1753        &self,
 1754        buffer: &Model<Buffer>,
 1755        buffer_position: language::Anchor,
 1756        cx: &AppContext,
 1757    ) -> bool {
 1758        if !self.snippet_stack.is_empty() {
 1759            return false;
 1760        }
 1761
 1762        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1763            return false;
 1764        }
 1765
 1766        if let Some(provider) = self.inline_completion_provider() {
 1767            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1768                show_inline_completions
 1769            } else {
 1770                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1771            }
 1772        } else {
 1773            false
 1774        }
 1775    }
 1776
 1777    fn inline_completions_disabled_in_scope(
 1778        &self,
 1779        buffer: &Model<Buffer>,
 1780        buffer_position: language::Anchor,
 1781        cx: &AppContext,
 1782    ) -> bool {
 1783        let snapshot = buffer.read(cx).snapshot();
 1784        let settings = snapshot.settings_at(buffer_position, cx);
 1785
 1786        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1787            return false;
 1788        };
 1789
 1790        scope.override_name().map_or(false, |scope_name| {
 1791            settings
 1792                .inline_completions_disabled_in
 1793                .iter()
 1794                .any(|s| s == scope_name)
 1795        })
 1796    }
 1797
 1798    pub fn set_use_modal_editing(&mut self, to: bool) {
 1799        self.use_modal_editing = to;
 1800    }
 1801
 1802    pub fn use_modal_editing(&self) -> bool {
 1803        self.use_modal_editing
 1804    }
 1805
 1806    fn selections_did_change(
 1807        &mut self,
 1808        local: bool,
 1809        old_cursor_position: &Anchor,
 1810        show_completions: bool,
 1811        cx: &mut ViewContext<Self>,
 1812    ) {
 1813        cx.invalidate_character_coordinates();
 1814
 1815        // Copy selections to primary selection buffer
 1816        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1817        if local {
 1818            let selections = self.selections.all::<usize>(cx);
 1819            let buffer_handle = self.buffer.read(cx).read(cx);
 1820
 1821            let mut text = String::new();
 1822            for (index, selection) in selections.iter().enumerate() {
 1823                let text_for_selection = buffer_handle
 1824                    .text_for_range(selection.start..selection.end)
 1825                    .collect::<String>();
 1826
 1827                text.push_str(&text_for_selection);
 1828                if index != selections.len() - 1 {
 1829                    text.push('\n');
 1830                }
 1831            }
 1832
 1833            if !text.is_empty() {
 1834                cx.write_to_primary(ClipboardItem::new_string(text));
 1835            }
 1836        }
 1837
 1838        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1839            self.buffer.update(cx, |buffer, cx| {
 1840                buffer.set_active_selections(
 1841                    &self.selections.disjoint_anchors(),
 1842                    self.selections.line_mode,
 1843                    self.cursor_shape,
 1844                    cx,
 1845                )
 1846            });
 1847        }
 1848        let display_map = self
 1849            .display_map
 1850            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1851        let buffer = &display_map.buffer_snapshot;
 1852        self.add_selections_state = None;
 1853        self.select_next_state = None;
 1854        self.select_prev_state = None;
 1855        self.select_larger_syntax_node_stack.clear();
 1856        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1857        self.snippet_stack
 1858            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1859        self.take_rename(false, cx);
 1860
 1861        let new_cursor_position = self.selections.newest_anchor().head();
 1862
 1863        self.push_to_nav_history(
 1864            *old_cursor_position,
 1865            Some(new_cursor_position.to_point(buffer)),
 1866            cx,
 1867        );
 1868
 1869        if local {
 1870            let new_cursor_position = self.selections.newest_anchor().head();
 1871            let mut context_menu = self.context_menu.write();
 1872            let completion_menu = match context_menu.as_ref() {
 1873                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1874
 1875                _ => {
 1876                    *context_menu = None;
 1877                    None
 1878                }
 1879            };
 1880
 1881            if let Some(completion_menu) = completion_menu {
 1882                let cursor_position = new_cursor_position.to_offset(buffer);
 1883                let (word_range, kind) =
 1884                    buffer.surrounding_word(completion_menu.initial_position, true);
 1885                if kind == Some(CharKind::Word)
 1886                    && word_range.to_inclusive().contains(&cursor_position)
 1887                {
 1888                    let mut completion_menu = completion_menu.clone();
 1889                    drop(context_menu);
 1890
 1891                    let query = Self::completion_query(buffer, cursor_position);
 1892                    cx.spawn(move |this, mut cx| async move {
 1893                        completion_menu
 1894                            .filter(query.as_deref(), cx.background_executor().clone())
 1895                            .await;
 1896
 1897                        this.update(&mut cx, |this, cx| {
 1898                            let mut context_menu = this.context_menu.write();
 1899                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1900                            else {
 1901                                return;
 1902                            };
 1903
 1904                            if menu.id > completion_menu.id {
 1905                                return;
 1906                            }
 1907
 1908                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1909                            drop(context_menu);
 1910                            cx.notify();
 1911                        })
 1912                    })
 1913                    .detach();
 1914
 1915                    if show_completions {
 1916                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1917                    }
 1918                } else {
 1919                    drop(context_menu);
 1920                    self.hide_context_menu(cx);
 1921                }
 1922            } else {
 1923                drop(context_menu);
 1924            }
 1925
 1926            hide_hover(self, cx);
 1927
 1928            if old_cursor_position.to_display_point(&display_map).row()
 1929                != new_cursor_position.to_display_point(&display_map).row()
 1930            {
 1931                self.available_code_actions.take();
 1932            }
 1933            self.refresh_code_actions(cx);
 1934            self.refresh_document_highlights(cx);
 1935            refresh_matching_bracket_highlights(self, cx);
 1936            self.update_visible_inline_completion(cx);
 1937            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1938            if self.git_blame_inline_enabled {
 1939                self.start_inline_blame_timer(cx);
 1940            }
 1941        }
 1942
 1943        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1944        cx.emit(EditorEvent::SelectionsChanged { local });
 1945
 1946        if self.selections.disjoint_anchors().len() == 1 {
 1947            cx.emit(SearchEvent::ActiveMatchChanged)
 1948        }
 1949        cx.notify();
 1950    }
 1951
 1952    pub fn change_selections<R>(
 1953        &mut self,
 1954        autoscroll: Option<Autoscroll>,
 1955        cx: &mut ViewContext<Self>,
 1956        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1957    ) -> R {
 1958        self.change_selections_inner(autoscroll, true, cx, change)
 1959    }
 1960
 1961    pub fn change_selections_inner<R>(
 1962        &mut self,
 1963        autoscroll: Option<Autoscroll>,
 1964        request_completions: bool,
 1965        cx: &mut ViewContext<Self>,
 1966        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1967    ) -> R {
 1968        let old_cursor_position = self.selections.newest_anchor().head();
 1969        self.push_to_selection_history();
 1970
 1971        let (changed, result) = self.selections.change_with(cx, change);
 1972
 1973        if changed {
 1974            if let Some(autoscroll) = autoscroll {
 1975                self.request_autoscroll(autoscroll, cx);
 1976            }
 1977            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 1978
 1979            if self.should_open_signature_help_automatically(
 1980                &old_cursor_position,
 1981                self.signature_help_state.backspace_pressed(),
 1982                cx,
 1983            ) {
 1984                self.show_signature_help(&ShowSignatureHelp, cx);
 1985            }
 1986            self.signature_help_state.set_backspace_pressed(false);
 1987        }
 1988
 1989        result
 1990    }
 1991
 1992    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 1993    where
 1994        I: IntoIterator<Item = (Range<S>, T)>,
 1995        S: ToOffset,
 1996        T: Into<Arc<str>>,
 1997    {
 1998        if self.read_only(cx) {
 1999            return;
 2000        }
 2001
 2002        self.buffer
 2003            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2004    }
 2005
 2006    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2007    where
 2008        I: IntoIterator<Item = (Range<S>, T)>,
 2009        S: ToOffset,
 2010        T: Into<Arc<str>>,
 2011    {
 2012        if self.read_only(cx) {
 2013            return;
 2014        }
 2015
 2016        self.buffer.update(cx, |buffer, cx| {
 2017            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2018        });
 2019    }
 2020
 2021    pub fn edit_with_block_indent<I, S, T>(
 2022        &mut self,
 2023        edits: I,
 2024        original_indent_columns: Vec<u32>,
 2025        cx: &mut ViewContext<Self>,
 2026    ) where
 2027        I: IntoIterator<Item = (Range<S>, T)>,
 2028        S: ToOffset,
 2029        T: Into<Arc<str>>,
 2030    {
 2031        if self.read_only(cx) {
 2032            return;
 2033        }
 2034
 2035        self.buffer.update(cx, |buffer, cx| {
 2036            buffer.edit(
 2037                edits,
 2038                Some(AutoindentMode::Block {
 2039                    original_indent_columns,
 2040                }),
 2041                cx,
 2042            )
 2043        });
 2044    }
 2045
 2046    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2047        self.hide_context_menu(cx);
 2048
 2049        match phase {
 2050            SelectPhase::Begin {
 2051                position,
 2052                add,
 2053                click_count,
 2054            } => self.begin_selection(position, add, click_count, cx),
 2055            SelectPhase::BeginColumnar {
 2056                position,
 2057                goal_column,
 2058                reset,
 2059            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2060            SelectPhase::Extend {
 2061                position,
 2062                click_count,
 2063            } => self.extend_selection(position, click_count, cx),
 2064            SelectPhase::Update {
 2065                position,
 2066                goal_column,
 2067                scroll_delta,
 2068            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2069            SelectPhase::End => self.end_selection(cx),
 2070        }
 2071    }
 2072
 2073    fn extend_selection(
 2074        &mut self,
 2075        position: DisplayPoint,
 2076        click_count: usize,
 2077        cx: &mut ViewContext<Self>,
 2078    ) {
 2079        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2080        let tail = self.selections.newest::<usize>(cx).tail();
 2081        self.begin_selection(position, false, click_count, cx);
 2082
 2083        let position = position.to_offset(&display_map, Bias::Left);
 2084        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2085
 2086        let mut pending_selection = self
 2087            .selections
 2088            .pending_anchor()
 2089            .expect("extend_selection not called with pending selection");
 2090        if position >= tail {
 2091            pending_selection.start = tail_anchor;
 2092        } else {
 2093            pending_selection.end = tail_anchor;
 2094            pending_selection.reversed = true;
 2095        }
 2096
 2097        let mut pending_mode = self.selections.pending_mode().unwrap();
 2098        match &mut pending_mode {
 2099            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2100            _ => {}
 2101        }
 2102
 2103        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2104            s.set_pending(pending_selection, pending_mode)
 2105        });
 2106    }
 2107
 2108    fn begin_selection(
 2109        &mut self,
 2110        position: DisplayPoint,
 2111        add: bool,
 2112        click_count: usize,
 2113        cx: &mut ViewContext<Self>,
 2114    ) {
 2115        if !self.focus_handle.is_focused(cx) {
 2116            self.last_focused_descendant = None;
 2117            cx.focus(&self.focus_handle);
 2118        }
 2119
 2120        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2121        let buffer = &display_map.buffer_snapshot;
 2122        let newest_selection = self.selections.newest_anchor().clone();
 2123        let position = display_map.clip_point(position, Bias::Left);
 2124
 2125        let start;
 2126        let end;
 2127        let mode;
 2128        let mut auto_scroll;
 2129        match click_count {
 2130            1 => {
 2131                start = buffer.anchor_before(position.to_point(&display_map));
 2132                end = start;
 2133                mode = SelectMode::Character;
 2134                auto_scroll = true;
 2135            }
 2136            2 => {
 2137                let range = movement::surrounding_word(&display_map, position);
 2138                start = buffer.anchor_before(range.start.to_point(&display_map));
 2139                end = buffer.anchor_before(range.end.to_point(&display_map));
 2140                mode = SelectMode::Word(start..end);
 2141                auto_scroll = true;
 2142            }
 2143            3 => {
 2144                let position = display_map
 2145                    .clip_point(position, Bias::Left)
 2146                    .to_point(&display_map);
 2147                let line_start = display_map.prev_line_boundary(position).0;
 2148                let next_line_start = buffer.clip_point(
 2149                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2150                    Bias::Left,
 2151                );
 2152                start = buffer.anchor_before(line_start);
 2153                end = buffer.anchor_before(next_line_start);
 2154                mode = SelectMode::Line(start..end);
 2155                auto_scroll = true;
 2156            }
 2157            _ => {
 2158                start = buffer.anchor_before(0);
 2159                end = buffer.anchor_before(buffer.len());
 2160                mode = SelectMode::All;
 2161                auto_scroll = false;
 2162            }
 2163        }
 2164        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2165
 2166        let point_to_delete: Option<usize> = {
 2167            let selected_points: Vec<Selection<Point>> =
 2168                self.selections.disjoint_in_range(start..end, cx);
 2169
 2170            if !add || click_count > 1 {
 2171                None
 2172            } else if !selected_points.is_empty() {
 2173                Some(selected_points[0].id)
 2174            } else {
 2175                let clicked_point_already_selected =
 2176                    self.selections.disjoint.iter().find(|selection| {
 2177                        selection.start.to_point(buffer) == start.to_point(buffer)
 2178                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2179                    });
 2180
 2181                clicked_point_already_selected.map(|selection| selection.id)
 2182            }
 2183        };
 2184
 2185        let selections_count = self.selections.count();
 2186
 2187        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2188            if let Some(point_to_delete) = point_to_delete {
 2189                s.delete(point_to_delete);
 2190
 2191                if selections_count == 1 {
 2192                    s.set_pending_anchor_range(start..end, mode);
 2193                }
 2194            } else {
 2195                if !add {
 2196                    s.clear_disjoint();
 2197                } else if click_count > 1 {
 2198                    s.delete(newest_selection.id)
 2199                }
 2200
 2201                s.set_pending_anchor_range(start..end, mode);
 2202            }
 2203        });
 2204    }
 2205
 2206    fn begin_columnar_selection(
 2207        &mut self,
 2208        position: DisplayPoint,
 2209        goal_column: u32,
 2210        reset: bool,
 2211        cx: &mut ViewContext<Self>,
 2212    ) {
 2213        if !self.focus_handle.is_focused(cx) {
 2214            self.last_focused_descendant = None;
 2215            cx.focus(&self.focus_handle);
 2216        }
 2217
 2218        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2219
 2220        if reset {
 2221            let pointer_position = display_map
 2222                .buffer_snapshot
 2223                .anchor_before(position.to_point(&display_map));
 2224
 2225            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2226                s.clear_disjoint();
 2227                s.set_pending_anchor_range(
 2228                    pointer_position..pointer_position,
 2229                    SelectMode::Character,
 2230                );
 2231            });
 2232        }
 2233
 2234        let tail = self.selections.newest::<Point>(cx).tail();
 2235        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2236
 2237        if !reset {
 2238            self.select_columns(
 2239                tail.to_display_point(&display_map),
 2240                position,
 2241                goal_column,
 2242                &display_map,
 2243                cx,
 2244            );
 2245        }
 2246    }
 2247
 2248    fn update_selection(
 2249        &mut self,
 2250        position: DisplayPoint,
 2251        goal_column: u32,
 2252        scroll_delta: gpui::Point<f32>,
 2253        cx: &mut ViewContext<Self>,
 2254    ) {
 2255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2256
 2257        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2258            let tail = tail.to_display_point(&display_map);
 2259            self.select_columns(tail, position, goal_column, &display_map, cx);
 2260        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2261            let buffer = self.buffer.read(cx).snapshot(cx);
 2262            let head;
 2263            let tail;
 2264            let mode = self.selections.pending_mode().unwrap();
 2265            match &mode {
 2266                SelectMode::Character => {
 2267                    head = position.to_point(&display_map);
 2268                    tail = pending.tail().to_point(&buffer);
 2269                }
 2270                SelectMode::Word(original_range) => {
 2271                    let original_display_range = original_range.start.to_display_point(&display_map)
 2272                        ..original_range.end.to_display_point(&display_map);
 2273                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2274                        ..original_display_range.end.to_point(&display_map);
 2275                    if movement::is_inside_word(&display_map, position)
 2276                        || original_display_range.contains(&position)
 2277                    {
 2278                        let word_range = movement::surrounding_word(&display_map, position);
 2279                        if word_range.start < original_display_range.start {
 2280                            head = word_range.start.to_point(&display_map);
 2281                        } else {
 2282                            head = word_range.end.to_point(&display_map);
 2283                        }
 2284                    } else {
 2285                        head = position.to_point(&display_map);
 2286                    }
 2287
 2288                    if head <= original_buffer_range.start {
 2289                        tail = original_buffer_range.end;
 2290                    } else {
 2291                        tail = original_buffer_range.start;
 2292                    }
 2293                }
 2294                SelectMode::Line(original_range) => {
 2295                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2296
 2297                    let position = display_map
 2298                        .clip_point(position, Bias::Left)
 2299                        .to_point(&display_map);
 2300                    let line_start = display_map.prev_line_boundary(position).0;
 2301                    let next_line_start = buffer.clip_point(
 2302                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2303                        Bias::Left,
 2304                    );
 2305
 2306                    if line_start < original_range.start {
 2307                        head = line_start
 2308                    } else {
 2309                        head = next_line_start
 2310                    }
 2311
 2312                    if head <= original_range.start {
 2313                        tail = original_range.end;
 2314                    } else {
 2315                        tail = original_range.start;
 2316                    }
 2317                }
 2318                SelectMode::All => {
 2319                    return;
 2320                }
 2321            };
 2322
 2323            if head < tail {
 2324                pending.start = buffer.anchor_before(head);
 2325                pending.end = buffer.anchor_before(tail);
 2326                pending.reversed = true;
 2327            } else {
 2328                pending.start = buffer.anchor_before(tail);
 2329                pending.end = buffer.anchor_before(head);
 2330                pending.reversed = false;
 2331            }
 2332
 2333            self.change_selections(None, cx, |s| {
 2334                s.set_pending(pending, mode);
 2335            });
 2336        } else {
 2337            log::error!("update_selection dispatched with no pending selection");
 2338            return;
 2339        }
 2340
 2341        self.apply_scroll_delta(scroll_delta, cx);
 2342        cx.notify();
 2343    }
 2344
 2345    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2346        self.columnar_selection_tail.take();
 2347        if self.selections.pending_anchor().is_some() {
 2348            let selections = self.selections.all::<usize>(cx);
 2349            self.change_selections(None, cx, |s| {
 2350                s.select(selections);
 2351                s.clear_pending();
 2352            });
 2353        }
 2354    }
 2355
 2356    fn select_columns(
 2357        &mut self,
 2358        tail: DisplayPoint,
 2359        head: DisplayPoint,
 2360        goal_column: u32,
 2361        display_map: &DisplaySnapshot,
 2362        cx: &mut ViewContext<Self>,
 2363    ) {
 2364        let start_row = cmp::min(tail.row(), head.row());
 2365        let end_row = cmp::max(tail.row(), head.row());
 2366        let start_column = cmp::min(tail.column(), goal_column);
 2367        let end_column = cmp::max(tail.column(), goal_column);
 2368        let reversed = start_column < tail.column();
 2369
 2370        let selection_ranges = (start_row.0..=end_row.0)
 2371            .map(DisplayRow)
 2372            .filter_map(|row| {
 2373                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2374                    let start = display_map
 2375                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2376                        .to_point(display_map);
 2377                    let end = display_map
 2378                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2379                        .to_point(display_map);
 2380                    if reversed {
 2381                        Some(end..start)
 2382                    } else {
 2383                        Some(start..end)
 2384                    }
 2385                } else {
 2386                    None
 2387                }
 2388            })
 2389            .collect::<Vec<_>>();
 2390
 2391        self.change_selections(None, cx, |s| {
 2392            s.select_ranges(selection_ranges);
 2393        });
 2394        cx.notify();
 2395    }
 2396
 2397    pub fn has_pending_nonempty_selection(&self) -> bool {
 2398        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2399            Some(Selection { start, end, .. }) => start != end,
 2400            None => false,
 2401        };
 2402
 2403        pending_nonempty_selection
 2404            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2405    }
 2406
 2407    pub fn has_pending_selection(&self) -> bool {
 2408        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2409    }
 2410
 2411    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2412        if self.clear_expanded_diff_hunks(cx) {
 2413            cx.notify();
 2414            return;
 2415        }
 2416        if self.dismiss_menus_and_popups(true, cx) {
 2417            return;
 2418        }
 2419
 2420        if self.mode == EditorMode::Full
 2421            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2422        {
 2423            return;
 2424        }
 2425
 2426        cx.propagate();
 2427    }
 2428
 2429    pub fn dismiss_menus_and_popups(
 2430        &mut self,
 2431        should_report_inline_completion_event: bool,
 2432        cx: &mut ViewContext<Self>,
 2433    ) -> bool {
 2434        if self.take_rename(false, cx).is_some() {
 2435            return true;
 2436        }
 2437
 2438        if hide_hover(self, cx) {
 2439            return true;
 2440        }
 2441
 2442        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2443            return true;
 2444        }
 2445
 2446        if self.hide_context_menu(cx).is_some() {
 2447            return true;
 2448        }
 2449
 2450        if self.mouse_context_menu.take().is_some() {
 2451            return true;
 2452        }
 2453
 2454        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2455            return true;
 2456        }
 2457
 2458        if self.snippet_stack.pop().is_some() {
 2459            return true;
 2460        }
 2461
 2462        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2463            self.dismiss_diagnostics(cx);
 2464            return true;
 2465        }
 2466
 2467        false
 2468    }
 2469
 2470    fn linked_editing_ranges_for(
 2471        &self,
 2472        selection: Range<text::Anchor>,
 2473        cx: &AppContext,
 2474    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2475        if self.linked_edit_ranges.is_empty() {
 2476            return None;
 2477        }
 2478        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2479            selection.end.buffer_id.and_then(|end_buffer_id| {
 2480                if selection.start.buffer_id != Some(end_buffer_id) {
 2481                    return None;
 2482                }
 2483                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2484                let snapshot = buffer.read(cx).snapshot();
 2485                self.linked_edit_ranges
 2486                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2487                    .map(|ranges| (ranges, snapshot, buffer))
 2488            })?;
 2489        use text::ToOffset as TO;
 2490        // find offset from the start of current range to current cursor position
 2491        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2492
 2493        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2494        let start_difference = start_offset - start_byte_offset;
 2495        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2496        let end_difference = end_offset - start_byte_offset;
 2497        // Current range has associated linked ranges.
 2498        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2499        for range in linked_ranges.iter() {
 2500            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2501            let end_offset = start_offset + end_difference;
 2502            let start_offset = start_offset + start_difference;
 2503            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2504                continue;
 2505            }
 2506            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2507                if s.start.buffer_id != selection.start.buffer_id
 2508                    || s.end.buffer_id != selection.end.buffer_id
 2509                {
 2510                    return false;
 2511                }
 2512                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2513                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2514            }) {
 2515                continue;
 2516            }
 2517            let start = buffer_snapshot.anchor_after(start_offset);
 2518            let end = buffer_snapshot.anchor_after(end_offset);
 2519            linked_edits
 2520                .entry(buffer.clone())
 2521                .or_default()
 2522                .push(start..end);
 2523        }
 2524        Some(linked_edits)
 2525    }
 2526
 2527    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2528        let text: Arc<str> = text.into();
 2529
 2530        if self.read_only(cx) {
 2531            return;
 2532        }
 2533
 2534        let selections = self.selections.all_adjusted(cx);
 2535        let mut bracket_inserted = false;
 2536        let mut edits = Vec::new();
 2537        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2538        let mut new_selections = Vec::with_capacity(selections.len());
 2539        let mut new_autoclose_regions = Vec::new();
 2540        let snapshot = self.buffer.read(cx).read(cx);
 2541
 2542        for (selection, autoclose_region) in
 2543            self.selections_with_autoclose_regions(selections, &snapshot)
 2544        {
 2545            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2546                // Determine if the inserted text matches the opening or closing
 2547                // bracket of any of this language's bracket pairs.
 2548                let mut bracket_pair = None;
 2549                let mut is_bracket_pair_start = false;
 2550                let mut is_bracket_pair_end = false;
 2551                if !text.is_empty() {
 2552                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2553                    //  and they are removing the character that triggered IME popup.
 2554                    for (pair, enabled) in scope.brackets() {
 2555                        if !pair.close && !pair.surround {
 2556                            continue;
 2557                        }
 2558
 2559                        if enabled && pair.start.ends_with(text.as_ref()) {
 2560                            let prefix_len = pair.start.len() - text.len();
 2561                            let preceding_text_matches_prefix = prefix_len == 0
 2562                                || (selection.start.column >= (prefix_len as u32)
 2563                                    && snapshot.contains_str_at(
 2564                                        Point::new(
 2565                                            selection.start.row,
 2566                                            selection.start.column - (prefix_len as u32),
 2567                                        ),
 2568                                        &pair.start[..prefix_len],
 2569                                    ));
 2570                            if preceding_text_matches_prefix {
 2571                                bracket_pair = Some(pair.clone());
 2572                                is_bracket_pair_start = true;
 2573                                break;
 2574                            }
 2575                        }
 2576                        if pair.end.as_str() == text.as_ref() {
 2577                            bracket_pair = Some(pair.clone());
 2578                            is_bracket_pair_end = true;
 2579                            break;
 2580                        }
 2581                    }
 2582                }
 2583
 2584                if let Some(bracket_pair) = bracket_pair {
 2585                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2586                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2587                    let auto_surround =
 2588                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2589                    if selection.is_empty() {
 2590                        if is_bracket_pair_start {
 2591                            // If the inserted text is a suffix of an opening bracket and the
 2592                            // selection is preceded by the rest of the opening bracket, then
 2593                            // insert the closing bracket.
 2594                            let following_text_allows_autoclose = snapshot
 2595                                .chars_at(selection.start)
 2596                                .next()
 2597                                .map_or(true, |c| scope.should_autoclose_before(c));
 2598
 2599                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2600                                && bracket_pair.start.len() == 1
 2601                            {
 2602                                let target = bracket_pair.start.chars().next().unwrap();
 2603                                let current_line_count = snapshot
 2604                                    .reversed_chars_at(selection.start)
 2605                                    .take_while(|&c| c != '\n')
 2606                                    .filter(|&c| c == target)
 2607                                    .count();
 2608                                current_line_count % 2 == 1
 2609                            } else {
 2610                                false
 2611                            };
 2612
 2613                            if autoclose
 2614                                && bracket_pair.close
 2615                                && following_text_allows_autoclose
 2616                                && !is_closing_quote
 2617                            {
 2618                                let anchor = snapshot.anchor_before(selection.end);
 2619                                new_selections.push((selection.map(|_| anchor), text.len()));
 2620                                new_autoclose_regions.push((
 2621                                    anchor,
 2622                                    text.len(),
 2623                                    selection.id,
 2624                                    bracket_pair.clone(),
 2625                                ));
 2626                                edits.push((
 2627                                    selection.range(),
 2628                                    format!("{}{}", text, bracket_pair.end).into(),
 2629                                ));
 2630                                bracket_inserted = true;
 2631                                continue;
 2632                            }
 2633                        }
 2634
 2635                        if let Some(region) = autoclose_region {
 2636                            // If the selection is followed by an auto-inserted closing bracket,
 2637                            // then don't insert that closing bracket again; just move the selection
 2638                            // past the closing bracket.
 2639                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2640                                && text.as_ref() == region.pair.end.as_str();
 2641                            if should_skip {
 2642                                let anchor = snapshot.anchor_after(selection.end);
 2643                                new_selections
 2644                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2645                                continue;
 2646                            }
 2647                        }
 2648
 2649                        let always_treat_brackets_as_autoclosed = snapshot
 2650                            .settings_at(selection.start, cx)
 2651                            .always_treat_brackets_as_autoclosed;
 2652                        if always_treat_brackets_as_autoclosed
 2653                            && is_bracket_pair_end
 2654                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2655                        {
 2656                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2657                            // and the inserted text is a closing bracket and the selection is followed
 2658                            // by the closing bracket then move the selection past the closing bracket.
 2659                            let anchor = snapshot.anchor_after(selection.end);
 2660                            new_selections.push((selection.map(|_| anchor), text.len()));
 2661                            continue;
 2662                        }
 2663                    }
 2664                    // If an opening bracket is 1 character long and is typed while
 2665                    // text is selected, then surround that text with the bracket pair.
 2666                    else if auto_surround
 2667                        && bracket_pair.surround
 2668                        && is_bracket_pair_start
 2669                        && bracket_pair.start.chars().count() == 1
 2670                    {
 2671                        edits.push((selection.start..selection.start, text.clone()));
 2672                        edits.push((
 2673                            selection.end..selection.end,
 2674                            bracket_pair.end.as_str().into(),
 2675                        ));
 2676                        bracket_inserted = true;
 2677                        new_selections.push((
 2678                            Selection {
 2679                                id: selection.id,
 2680                                start: snapshot.anchor_after(selection.start),
 2681                                end: snapshot.anchor_before(selection.end),
 2682                                reversed: selection.reversed,
 2683                                goal: selection.goal,
 2684                            },
 2685                            0,
 2686                        ));
 2687                        continue;
 2688                    }
 2689                }
 2690            }
 2691
 2692            if self.auto_replace_emoji_shortcode
 2693                && selection.is_empty()
 2694                && text.as_ref().ends_with(':')
 2695            {
 2696                if let Some(possible_emoji_short_code) =
 2697                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2698                {
 2699                    if !possible_emoji_short_code.is_empty() {
 2700                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2701                            let emoji_shortcode_start = Point::new(
 2702                                selection.start.row,
 2703                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2704                            );
 2705
 2706                            // Remove shortcode from buffer
 2707                            edits.push((
 2708                                emoji_shortcode_start..selection.start,
 2709                                "".to_string().into(),
 2710                            ));
 2711                            new_selections.push((
 2712                                Selection {
 2713                                    id: selection.id,
 2714                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2715                                    end: snapshot.anchor_before(selection.start),
 2716                                    reversed: selection.reversed,
 2717                                    goal: selection.goal,
 2718                                },
 2719                                0,
 2720                            ));
 2721
 2722                            // Insert emoji
 2723                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2724                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2725                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2726
 2727                            continue;
 2728                        }
 2729                    }
 2730                }
 2731            }
 2732
 2733            // If not handling any auto-close operation, then just replace the selected
 2734            // text with the given input and move the selection to the end of the
 2735            // newly inserted text.
 2736            let anchor = snapshot.anchor_after(selection.end);
 2737            if !self.linked_edit_ranges.is_empty() {
 2738                let start_anchor = snapshot.anchor_before(selection.start);
 2739
 2740                let is_word_char = text.chars().next().map_or(true, |char| {
 2741                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2742                    classifier.is_word(char)
 2743                });
 2744
 2745                if is_word_char {
 2746                    if let Some(ranges) = self
 2747                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2748                    {
 2749                        for (buffer, edits) in ranges {
 2750                            linked_edits
 2751                                .entry(buffer.clone())
 2752                                .or_default()
 2753                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2754                        }
 2755                    }
 2756                }
 2757            }
 2758
 2759            new_selections.push((selection.map(|_| anchor), 0));
 2760            edits.push((selection.start..selection.end, text.clone()));
 2761        }
 2762
 2763        drop(snapshot);
 2764
 2765        self.transact(cx, |this, cx| {
 2766            this.buffer.update(cx, |buffer, cx| {
 2767                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2768            });
 2769            for (buffer, edits) in linked_edits {
 2770                buffer.update(cx, |buffer, cx| {
 2771                    let snapshot = buffer.snapshot();
 2772                    let edits = edits
 2773                        .into_iter()
 2774                        .map(|(range, text)| {
 2775                            use text::ToPoint as TP;
 2776                            let end_point = TP::to_point(&range.end, &snapshot);
 2777                            let start_point = TP::to_point(&range.start, &snapshot);
 2778                            (start_point..end_point, text)
 2779                        })
 2780                        .sorted_by_key(|(range, _)| range.start)
 2781                        .collect::<Vec<_>>();
 2782                    buffer.edit(edits, None, cx);
 2783                })
 2784            }
 2785            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2786            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2787            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2788            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2789                .zip(new_selection_deltas)
 2790                .map(|(selection, delta)| Selection {
 2791                    id: selection.id,
 2792                    start: selection.start + delta,
 2793                    end: selection.end + delta,
 2794                    reversed: selection.reversed,
 2795                    goal: SelectionGoal::None,
 2796                })
 2797                .collect::<Vec<_>>();
 2798
 2799            let mut i = 0;
 2800            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2801                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2802                let start = map.buffer_snapshot.anchor_before(position);
 2803                let end = map.buffer_snapshot.anchor_after(position);
 2804                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2805                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2806                        Ordering::Less => i += 1,
 2807                        Ordering::Greater => break,
 2808                        Ordering::Equal => {
 2809                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2810                                Ordering::Less => i += 1,
 2811                                Ordering::Equal => break,
 2812                                Ordering::Greater => break,
 2813                            }
 2814                        }
 2815                    }
 2816                }
 2817                this.autoclose_regions.insert(
 2818                    i,
 2819                    AutocloseRegion {
 2820                        selection_id,
 2821                        range: start..end,
 2822                        pair,
 2823                    },
 2824                );
 2825            }
 2826
 2827            let had_active_inline_completion = this.has_active_inline_completion();
 2828            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2829                s.select(new_selections)
 2830            });
 2831
 2832            if !bracket_inserted {
 2833                if let Some(on_type_format_task) =
 2834                    this.trigger_on_type_formatting(text.to_string(), cx)
 2835                {
 2836                    on_type_format_task.detach_and_log_err(cx);
 2837                }
 2838            }
 2839
 2840            let editor_settings = EditorSettings::get_global(cx);
 2841            if bracket_inserted
 2842                && (editor_settings.auto_signature_help
 2843                    || editor_settings.show_signature_help_after_edits)
 2844            {
 2845                this.show_signature_help(&ShowSignatureHelp, cx);
 2846            }
 2847
 2848            let trigger_in_words = !had_active_inline_completion;
 2849            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2850            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2851            this.refresh_inline_completion(true, false, cx);
 2852        });
 2853    }
 2854
 2855    fn find_possible_emoji_shortcode_at_position(
 2856        snapshot: &MultiBufferSnapshot,
 2857        position: Point,
 2858    ) -> Option<String> {
 2859        let mut chars = Vec::new();
 2860        let mut found_colon = false;
 2861        for char in snapshot.reversed_chars_at(position).take(100) {
 2862            // Found a possible emoji shortcode in the middle of the buffer
 2863            if found_colon {
 2864                if char.is_whitespace() {
 2865                    chars.reverse();
 2866                    return Some(chars.iter().collect());
 2867                }
 2868                // If the previous character is not a whitespace, we are in the middle of a word
 2869                // and we only want to complete the shortcode if the word is made up of other emojis
 2870                let mut containing_word = String::new();
 2871                for ch in snapshot
 2872                    .reversed_chars_at(position)
 2873                    .skip(chars.len() + 1)
 2874                    .take(100)
 2875                {
 2876                    if ch.is_whitespace() {
 2877                        break;
 2878                    }
 2879                    containing_word.push(ch);
 2880                }
 2881                let containing_word = containing_word.chars().rev().collect::<String>();
 2882                if util::word_consists_of_emojis(containing_word.as_str()) {
 2883                    chars.reverse();
 2884                    return Some(chars.iter().collect());
 2885                }
 2886            }
 2887
 2888            if char.is_whitespace() || !char.is_ascii() {
 2889                return None;
 2890            }
 2891            if char == ':' {
 2892                found_colon = true;
 2893            } else {
 2894                chars.push(char);
 2895            }
 2896        }
 2897        // Found a possible emoji shortcode at the beginning of the buffer
 2898        chars.reverse();
 2899        Some(chars.iter().collect())
 2900    }
 2901
 2902    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2903        self.transact(cx, |this, cx| {
 2904            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2905                let selections = this.selections.all::<usize>(cx);
 2906                let multi_buffer = this.buffer.read(cx);
 2907                let buffer = multi_buffer.snapshot(cx);
 2908                selections
 2909                    .iter()
 2910                    .map(|selection| {
 2911                        let start_point = selection.start.to_point(&buffer);
 2912                        let mut indent =
 2913                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2914                        indent.len = cmp::min(indent.len, start_point.column);
 2915                        let start = selection.start;
 2916                        let end = selection.end;
 2917                        let selection_is_empty = start == end;
 2918                        let language_scope = buffer.language_scope_at(start);
 2919                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2920                            &language_scope
 2921                        {
 2922                            let leading_whitespace_len = buffer
 2923                                .reversed_chars_at(start)
 2924                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2925                                .map(|c| c.len_utf8())
 2926                                .sum::<usize>();
 2927
 2928                            let trailing_whitespace_len = buffer
 2929                                .chars_at(end)
 2930                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2931                                .map(|c| c.len_utf8())
 2932                                .sum::<usize>();
 2933
 2934                            let insert_extra_newline =
 2935                                language.brackets().any(|(pair, enabled)| {
 2936                                    let pair_start = pair.start.trim_end();
 2937                                    let pair_end = pair.end.trim_start();
 2938
 2939                                    enabled
 2940                                        && pair.newline
 2941                                        && buffer.contains_str_at(
 2942                                            end + trailing_whitespace_len,
 2943                                            pair_end,
 2944                                        )
 2945                                        && buffer.contains_str_at(
 2946                                            (start - leading_whitespace_len)
 2947                                                .saturating_sub(pair_start.len()),
 2948                                            pair_start,
 2949                                        )
 2950                                });
 2951
 2952                            // Comment extension on newline is allowed only for cursor selections
 2953                            let comment_delimiter = maybe!({
 2954                                if !selection_is_empty {
 2955                                    return None;
 2956                                }
 2957
 2958                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 2959                                    return None;
 2960                                }
 2961
 2962                                let delimiters = language.line_comment_prefixes();
 2963                                let max_len_of_delimiter =
 2964                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 2965                                let (snapshot, range) =
 2966                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 2967
 2968                                let mut index_of_first_non_whitespace = 0;
 2969                                let comment_candidate = snapshot
 2970                                    .chars_for_range(range)
 2971                                    .skip_while(|c| {
 2972                                        let should_skip = c.is_whitespace();
 2973                                        if should_skip {
 2974                                            index_of_first_non_whitespace += 1;
 2975                                        }
 2976                                        should_skip
 2977                                    })
 2978                                    .take(max_len_of_delimiter)
 2979                                    .collect::<String>();
 2980                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 2981                                    comment_candidate.starts_with(comment_prefix.as_ref())
 2982                                })?;
 2983                                let cursor_is_placed_after_comment_marker =
 2984                                    index_of_first_non_whitespace + comment_prefix.len()
 2985                                        <= start_point.column as usize;
 2986                                if cursor_is_placed_after_comment_marker {
 2987                                    Some(comment_prefix.clone())
 2988                                } else {
 2989                                    None
 2990                                }
 2991                            });
 2992                            (comment_delimiter, insert_extra_newline)
 2993                        } else {
 2994                            (None, false)
 2995                        };
 2996
 2997                        let capacity_for_delimiter = comment_delimiter
 2998                            .as_deref()
 2999                            .map(str::len)
 3000                            .unwrap_or_default();
 3001                        let mut new_text =
 3002                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3003                        new_text.push('\n');
 3004                        new_text.extend(indent.chars());
 3005                        if let Some(delimiter) = &comment_delimiter {
 3006                            new_text.push_str(delimiter);
 3007                        }
 3008                        if insert_extra_newline {
 3009                            new_text = new_text.repeat(2);
 3010                        }
 3011
 3012                        let anchor = buffer.anchor_after(end);
 3013                        let new_selection = selection.map(|_| anchor);
 3014                        (
 3015                            (start..end, new_text),
 3016                            (insert_extra_newline, new_selection),
 3017                        )
 3018                    })
 3019                    .unzip()
 3020            };
 3021
 3022            this.edit_with_autoindent(edits, cx);
 3023            let buffer = this.buffer.read(cx).snapshot(cx);
 3024            let new_selections = selection_fixup_info
 3025                .into_iter()
 3026                .map(|(extra_newline_inserted, new_selection)| {
 3027                    let mut cursor = new_selection.end.to_point(&buffer);
 3028                    if extra_newline_inserted {
 3029                        cursor.row -= 1;
 3030                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3031                    }
 3032                    new_selection.map(|_| cursor)
 3033                })
 3034                .collect();
 3035
 3036            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3037            this.refresh_inline_completion(true, false, cx);
 3038        });
 3039    }
 3040
 3041    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3042        let buffer = self.buffer.read(cx);
 3043        let snapshot = buffer.snapshot(cx);
 3044
 3045        let mut edits = Vec::new();
 3046        let mut rows = Vec::new();
 3047
 3048        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3049            let cursor = selection.head();
 3050            let row = cursor.row;
 3051
 3052            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3053
 3054            let newline = "\n".to_string();
 3055            edits.push((start_of_line..start_of_line, newline));
 3056
 3057            rows.push(row + rows_inserted as u32);
 3058        }
 3059
 3060        self.transact(cx, |editor, cx| {
 3061            editor.edit(edits, cx);
 3062
 3063            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3064                let mut index = 0;
 3065                s.move_cursors_with(|map, _, _| {
 3066                    let row = rows[index];
 3067                    index += 1;
 3068
 3069                    let point = Point::new(row, 0);
 3070                    let boundary = map.next_line_boundary(point).1;
 3071                    let clipped = map.clip_point(boundary, Bias::Left);
 3072
 3073                    (clipped, SelectionGoal::None)
 3074                });
 3075            });
 3076
 3077            let mut indent_edits = Vec::new();
 3078            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3079            for row in rows {
 3080                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3081                for (row, indent) in indents {
 3082                    if indent.len == 0 {
 3083                        continue;
 3084                    }
 3085
 3086                    let text = match indent.kind {
 3087                        IndentKind::Space => " ".repeat(indent.len as usize),
 3088                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3089                    };
 3090                    let point = Point::new(row.0, 0);
 3091                    indent_edits.push((point..point, text));
 3092                }
 3093            }
 3094            editor.edit(indent_edits, cx);
 3095        });
 3096    }
 3097
 3098    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3099        let buffer = self.buffer.read(cx);
 3100        let snapshot = buffer.snapshot(cx);
 3101
 3102        let mut edits = Vec::new();
 3103        let mut rows = Vec::new();
 3104        let mut rows_inserted = 0;
 3105
 3106        for selection in self.selections.all_adjusted(cx) {
 3107            let cursor = selection.head();
 3108            let row = cursor.row;
 3109
 3110            let point = Point::new(row + 1, 0);
 3111            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3112
 3113            let newline = "\n".to_string();
 3114            edits.push((start_of_line..start_of_line, newline));
 3115
 3116            rows_inserted += 1;
 3117            rows.push(row + rows_inserted);
 3118        }
 3119
 3120        self.transact(cx, |editor, cx| {
 3121            editor.edit(edits, cx);
 3122
 3123            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3124                let mut index = 0;
 3125                s.move_cursors_with(|map, _, _| {
 3126                    let row = rows[index];
 3127                    index += 1;
 3128
 3129                    let point = Point::new(row, 0);
 3130                    let boundary = map.next_line_boundary(point).1;
 3131                    let clipped = map.clip_point(boundary, Bias::Left);
 3132
 3133                    (clipped, SelectionGoal::None)
 3134                });
 3135            });
 3136
 3137            let mut indent_edits = Vec::new();
 3138            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3139            for row in rows {
 3140                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3141                for (row, indent) in indents {
 3142                    if indent.len == 0 {
 3143                        continue;
 3144                    }
 3145
 3146                    let text = match indent.kind {
 3147                        IndentKind::Space => " ".repeat(indent.len as usize),
 3148                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3149                    };
 3150                    let point = Point::new(row.0, 0);
 3151                    indent_edits.push((point..point, text));
 3152                }
 3153            }
 3154            editor.edit(indent_edits, cx);
 3155        });
 3156    }
 3157
 3158    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3159        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3160            original_indent_columns: Vec::new(),
 3161        });
 3162        self.insert_with_autoindent_mode(text, autoindent, cx);
 3163    }
 3164
 3165    fn insert_with_autoindent_mode(
 3166        &mut self,
 3167        text: &str,
 3168        autoindent_mode: Option<AutoindentMode>,
 3169        cx: &mut ViewContext<Self>,
 3170    ) {
 3171        if self.read_only(cx) {
 3172            return;
 3173        }
 3174
 3175        let text: Arc<str> = text.into();
 3176        self.transact(cx, |this, cx| {
 3177            let old_selections = this.selections.all_adjusted(cx);
 3178            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3179                let anchors = {
 3180                    let snapshot = buffer.read(cx);
 3181                    old_selections
 3182                        .iter()
 3183                        .map(|s| {
 3184                            let anchor = snapshot.anchor_after(s.head());
 3185                            s.map(|_| anchor)
 3186                        })
 3187                        .collect::<Vec<_>>()
 3188                };
 3189                buffer.edit(
 3190                    old_selections
 3191                        .iter()
 3192                        .map(|s| (s.start..s.end, text.clone())),
 3193                    autoindent_mode,
 3194                    cx,
 3195                );
 3196                anchors
 3197            });
 3198
 3199            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3200                s.select_anchors(selection_anchors);
 3201            })
 3202        });
 3203    }
 3204
 3205    fn trigger_completion_on_input(
 3206        &mut self,
 3207        text: &str,
 3208        trigger_in_words: bool,
 3209        cx: &mut ViewContext<Self>,
 3210    ) {
 3211        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3212            self.show_completions(
 3213                &ShowCompletions {
 3214                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3215                },
 3216                cx,
 3217            );
 3218        } else {
 3219            self.hide_context_menu(cx);
 3220        }
 3221    }
 3222
 3223    fn is_completion_trigger(
 3224        &self,
 3225        text: &str,
 3226        trigger_in_words: bool,
 3227        cx: &mut ViewContext<Self>,
 3228    ) -> bool {
 3229        let position = self.selections.newest_anchor().head();
 3230        let multibuffer = self.buffer.read(cx);
 3231        let Some(buffer) = position
 3232            .buffer_id
 3233            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3234        else {
 3235            return false;
 3236        };
 3237
 3238        if let Some(completion_provider) = &self.completion_provider {
 3239            completion_provider.is_completion_trigger(
 3240                &buffer,
 3241                position.text_anchor,
 3242                text,
 3243                trigger_in_words,
 3244                cx,
 3245            )
 3246        } else {
 3247            false
 3248        }
 3249    }
 3250
 3251    /// If any empty selections is touching the start of its innermost containing autoclose
 3252    /// region, expand it to select the brackets.
 3253    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3254        let selections = self.selections.all::<usize>(cx);
 3255        let buffer = self.buffer.read(cx).read(cx);
 3256        let new_selections = self
 3257            .selections_with_autoclose_regions(selections, &buffer)
 3258            .map(|(mut selection, region)| {
 3259                if !selection.is_empty() {
 3260                    return selection;
 3261                }
 3262
 3263                if let Some(region) = region {
 3264                    let mut range = region.range.to_offset(&buffer);
 3265                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3266                        range.start -= region.pair.start.len();
 3267                        if buffer.contains_str_at(range.start, &region.pair.start)
 3268                            && buffer.contains_str_at(range.end, &region.pair.end)
 3269                        {
 3270                            range.end += region.pair.end.len();
 3271                            selection.start = range.start;
 3272                            selection.end = range.end;
 3273
 3274                            return selection;
 3275                        }
 3276                    }
 3277                }
 3278
 3279                let always_treat_brackets_as_autoclosed = buffer
 3280                    .settings_at(selection.start, cx)
 3281                    .always_treat_brackets_as_autoclosed;
 3282
 3283                if !always_treat_brackets_as_autoclosed {
 3284                    return selection;
 3285                }
 3286
 3287                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3288                    for (pair, enabled) in scope.brackets() {
 3289                        if !enabled || !pair.close {
 3290                            continue;
 3291                        }
 3292
 3293                        if buffer.contains_str_at(selection.start, &pair.end) {
 3294                            let pair_start_len = pair.start.len();
 3295                            if buffer.contains_str_at(
 3296                                selection.start.saturating_sub(pair_start_len),
 3297                                &pair.start,
 3298                            ) {
 3299                                selection.start -= pair_start_len;
 3300                                selection.end += pair.end.len();
 3301
 3302                                return selection;
 3303                            }
 3304                        }
 3305                    }
 3306                }
 3307
 3308                selection
 3309            })
 3310            .collect();
 3311
 3312        drop(buffer);
 3313        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3314    }
 3315
 3316    /// Iterate the given selections, and for each one, find the smallest surrounding
 3317    /// autoclose region. This uses the ordering of the selections and the autoclose
 3318    /// regions to avoid repeated comparisons.
 3319    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3320        &'a self,
 3321        selections: impl IntoIterator<Item = Selection<D>>,
 3322        buffer: &'a MultiBufferSnapshot,
 3323    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3324        let mut i = 0;
 3325        let mut regions = self.autoclose_regions.as_slice();
 3326        selections.into_iter().map(move |selection| {
 3327            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3328
 3329            let mut enclosing = None;
 3330            while let Some(pair_state) = regions.get(i) {
 3331                if pair_state.range.end.to_offset(buffer) < range.start {
 3332                    regions = &regions[i + 1..];
 3333                    i = 0;
 3334                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3335                    break;
 3336                } else {
 3337                    if pair_state.selection_id == selection.id {
 3338                        enclosing = Some(pair_state);
 3339                    }
 3340                    i += 1;
 3341                }
 3342            }
 3343
 3344            (selection, enclosing)
 3345        })
 3346    }
 3347
 3348    /// Remove any autoclose regions that no longer contain their selection.
 3349    fn invalidate_autoclose_regions(
 3350        &mut self,
 3351        mut selections: &[Selection<Anchor>],
 3352        buffer: &MultiBufferSnapshot,
 3353    ) {
 3354        self.autoclose_regions.retain(|state| {
 3355            let mut i = 0;
 3356            while let Some(selection) = selections.get(i) {
 3357                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3358                    selections = &selections[1..];
 3359                    continue;
 3360                }
 3361                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3362                    break;
 3363                }
 3364                if selection.id == state.selection_id {
 3365                    return true;
 3366                } else {
 3367                    i += 1;
 3368                }
 3369            }
 3370            false
 3371        });
 3372    }
 3373
 3374    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3375        let offset = position.to_offset(buffer);
 3376        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3377        if offset > word_range.start && kind == Some(CharKind::Word) {
 3378            Some(
 3379                buffer
 3380                    .text_for_range(word_range.start..offset)
 3381                    .collect::<String>(),
 3382            )
 3383        } else {
 3384            None
 3385        }
 3386    }
 3387
 3388    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3389        self.refresh_inlay_hints(
 3390            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3391            cx,
 3392        );
 3393    }
 3394
 3395    pub fn inlay_hints_enabled(&self) -> bool {
 3396        self.inlay_hint_cache.enabled
 3397    }
 3398
 3399    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3400        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3401            return;
 3402        }
 3403
 3404        let reason_description = reason.description();
 3405        let ignore_debounce = matches!(
 3406            reason,
 3407            InlayHintRefreshReason::SettingsChange(_)
 3408                | InlayHintRefreshReason::Toggle(_)
 3409                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3410        );
 3411        let (invalidate_cache, required_languages) = match reason {
 3412            InlayHintRefreshReason::Toggle(enabled) => {
 3413                self.inlay_hint_cache.enabled = enabled;
 3414                if enabled {
 3415                    (InvalidationStrategy::RefreshRequested, None)
 3416                } else {
 3417                    self.inlay_hint_cache.clear();
 3418                    self.splice_inlays(
 3419                        self.visible_inlay_hints(cx)
 3420                            .iter()
 3421                            .map(|inlay| inlay.id)
 3422                            .collect(),
 3423                        Vec::new(),
 3424                        cx,
 3425                    );
 3426                    return;
 3427                }
 3428            }
 3429            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3430                match self.inlay_hint_cache.update_settings(
 3431                    &self.buffer,
 3432                    new_settings,
 3433                    self.visible_inlay_hints(cx),
 3434                    cx,
 3435                ) {
 3436                    ControlFlow::Break(Some(InlaySplice {
 3437                        to_remove,
 3438                        to_insert,
 3439                    })) => {
 3440                        self.splice_inlays(to_remove, to_insert, cx);
 3441                        return;
 3442                    }
 3443                    ControlFlow::Break(None) => return,
 3444                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3445                }
 3446            }
 3447            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3448                if let Some(InlaySplice {
 3449                    to_remove,
 3450                    to_insert,
 3451                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3452                {
 3453                    self.splice_inlays(to_remove, to_insert, cx);
 3454                }
 3455                return;
 3456            }
 3457            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3458            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3459                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3460            }
 3461            InlayHintRefreshReason::RefreshRequested => {
 3462                (InvalidationStrategy::RefreshRequested, None)
 3463            }
 3464        };
 3465
 3466        if let Some(InlaySplice {
 3467            to_remove,
 3468            to_insert,
 3469        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3470            reason_description,
 3471            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3472            invalidate_cache,
 3473            ignore_debounce,
 3474            cx,
 3475        ) {
 3476            self.splice_inlays(to_remove, to_insert, cx);
 3477        }
 3478    }
 3479
 3480    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3481        self.display_map
 3482            .read(cx)
 3483            .current_inlays()
 3484            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3485            .cloned()
 3486            .collect()
 3487    }
 3488
 3489    pub fn excerpts_for_inlay_hints_query(
 3490        &self,
 3491        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3492        cx: &mut ViewContext<Editor>,
 3493    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3494        let Some(project) = self.project.as_ref() else {
 3495            return HashMap::default();
 3496        };
 3497        let project = project.read(cx);
 3498        let multi_buffer = self.buffer().read(cx);
 3499        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3500        let multi_buffer_visible_start = self
 3501            .scroll_manager
 3502            .anchor()
 3503            .anchor
 3504            .to_point(&multi_buffer_snapshot);
 3505        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3506            multi_buffer_visible_start
 3507                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3508            Bias::Left,
 3509        );
 3510        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3511        multi_buffer
 3512            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3513            .into_iter()
 3514            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3515            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3516                let buffer = buffer_handle.read(cx);
 3517                let buffer_file = project::File::from_dyn(buffer.file())?;
 3518                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3519                let worktree_entry = buffer_worktree
 3520                    .read(cx)
 3521                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3522                if worktree_entry.is_ignored {
 3523                    return None;
 3524                }
 3525
 3526                let language = buffer.language()?;
 3527                if let Some(restrict_to_languages) = restrict_to_languages {
 3528                    if !restrict_to_languages.contains(language) {
 3529                        return None;
 3530                    }
 3531                }
 3532                Some((
 3533                    excerpt_id,
 3534                    (
 3535                        buffer_handle,
 3536                        buffer.version().clone(),
 3537                        excerpt_visible_range,
 3538                    ),
 3539                ))
 3540            })
 3541            .collect()
 3542    }
 3543
 3544    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3545        TextLayoutDetails {
 3546            text_system: cx.text_system().clone(),
 3547            editor_style: self.style.clone().unwrap(),
 3548            rem_size: cx.rem_size(),
 3549            scroll_anchor: self.scroll_manager.anchor(),
 3550            visible_rows: self.visible_line_count(),
 3551            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3552        }
 3553    }
 3554
 3555    fn splice_inlays(
 3556        &self,
 3557        to_remove: Vec<InlayId>,
 3558        to_insert: Vec<Inlay>,
 3559        cx: &mut ViewContext<Self>,
 3560    ) {
 3561        self.display_map.update(cx, |display_map, cx| {
 3562            display_map.splice_inlays(to_remove, to_insert, cx)
 3563        });
 3564        cx.notify();
 3565    }
 3566
 3567    fn trigger_on_type_formatting(
 3568        &self,
 3569        input: String,
 3570        cx: &mut ViewContext<Self>,
 3571    ) -> Option<Task<Result<()>>> {
 3572        if input.len() != 1 {
 3573            return None;
 3574        }
 3575
 3576        let project = self.project.as_ref()?;
 3577        let position = self.selections.newest_anchor().head();
 3578        let (buffer, buffer_position) = self
 3579            .buffer
 3580            .read(cx)
 3581            .text_anchor_for_position(position, cx)?;
 3582
 3583        let settings = language_settings::language_settings(
 3584            buffer
 3585                .read(cx)
 3586                .language_at(buffer_position)
 3587                .map(|l| l.name()),
 3588            buffer.read(cx).file(),
 3589            cx,
 3590        );
 3591        if !settings.use_on_type_format {
 3592            return None;
 3593        }
 3594
 3595        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3596        // hence we do LSP request & edit on host side only — add formats to host's history.
 3597        let push_to_lsp_host_history = true;
 3598        // If this is not the host, append its history with new edits.
 3599        let push_to_client_history = project.read(cx).is_via_collab();
 3600
 3601        let on_type_formatting = project.update(cx, |project, cx| {
 3602            project.on_type_format(
 3603                buffer.clone(),
 3604                buffer_position,
 3605                input,
 3606                push_to_lsp_host_history,
 3607                cx,
 3608            )
 3609        });
 3610        Some(cx.spawn(|editor, mut cx| async move {
 3611            if let Some(transaction) = on_type_formatting.await? {
 3612                if push_to_client_history {
 3613                    buffer
 3614                        .update(&mut cx, |buffer, _| {
 3615                            buffer.push_transaction(transaction, Instant::now());
 3616                        })
 3617                        .ok();
 3618                }
 3619                editor.update(&mut cx, |editor, cx| {
 3620                    editor.refresh_document_highlights(cx);
 3621                })?;
 3622            }
 3623            Ok(())
 3624        }))
 3625    }
 3626
 3627    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3628        if self.pending_rename.is_some() {
 3629            return;
 3630        }
 3631
 3632        let Some(provider) = self.completion_provider.as_ref() else {
 3633            return;
 3634        };
 3635
 3636        if !self.snippet_stack.is_empty() && self.context_menu.read().as_ref().is_some() {
 3637            return;
 3638        }
 3639
 3640        let position = self.selections.newest_anchor().head();
 3641        let (buffer, buffer_position) =
 3642            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3643                output
 3644            } else {
 3645                return;
 3646            };
 3647        let show_completion_documentation = buffer
 3648            .read(cx)
 3649            .snapshot()
 3650            .settings_at(buffer_position, cx)
 3651            .show_completion_documentation;
 3652
 3653        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3654
 3655        let aside_was_displayed = match self.context_menu.read().deref() {
 3656            Some(CodeContextMenu::Completions(menu)) => menu.aside_was_displayed.get(),
 3657            _ => false,
 3658        };
 3659        let trigger_kind = match &options.trigger {
 3660            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3661                CompletionTriggerKind::TRIGGER_CHARACTER
 3662            }
 3663            _ => CompletionTriggerKind::INVOKED,
 3664        };
 3665        let completion_context = CompletionContext {
 3666            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3667                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3668                    Some(String::from(trigger))
 3669                } else {
 3670                    None
 3671                }
 3672            }),
 3673            trigger_kind,
 3674        };
 3675        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3676        let sort_completions = provider.sort_completions();
 3677
 3678        let id = post_inc(&mut self.next_completion_id);
 3679        let task = cx.spawn(|editor, mut cx| {
 3680            async move {
 3681                editor.update(&mut cx, |this, _| {
 3682                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3683                })?;
 3684                let completions = completions.await.log_err();
 3685                let menu = if let Some(completions) = completions {
 3686                    let mut menu = CompletionsMenu::new(
 3687                        id,
 3688                        sort_completions,
 3689                        show_completion_documentation,
 3690                        position,
 3691                        buffer.clone(),
 3692                        completions.into(),
 3693                        aside_was_displayed,
 3694                    );
 3695                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3696                        .await;
 3697
 3698                    if menu.matches.is_empty() {
 3699                        None
 3700                    } else {
 3701                        Some(menu)
 3702                    }
 3703                } else {
 3704                    None
 3705                };
 3706
 3707                editor.update(&mut cx, |editor, cx| {
 3708                    let mut context_menu = editor.context_menu.write();
 3709                    match context_menu.as_ref() {
 3710                        None => {}
 3711
 3712                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3713                            if prev_menu.id > id {
 3714                                return;
 3715                            }
 3716                        }
 3717
 3718                        _ => return,
 3719                    }
 3720
 3721                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3722                        let mut menu = menu.unwrap();
 3723                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3724                        *context_menu = Some(CodeContextMenu::Completions(menu));
 3725                        drop(context_menu);
 3726                        cx.notify();
 3727                    } else if editor.completion_tasks.len() <= 1 {
 3728                        // If there are no more completion tasks and the last menu was
 3729                        // empty, we should hide it. If it was already hidden, we should
 3730                        // also show the copilot completion when available.
 3731                        drop(context_menu);
 3732                        editor.hide_context_menu(cx);
 3733                    }
 3734                })?;
 3735
 3736                Ok::<_, anyhow::Error>(())
 3737            }
 3738            .log_err()
 3739        });
 3740
 3741        self.completion_tasks.push((id, task));
 3742    }
 3743
 3744    pub fn confirm_completion(
 3745        &mut self,
 3746        action: &ConfirmCompletion,
 3747        cx: &mut ViewContext<Self>,
 3748    ) -> Option<Task<Result<()>>> {
 3749        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3750    }
 3751
 3752    pub fn compose_completion(
 3753        &mut self,
 3754        action: &ComposeCompletion,
 3755        cx: &mut ViewContext<Self>,
 3756    ) -> Option<Task<Result<()>>> {
 3757        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3758    }
 3759
 3760    fn do_completion(
 3761        &mut self,
 3762        item_ix: Option<usize>,
 3763        intent: CompletionIntent,
 3764        cx: &mut ViewContext<Editor>,
 3765    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3766        use language::ToOffset as _;
 3767
 3768        self.discard_inline_completion(true, cx);
 3769        let completions_menu =
 3770            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3771                menu
 3772            } else {
 3773                return None;
 3774            };
 3775
 3776        let mat = completions_menu
 3777            .matches
 3778            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3779        let buffer_handle = completions_menu.buffer;
 3780        let completions = completions_menu.completions.read();
 3781        let completion = completions.get(mat.candidate_id)?;
 3782        cx.stop_propagation();
 3783
 3784        let snippet;
 3785        let text;
 3786
 3787        if completion.is_snippet() {
 3788            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3789            text = snippet.as_ref().unwrap().text.clone();
 3790        } else {
 3791            snippet = None;
 3792            text = completion.new_text.clone();
 3793        };
 3794        let selections = self.selections.all::<usize>(cx);
 3795        let buffer = buffer_handle.read(cx);
 3796        let old_range = completion.old_range.to_offset(buffer);
 3797        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3798
 3799        let newest_selection = self.selections.newest_anchor();
 3800        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3801            return None;
 3802        }
 3803
 3804        let lookbehind = newest_selection
 3805            .start
 3806            .text_anchor
 3807            .to_offset(buffer)
 3808            .saturating_sub(old_range.start);
 3809        let lookahead = old_range
 3810            .end
 3811            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3812        let mut common_prefix_len = old_text
 3813            .bytes()
 3814            .zip(text.bytes())
 3815            .take_while(|(a, b)| a == b)
 3816            .count();
 3817
 3818        let snapshot = self.buffer.read(cx).snapshot(cx);
 3819        let mut range_to_replace: Option<Range<isize>> = None;
 3820        let mut ranges = Vec::new();
 3821        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3822        for selection in &selections {
 3823            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3824                let start = selection.start.saturating_sub(lookbehind);
 3825                let end = selection.end + lookahead;
 3826                if selection.id == newest_selection.id {
 3827                    range_to_replace = Some(
 3828                        ((start + common_prefix_len) as isize - selection.start as isize)
 3829                            ..(end as isize - selection.start as isize),
 3830                    );
 3831                }
 3832                ranges.push(start + common_prefix_len..end);
 3833            } else {
 3834                common_prefix_len = 0;
 3835                ranges.clear();
 3836                ranges.extend(selections.iter().map(|s| {
 3837                    if s.id == newest_selection.id {
 3838                        range_to_replace = Some(
 3839                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3840                                - selection.start as isize
 3841                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3842                                    - selection.start as isize,
 3843                        );
 3844                        old_range.clone()
 3845                    } else {
 3846                        s.start..s.end
 3847                    }
 3848                }));
 3849                break;
 3850            }
 3851            if !self.linked_edit_ranges.is_empty() {
 3852                let start_anchor = snapshot.anchor_before(selection.head());
 3853                let end_anchor = snapshot.anchor_after(selection.tail());
 3854                if let Some(ranges) = self
 3855                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3856                {
 3857                    for (buffer, edits) in ranges {
 3858                        linked_edits.entry(buffer.clone()).or_default().extend(
 3859                            edits
 3860                                .into_iter()
 3861                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3862                        );
 3863                    }
 3864                }
 3865            }
 3866        }
 3867        let text = &text[common_prefix_len..];
 3868
 3869        cx.emit(EditorEvent::InputHandled {
 3870            utf16_range_to_replace: range_to_replace,
 3871            text: text.into(),
 3872        });
 3873
 3874        self.transact(cx, |this, cx| {
 3875            if let Some(mut snippet) = snippet {
 3876                snippet.text = text.to_string();
 3877                for tabstop in snippet
 3878                    .tabstops
 3879                    .iter_mut()
 3880                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3881                {
 3882                    tabstop.start -= common_prefix_len as isize;
 3883                    tabstop.end -= common_prefix_len as isize;
 3884                }
 3885
 3886                this.insert_snippet(&ranges, snippet, cx).log_err();
 3887            } else {
 3888                this.buffer.update(cx, |buffer, cx| {
 3889                    buffer.edit(
 3890                        ranges.iter().map(|range| (range.clone(), text)),
 3891                        this.autoindent_mode.clone(),
 3892                        cx,
 3893                    );
 3894                });
 3895            }
 3896            for (buffer, edits) in linked_edits {
 3897                buffer.update(cx, |buffer, cx| {
 3898                    let snapshot = buffer.snapshot();
 3899                    let edits = edits
 3900                        .into_iter()
 3901                        .map(|(range, text)| {
 3902                            use text::ToPoint as TP;
 3903                            let end_point = TP::to_point(&range.end, &snapshot);
 3904                            let start_point = TP::to_point(&range.start, &snapshot);
 3905                            (start_point..end_point, text)
 3906                        })
 3907                        .sorted_by_key(|(range, _)| range.start)
 3908                        .collect::<Vec<_>>();
 3909                    buffer.edit(edits, None, cx);
 3910                })
 3911            }
 3912
 3913            this.refresh_inline_completion(true, false, cx);
 3914        });
 3915
 3916        let show_new_completions_on_confirm = completion
 3917            .confirm
 3918            .as_ref()
 3919            .map_or(false, |confirm| confirm(intent, cx));
 3920        if show_new_completions_on_confirm {
 3921            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3922        }
 3923
 3924        let provider = self.completion_provider.as_ref()?;
 3925        let apply_edits = provider.apply_additional_edits_for_completion(
 3926            buffer_handle,
 3927            completion.clone(),
 3928            true,
 3929            cx,
 3930        );
 3931
 3932        let editor_settings = EditorSettings::get_global(cx);
 3933        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3934            // After the code completion is finished, users often want to know what signatures are needed.
 3935            // so we should automatically call signature_help
 3936            self.show_signature_help(&ShowSignatureHelp, cx);
 3937        }
 3938
 3939        Some(cx.foreground_executor().spawn(async move {
 3940            apply_edits.await?;
 3941            Ok(())
 3942        }))
 3943    }
 3944
 3945    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3946        let mut context_menu = self.context_menu.write();
 3947        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 3948            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 3949                // Toggle if we're selecting the same one
 3950                *context_menu = None;
 3951                cx.notify();
 3952                return;
 3953            } else {
 3954                // Otherwise, clear it and start a new one
 3955                *context_menu = None;
 3956                cx.notify();
 3957            }
 3958        }
 3959        drop(context_menu);
 3960        let snapshot = self.snapshot(cx);
 3961        let deployed_from_indicator = action.deployed_from_indicator;
 3962        let mut task = self.code_actions_task.take();
 3963        let action = action.clone();
 3964        cx.spawn(|editor, mut cx| async move {
 3965            while let Some(prev_task) = task {
 3966                prev_task.await.log_err();
 3967                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 3968            }
 3969
 3970            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 3971                if editor.focus_handle.is_focused(cx) {
 3972                    let multibuffer_point = action
 3973                        .deployed_from_indicator
 3974                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 3975                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 3976                    let (buffer, buffer_row) = snapshot
 3977                        .buffer_snapshot
 3978                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 3979                        .and_then(|(buffer_snapshot, range)| {
 3980                            editor
 3981                                .buffer
 3982                                .read(cx)
 3983                                .buffer(buffer_snapshot.remote_id())
 3984                                .map(|buffer| (buffer, range.start.row))
 3985                        })?;
 3986                    let (_, code_actions) = editor
 3987                        .available_code_actions
 3988                        .clone()
 3989                        .and_then(|(location, code_actions)| {
 3990                            let snapshot = location.buffer.read(cx).snapshot();
 3991                            let point_range = location.range.to_point(&snapshot);
 3992                            let point_range = point_range.start.row..=point_range.end.row;
 3993                            if point_range.contains(&buffer_row) {
 3994                                Some((location, code_actions))
 3995                            } else {
 3996                                None
 3997                            }
 3998                        })
 3999                        .unzip();
 4000                    let buffer_id = buffer.read(cx).remote_id();
 4001                    let tasks = editor
 4002                        .tasks
 4003                        .get(&(buffer_id, buffer_row))
 4004                        .map(|t| Arc::new(t.to_owned()));
 4005                    if tasks.is_none() && code_actions.is_none() {
 4006                        return None;
 4007                    }
 4008
 4009                    editor.completion_tasks.clear();
 4010                    editor.discard_inline_completion(false, cx);
 4011                    let task_context =
 4012                        tasks
 4013                            .as_ref()
 4014                            .zip(editor.project.clone())
 4015                            .map(|(tasks, project)| {
 4016                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4017                            });
 4018
 4019                    Some(cx.spawn(|editor, mut cx| async move {
 4020                        let task_context = match task_context {
 4021                            Some(task_context) => task_context.await,
 4022                            None => None,
 4023                        };
 4024                        let resolved_tasks =
 4025                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4026                                Arc::new(ResolvedTasks {
 4027                                    templates: tasks.resolve(&task_context).collect(),
 4028                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4029                                        multibuffer_point.row,
 4030                                        tasks.column,
 4031                                    )),
 4032                                })
 4033                            });
 4034                        let spawn_straight_away = resolved_tasks
 4035                            .as_ref()
 4036                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4037                            && code_actions
 4038                                .as_ref()
 4039                                .map_or(true, |actions| actions.is_empty());
 4040                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4041                            *editor.context_menu.write() =
 4042                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4043                                    buffer,
 4044                                    actions: CodeActionContents {
 4045                                        tasks: resolved_tasks,
 4046                                        actions: code_actions,
 4047                                    },
 4048                                    selected_item: Default::default(),
 4049                                    scroll_handle: UniformListScrollHandle::default(),
 4050                                    deployed_from_indicator,
 4051                                }));
 4052                            if spawn_straight_away {
 4053                                if let Some(task) = editor.confirm_code_action(
 4054                                    &ConfirmCodeAction { item_ix: Some(0) },
 4055                                    cx,
 4056                                ) {
 4057                                    cx.notify();
 4058                                    return task;
 4059                                }
 4060                            }
 4061                            cx.notify();
 4062                            Task::ready(Ok(()))
 4063                        }) {
 4064                            task.await
 4065                        } else {
 4066                            Ok(())
 4067                        }
 4068                    }))
 4069                } else {
 4070                    Some(Task::ready(Ok(())))
 4071                }
 4072            })?;
 4073            if let Some(task) = spawned_test_task {
 4074                task.await?;
 4075            }
 4076
 4077            Ok::<_, anyhow::Error>(())
 4078        })
 4079        .detach_and_log_err(cx);
 4080    }
 4081
 4082    pub fn confirm_code_action(
 4083        &mut self,
 4084        action: &ConfirmCodeAction,
 4085        cx: &mut ViewContext<Self>,
 4086    ) -> Option<Task<Result<()>>> {
 4087        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4088            menu
 4089        } else {
 4090            return None;
 4091        };
 4092        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4093        let action = actions_menu.actions.get(action_ix)?;
 4094        let title = action.label();
 4095        let buffer = actions_menu.buffer;
 4096        let workspace = self.workspace()?;
 4097
 4098        match action {
 4099            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4100                workspace.update(cx, |workspace, cx| {
 4101                    workspace::tasks::schedule_resolved_task(
 4102                        workspace,
 4103                        task_source_kind,
 4104                        resolved_task,
 4105                        false,
 4106                        cx,
 4107                    );
 4108
 4109                    Some(Task::ready(Ok(())))
 4110                })
 4111            }
 4112            CodeActionsItem::CodeAction {
 4113                excerpt_id,
 4114                action,
 4115                provider,
 4116            } => {
 4117                let apply_code_action =
 4118                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4119                let workspace = workspace.downgrade();
 4120                Some(cx.spawn(|editor, cx| async move {
 4121                    let project_transaction = apply_code_action.await?;
 4122                    Self::open_project_transaction(
 4123                        &editor,
 4124                        workspace,
 4125                        project_transaction,
 4126                        title,
 4127                        cx,
 4128                    )
 4129                    .await
 4130                }))
 4131            }
 4132        }
 4133    }
 4134
 4135    pub async fn open_project_transaction(
 4136        this: &WeakView<Editor>,
 4137        workspace: WeakView<Workspace>,
 4138        transaction: ProjectTransaction,
 4139        title: String,
 4140        mut cx: AsyncWindowContext,
 4141    ) -> Result<()> {
 4142        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4143        cx.update(|cx| {
 4144            entries.sort_unstable_by_key(|(buffer, _)| {
 4145                buffer.read(cx).file().map(|f| f.path().clone())
 4146            });
 4147        })?;
 4148
 4149        // If the project transaction's edits are all contained within this editor, then
 4150        // avoid opening a new editor to display them.
 4151
 4152        if let Some((buffer, transaction)) = entries.first() {
 4153            if entries.len() == 1 {
 4154                let excerpt = this.update(&mut cx, |editor, cx| {
 4155                    editor
 4156                        .buffer()
 4157                        .read(cx)
 4158                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4159                })?;
 4160                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4161                    if excerpted_buffer == *buffer {
 4162                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4163                            let excerpt_range = excerpt_range.to_offset(buffer);
 4164                            buffer
 4165                                .edited_ranges_for_transaction::<usize>(transaction)
 4166                                .all(|range| {
 4167                                    excerpt_range.start <= range.start
 4168                                        && excerpt_range.end >= range.end
 4169                                })
 4170                        })?;
 4171
 4172                        if all_edits_within_excerpt {
 4173                            return Ok(());
 4174                        }
 4175                    }
 4176                }
 4177            }
 4178        } else {
 4179            return Ok(());
 4180        }
 4181
 4182        let mut ranges_to_highlight = Vec::new();
 4183        let excerpt_buffer = cx.new_model(|cx| {
 4184            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4185            for (buffer_handle, transaction) in &entries {
 4186                let buffer = buffer_handle.read(cx);
 4187                ranges_to_highlight.extend(
 4188                    multibuffer.push_excerpts_with_context_lines(
 4189                        buffer_handle.clone(),
 4190                        buffer
 4191                            .edited_ranges_for_transaction::<usize>(transaction)
 4192                            .collect(),
 4193                        DEFAULT_MULTIBUFFER_CONTEXT,
 4194                        cx,
 4195                    ),
 4196                );
 4197            }
 4198            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4199            multibuffer
 4200        })?;
 4201
 4202        workspace.update(&mut cx, |workspace, cx| {
 4203            let project = workspace.project().clone();
 4204            let editor =
 4205                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4206            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4207            editor.update(cx, |editor, cx| {
 4208                editor.highlight_background::<Self>(
 4209                    &ranges_to_highlight,
 4210                    |theme| theme.editor_highlighted_line_background,
 4211                    cx,
 4212                );
 4213            });
 4214        })?;
 4215
 4216        Ok(())
 4217    }
 4218
 4219    pub fn clear_code_action_providers(&mut self) {
 4220        self.code_action_providers.clear();
 4221        self.available_code_actions.take();
 4222    }
 4223
 4224    pub fn push_code_action_provider(
 4225        &mut self,
 4226        provider: Arc<dyn CodeActionProvider>,
 4227        cx: &mut ViewContext<Self>,
 4228    ) {
 4229        self.code_action_providers.push(provider);
 4230        self.refresh_code_actions(cx);
 4231    }
 4232
 4233    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4234        let buffer = self.buffer.read(cx);
 4235        let newest_selection = self.selections.newest_anchor().clone();
 4236        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4237        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4238        if start_buffer != end_buffer {
 4239            return None;
 4240        }
 4241
 4242        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4243            cx.background_executor()
 4244                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4245                .await;
 4246
 4247            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4248                let providers = this.code_action_providers.clone();
 4249                let tasks = this
 4250                    .code_action_providers
 4251                    .iter()
 4252                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4253                    .collect::<Vec<_>>();
 4254                (providers, tasks)
 4255            })?;
 4256
 4257            let mut actions = Vec::new();
 4258            for (provider, provider_actions) in
 4259                providers.into_iter().zip(future::join_all(tasks).await)
 4260            {
 4261                if let Some(provider_actions) = provider_actions.log_err() {
 4262                    actions.extend(provider_actions.into_iter().map(|action| {
 4263                        AvailableCodeAction {
 4264                            excerpt_id: newest_selection.start.excerpt_id,
 4265                            action,
 4266                            provider: provider.clone(),
 4267                        }
 4268                    }));
 4269                }
 4270            }
 4271
 4272            this.update(&mut cx, |this, cx| {
 4273                this.available_code_actions = if actions.is_empty() {
 4274                    None
 4275                } else {
 4276                    Some((
 4277                        Location {
 4278                            buffer: start_buffer,
 4279                            range: start..end,
 4280                        },
 4281                        actions.into(),
 4282                    ))
 4283                };
 4284                cx.notify();
 4285            })
 4286        }));
 4287        None
 4288    }
 4289
 4290    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4291        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4292            self.show_git_blame_inline = false;
 4293
 4294            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4295                cx.background_executor().timer(delay).await;
 4296
 4297                this.update(&mut cx, |this, cx| {
 4298                    this.show_git_blame_inline = true;
 4299                    cx.notify();
 4300                })
 4301                .log_err();
 4302            }));
 4303        }
 4304    }
 4305
 4306    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4307        if self.pending_rename.is_some() {
 4308            return None;
 4309        }
 4310
 4311        let provider = self.semantics_provider.clone()?;
 4312        let buffer = self.buffer.read(cx);
 4313        let newest_selection = self.selections.newest_anchor().clone();
 4314        let cursor_position = newest_selection.head();
 4315        let (cursor_buffer, cursor_buffer_position) =
 4316            buffer.text_anchor_for_position(cursor_position, cx)?;
 4317        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4318        if cursor_buffer != tail_buffer {
 4319            return None;
 4320        }
 4321        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4322        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4323            cx.background_executor()
 4324                .timer(Duration::from_millis(debounce))
 4325                .await;
 4326
 4327            let highlights = if let Some(highlights) = cx
 4328                .update(|cx| {
 4329                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4330                })
 4331                .ok()
 4332                .flatten()
 4333            {
 4334                highlights.await.log_err()
 4335            } else {
 4336                None
 4337            };
 4338
 4339            if let Some(highlights) = highlights {
 4340                this.update(&mut cx, |this, cx| {
 4341                    if this.pending_rename.is_some() {
 4342                        return;
 4343                    }
 4344
 4345                    let buffer_id = cursor_position.buffer_id;
 4346                    let buffer = this.buffer.read(cx);
 4347                    if !buffer
 4348                        .text_anchor_for_position(cursor_position, cx)
 4349                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4350                    {
 4351                        return;
 4352                    }
 4353
 4354                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4355                    let mut write_ranges = Vec::new();
 4356                    let mut read_ranges = Vec::new();
 4357                    for highlight in highlights {
 4358                        for (excerpt_id, excerpt_range) in
 4359                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4360                        {
 4361                            let start = highlight
 4362                                .range
 4363                                .start
 4364                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4365                            let end = highlight
 4366                                .range
 4367                                .end
 4368                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4369                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4370                                continue;
 4371                            }
 4372
 4373                            let range = Anchor {
 4374                                buffer_id,
 4375                                excerpt_id,
 4376                                text_anchor: start,
 4377                            }..Anchor {
 4378                                buffer_id,
 4379                                excerpt_id,
 4380                                text_anchor: end,
 4381                            };
 4382                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4383                                write_ranges.push(range);
 4384                            } else {
 4385                                read_ranges.push(range);
 4386                            }
 4387                        }
 4388                    }
 4389
 4390                    this.highlight_background::<DocumentHighlightRead>(
 4391                        &read_ranges,
 4392                        |theme| theme.editor_document_highlight_read_background,
 4393                        cx,
 4394                    );
 4395                    this.highlight_background::<DocumentHighlightWrite>(
 4396                        &write_ranges,
 4397                        |theme| theme.editor_document_highlight_write_background,
 4398                        cx,
 4399                    );
 4400                    cx.notify();
 4401                })
 4402                .log_err();
 4403            }
 4404        }));
 4405        None
 4406    }
 4407
 4408    pub fn refresh_inline_completion(
 4409        &mut self,
 4410        debounce: bool,
 4411        user_requested: bool,
 4412        cx: &mut ViewContext<Self>,
 4413    ) -> Option<()> {
 4414        let provider = self.inline_completion_provider()?;
 4415        let cursor = self.selections.newest_anchor().head();
 4416        let (buffer, cursor_buffer_position) =
 4417            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4418
 4419        if !user_requested
 4420            && (!self.enable_inline_completions
 4421                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4422                || !self.is_focused(cx))
 4423        {
 4424            self.discard_inline_completion(false, cx);
 4425            return None;
 4426        }
 4427
 4428        self.update_visible_inline_completion(cx);
 4429        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4430        Some(())
 4431    }
 4432
 4433    fn cycle_inline_completion(
 4434        &mut self,
 4435        direction: Direction,
 4436        cx: &mut ViewContext<Self>,
 4437    ) -> Option<()> {
 4438        let provider = self.inline_completion_provider()?;
 4439        let cursor = self.selections.newest_anchor().head();
 4440        let (buffer, cursor_buffer_position) =
 4441            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4442        if !self.enable_inline_completions
 4443            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4444        {
 4445            return None;
 4446        }
 4447
 4448        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4449        self.update_visible_inline_completion(cx);
 4450
 4451        Some(())
 4452    }
 4453
 4454    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4455        if !self.has_active_inline_completion() {
 4456            self.refresh_inline_completion(false, true, cx);
 4457            return;
 4458        }
 4459
 4460        self.update_visible_inline_completion(cx);
 4461    }
 4462
 4463    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4464        self.show_cursor_names(cx);
 4465    }
 4466
 4467    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4468        self.show_cursor_names = true;
 4469        cx.notify();
 4470        cx.spawn(|this, mut cx| async move {
 4471            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4472            this.update(&mut cx, |this, cx| {
 4473                this.show_cursor_names = false;
 4474                cx.notify()
 4475            })
 4476            .ok()
 4477        })
 4478        .detach();
 4479    }
 4480
 4481    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4482        if self.has_active_inline_completion() {
 4483            self.cycle_inline_completion(Direction::Next, cx);
 4484        } else {
 4485            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4486            if is_copilot_disabled {
 4487                cx.propagate();
 4488            }
 4489        }
 4490    }
 4491
 4492    pub fn previous_inline_completion(
 4493        &mut self,
 4494        _: &PreviousInlineCompletion,
 4495        cx: &mut ViewContext<Self>,
 4496    ) {
 4497        if self.has_active_inline_completion() {
 4498            self.cycle_inline_completion(Direction::Prev, cx);
 4499        } else {
 4500            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4501            if is_copilot_disabled {
 4502                cx.propagate();
 4503            }
 4504        }
 4505    }
 4506
 4507    pub fn accept_inline_completion(
 4508        &mut self,
 4509        _: &AcceptInlineCompletion,
 4510        cx: &mut ViewContext<Self>,
 4511    ) {
 4512        self.hide_context_menu(cx);
 4513
 4514        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4515            return;
 4516        };
 4517
 4518        self.report_inline_completion_event(true, cx);
 4519
 4520        match &active_inline_completion.completion {
 4521            InlineCompletion::Move(position) => {
 4522                let position = *position;
 4523                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4524                    selections.select_anchor_ranges([position..position]);
 4525                });
 4526            }
 4527            InlineCompletion::Edit(edits) => {
 4528                if let Some(provider) = self.inline_completion_provider() {
 4529                    provider.accept(cx);
 4530                }
 4531
 4532                let snapshot = self.buffer.read(cx).snapshot(cx);
 4533                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4534
 4535                self.buffer.update(cx, |buffer, cx| {
 4536                    buffer.edit(edits.iter().cloned(), None, cx)
 4537                });
 4538
 4539                self.change_selections(None, cx, |s| {
 4540                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4541                });
 4542
 4543                self.update_visible_inline_completion(cx);
 4544                if self.active_inline_completion.is_none() {
 4545                    self.refresh_inline_completion(true, true, cx);
 4546                }
 4547
 4548                cx.notify();
 4549            }
 4550        }
 4551    }
 4552
 4553    pub fn accept_partial_inline_completion(
 4554        &mut self,
 4555        _: &AcceptPartialInlineCompletion,
 4556        cx: &mut ViewContext<Self>,
 4557    ) {
 4558        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4559            return;
 4560        };
 4561        if self.selections.count() != 1 {
 4562            return;
 4563        }
 4564
 4565        self.report_inline_completion_event(true, cx);
 4566
 4567        match &active_inline_completion.completion {
 4568            InlineCompletion::Move(position) => {
 4569                let position = *position;
 4570                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4571                    selections.select_anchor_ranges([position..position]);
 4572                });
 4573            }
 4574            InlineCompletion::Edit(edits) => {
 4575                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4576                    let text = edits[0].1.as_str();
 4577                    let mut partial_completion = text
 4578                        .chars()
 4579                        .by_ref()
 4580                        .take_while(|c| c.is_alphabetic())
 4581                        .collect::<String>();
 4582                    if partial_completion.is_empty() {
 4583                        partial_completion = text
 4584                            .chars()
 4585                            .by_ref()
 4586                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4587                            .collect::<String>();
 4588                    }
 4589
 4590                    cx.emit(EditorEvent::InputHandled {
 4591                        utf16_range_to_replace: None,
 4592                        text: partial_completion.clone().into(),
 4593                    });
 4594
 4595                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4596
 4597                    self.refresh_inline_completion(true, true, cx);
 4598                    cx.notify();
 4599                }
 4600            }
 4601        }
 4602    }
 4603
 4604    fn discard_inline_completion(
 4605        &mut self,
 4606        should_report_inline_completion_event: bool,
 4607        cx: &mut ViewContext<Self>,
 4608    ) -> bool {
 4609        if should_report_inline_completion_event {
 4610            self.report_inline_completion_event(false, cx);
 4611        }
 4612
 4613        if let Some(provider) = self.inline_completion_provider() {
 4614            provider.discard(cx);
 4615        }
 4616
 4617        self.take_active_inline_completion(cx).is_some()
 4618    }
 4619
 4620    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4621        let Some(provider) = self.inline_completion_provider() else {
 4622            return;
 4623        };
 4624        let Some(project) = self.project.as_ref() else {
 4625            return;
 4626        };
 4627        let Some((_, buffer, _)) = self
 4628            .buffer
 4629            .read(cx)
 4630            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4631        else {
 4632            return;
 4633        };
 4634
 4635        let project = project.read(cx);
 4636        let extension = buffer
 4637            .read(cx)
 4638            .file()
 4639            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4640        project.client().telemetry().report_inline_completion_event(
 4641            provider.name().into(),
 4642            accepted,
 4643            extension,
 4644        );
 4645    }
 4646
 4647    pub fn has_active_inline_completion(&self) -> bool {
 4648        self.active_inline_completion.is_some()
 4649    }
 4650
 4651    fn take_active_inline_completion(
 4652        &mut self,
 4653        cx: &mut ViewContext<Self>,
 4654    ) -> Option<InlineCompletion> {
 4655        let active_inline_completion = self.active_inline_completion.take()?;
 4656        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4657        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4658        Some(active_inline_completion.completion)
 4659    }
 4660
 4661    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4662        let selection = self.selections.newest_anchor();
 4663        let cursor = selection.head();
 4664        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4665        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4666        let excerpt_id = cursor.excerpt_id;
 4667
 4668        if !offset_selection.is_empty()
 4669            || self
 4670                .active_inline_completion
 4671                .as_ref()
 4672                .map_or(false, |completion| {
 4673                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4674                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4675                    !invalidation_range.contains(&offset_selection.head())
 4676                })
 4677        {
 4678            self.discard_inline_completion(false, cx);
 4679            return None;
 4680        }
 4681
 4682        self.take_active_inline_completion(cx);
 4683        let provider = self.inline_completion_provider()?;
 4684
 4685        let (buffer, cursor_buffer_position) =
 4686            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4687
 4688        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4689        let edits = completion
 4690            .edits
 4691            .into_iter()
 4692            .map(|(range, new_text)| {
 4693                (
 4694                    multibuffer
 4695                        .anchor_in_excerpt(excerpt_id, range.start)
 4696                        .unwrap()
 4697                        ..multibuffer
 4698                            .anchor_in_excerpt(excerpt_id, range.end)
 4699                            .unwrap(),
 4700                    new_text,
 4701                )
 4702            })
 4703            .collect::<Vec<_>>();
 4704        if edits.is_empty() {
 4705            return None;
 4706        }
 4707
 4708        let first_edit_start = edits.first().unwrap().0.start;
 4709        let edit_start_row = first_edit_start
 4710            .to_point(&multibuffer)
 4711            .row
 4712            .saturating_sub(2);
 4713
 4714        let last_edit_end = edits.last().unwrap().0.end;
 4715        let edit_end_row = cmp::min(
 4716            multibuffer.max_point().row,
 4717            last_edit_end.to_point(&multibuffer).row + 2,
 4718        );
 4719
 4720        let cursor_row = cursor.to_point(&multibuffer).row;
 4721
 4722        let mut inlay_ids = Vec::new();
 4723        let invalidation_row_range;
 4724        let completion;
 4725        if cursor_row < edit_start_row {
 4726            invalidation_row_range = cursor_row..edit_end_row;
 4727            completion = InlineCompletion::Move(first_edit_start);
 4728        } else if cursor_row > edit_end_row {
 4729            invalidation_row_range = edit_start_row..cursor_row;
 4730            completion = InlineCompletion::Move(first_edit_start);
 4731        } else {
 4732            if edits
 4733                .iter()
 4734                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4735            {
 4736                let mut inlays = Vec::new();
 4737                for (range, new_text) in &edits {
 4738                    let inlay = Inlay::suggestion(
 4739                        post_inc(&mut self.next_inlay_id),
 4740                        range.start,
 4741                        new_text.as_str(),
 4742                    );
 4743                    inlay_ids.push(inlay.id);
 4744                    inlays.push(inlay);
 4745                }
 4746
 4747                self.splice_inlays(vec![], inlays, cx);
 4748            } else {
 4749                let background_color = cx.theme().status().deleted_background;
 4750                self.highlight_text::<InlineCompletionHighlight>(
 4751                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4752                    HighlightStyle {
 4753                        background_color: Some(background_color),
 4754                        ..Default::default()
 4755                    },
 4756                    cx,
 4757                );
 4758            }
 4759
 4760            invalidation_row_range = edit_start_row..edit_end_row;
 4761            completion = InlineCompletion::Edit(edits);
 4762        };
 4763
 4764        let invalidation_range = multibuffer
 4765            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4766            ..multibuffer.anchor_after(Point::new(
 4767                invalidation_row_range.end,
 4768                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4769            ));
 4770
 4771        self.active_inline_completion = Some(InlineCompletionState {
 4772            inlay_ids,
 4773            completion,
 4774            invalidation_range,
 4775        });
 4776        cx.notify();
 4777
 4778        Some(())
 4779    }
 4780
 4781    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4782        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4783    }
 4784
 4785    fn render_code_actions_indicator(
 4786        &self,
 4787        _style: &EditorStyle,
 4788        row: DisplayRow,
 4789        is_active: bool,
 4790        cx: &mut ViewContext<Self>,
 4791    ) -> Option<IconButton> {
 4792        if self.available_code_actions.is_some() {
 4793            Some(
 4794                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4795                    .shape(ui::IconButtonShape::Square)
 4796                    .icon_size(IconSize::XSmall)
 4797                    .icon_color(Color::Muted)
 4798                    .selected(is_active)
 4799                    .tooltip({
 4800                        let focus_handle = self.focus_handle.clone();
 4801                        move |cx| {
 4802                            Tooltip::for_action_in(
 4803                                "Toggle Code Actions",
 4804                                &ToggleCodeActions {
 4805                                    deployed_from_indicator: None,
 4806                                },
 4807                                &focus_handle,
 4808                                cx,
 4809                            )
 4810                        }
 4811                    })
 4812                    .on_click(cx.listener(move |editor, _e, cx| {
 4813                        editor.focus(cx);
 4814                        editor.toggle_code_actions(
 4815                            &ToggleCodeActions {
 4816                                deployed_from_indicator: Some(row),
 4817                            },
 4818                            cx,
 4819                        );
 4820                    })),
 4821            )
 4822        } else {
 4823            None
 4824        }
 4825    }
 4826
 4827    fn clear_tasks(&mut self) {
 4828        self.tasks.clear()
 4829    }
 4830
 4831    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4832        if self.tasks.insert(key, value).is_some() {
 4833            // This case should hopefully be rare, but just in case...
 4834            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4835        }
 4836    }
 4837
 4838    fn build_tasks_context(
 4839        project: &Model<Project>,
 4840        buffer: &Model<Buffer>,
 4841        buffer_row: u32,
 4842        tasks: &Arc<RunnableTasks>,
 4843        cx: &mut ViewContext<Self>,
 4844    ) -> Task<Option<task::TaskContext>> {
 4845        let position = Point::new(buffer_row, tasks.column);
 4846        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4847        let location = Location {
 4848            buffer: buffer.clone(),
 4849            range: range_start..range_start,
 4850        };
 4851        // Fill in the environmental variables from the tree-sitter captures
 4852        let mut captured_task_variables = TaskVariables::default();
 4853        for (capture_name, value) in tasks.extra_variables.clone() {
 4854            captured_task_variables.insert(
 4855                task::VariableName::Custom(capture_name.into()),
 4856                value.clone(),
 4857            );
 4858        }
 4859        project.update(cx, |project, cx| {
 4860            project.task_store().update(cx, |task_store, cx| {
 4861                task_store.task_context_for_location(captured_task_variables, location, cx)
 4862            })
 4863        })
 4864    }
 4865
 4866    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4867        let Some((workspace, _)) = self.workspace.clone() else {
 4868            return;
 4869        };
 4870        let Some(project) = self.project.clone() else {
 4871            return;
 4872        };
 4873
 4874        // Try to find a closest, enclosing node using tree-sitter that has a
 4875        // task
 4876        let Some((buffer, buffer_row, tasks)) = self
 4877            .find_enclosing_node_task(cx)
 4878            // Or find the task that's closest in row-distance.
 4879            .or_else(|| self.find_closest_task(cx))
 4880        else {
 4881            return;
 4882        };
 4883
 4884        let reveal_strategy = action.reveal;
 4885        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 4886        cx.spawn(|_, mut cx| async move {
 4887            let context = task_context.await?;
 4888            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 4889
 4890            let resolved = resolved_task.resolved.as_mut()?;
 4891            resolved.reveal = reveal_strategy;
 4892
 4893            workspace
 4894                .update(&mut cx, |workspace, cx| {
 4895                    workspace::tasks::schedule_resolved_task(
 4896                        workspace,
 4897                        task_source_kind,
 4898                        resolved_task,
 4899                        false,
 4900                        cx,
 4901                    );
 4902                })
 4903                .ok()
 4904        })
 4905        .detach();
 4906    }
 4907
 4908    fn find_closest_task(
 4909        &mut self,
 4910        cx: &mut ViewContext<Self>,
 4911    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4912        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 4913
 4914        let ((buffer_id, row), tasks) = self
 4915            .tasks
 4916            .iter()
 4917            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 4918
 4919        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 4920        let tasks = Arc::new(tasks.to_owned());
 4921        Some((buffer, *row, tasks))
 4922    }
 4923
 4924    fn find_enclosing_node_task(
 4925        &mut self,
 4926        cx: &mut ViewContext<Self>,
 4927    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4928        let snapshot = self.buffer.read(cx).snapshot(cx);
 4929        let offset = self.selections.newest::<usize>(cx).head();
 4930        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 4931        let buffer_id = excerpt.buffer().remote_id();
 4932
 4933        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 4934        let mut cursor = layer.node().walk();
 4935
 4936        while cursor.goto_first_child_for_byte(offset).is_some() {
 4937            if cursor.node().end_byte() == offset {
 4938                cursor.goto_next_sibling();
 4939            }
 4940        }
 4941
 4942        // Ascend to the smallest ancestor that contains the range and has a task.
 4943        loop {
 4944            let node = cursor.node();
 4945            let node_range = node.byte_range();
 4946            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 4947
 4948            // Check if this node contains our offset
 4949            if node_range.start <= offset && node_range.end >= offset {
 4950                // If it contains offset, check for task
 4951                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 4952                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 4953                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 4954                }
 4955            }
 4956
 4957            if !cursor.goto_parent() {
 4958                break;
 4959            }
 4960        }
 4961        None
 4962    }
 4963
 4964    fn render_run_indicator(
 4965        &self,
 4966        _style: &EditorStyle,
 4967        is_active: bool,
 4968        row: DisplayRow,
 4969        cx: &mut ViewContext<Self>,
 4970    ) -> IconButton {
 4971        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 4972            .shape(ui::IconButtonShape::Square)
 4973            .icon_size(IconSize::XSmall)
 4974            .icon_color(Color::Muted)
 4975            .selected(is_active)
 4976            .on_click(cx.listener(move |editor, _e, cx| {
 4977                editor.focus(cx);
 4978                editor.toggle_code_actions(
 4979                    &ToggleCodeActions {
 4980                        deployed_from_indicator: Some(row),
 4981                    },
 4982                    cx,
 4983                );
 4984            }))
 4985    }
 4986
 4987    pub fn context_menu_visible(&self) -> bool {
 4988        self.context_menu
 4989            .read()
 4990            .as_ref()
 4991            .map_or(false, |menu| menu.visible())
 4992    }
 4993
 4994    fn render_context_menu(
 4995        &self,
 4996        cursor_position: DisplayPoint,
 4997        style: &EditorStyle,
 4998        max_height: Pixels,
 4999        cx: &mut ViewContext<Editor>,
 5000    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5001        self.context_menu.read().as_ref().map(|menu| {
 5002            menu.render(
 5003                cursor_position,
 5004                style,
 5005                max_height,
 5006                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5007                cx,
 5008            )
 5009        })
 5010    }
 5011
 5012    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5013        cx.notify();
 5014        self.completion_tasks.clear();
 5015        self.context_menu.write().take()
 5016    }
 5017
 5018    fn show_snippet_choices(
 5019        &mut self,
 5020        choices: &Vec<String>,
 5021        selection: Range<Anchor>,
 5022        cx: &mut ViewContext<Self>,
 5023    ) {
 5024        if selection.start.buffer_id.is_none() {
 5025            return;
 5026        }
 5027        let buffer_id = selection.start.buffer_id.unwrap();
 5028        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5029        let id = post_inc(&mut self.next_completion_id);
 5030
 5031        if let Some(buffer) = buffer {
 5032            *self.context_menu.write() = Some(CodeContextMenu::Completions(
 5033                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5034            ));
 5035        }
 5036    }
 5037
 5038    pub fn insert_snippet(
 5039        &mut self,
 5040        insertion_ranges: &[Range<usize>],
 5041        snippet: Snippet,
 5042        cx: &mut ViewContext<Self>,
 5043    ) -> Result<()> {
 5044        struct Tabstop<T> {
 5045            is_end_tabstop: bool,
 5046            ranges: Vec<Range<T>>,
 5047            choices: Option<Vec<String>>,
 5048        }
 5049
 5050        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5051            let snippet_text: Arc<str> = snippet.text.clone().into();
 5052            buffer.edit(
 5053                insertion_ranges
 5054                    .iter()
 5055                    .cloned()
 5056                    .map(|range| (range, snippet_text.clone())),
 5057                Some(AutoindentMode::EachLine),
 5058                cx,
 5059            );
 5060
 5061            let snapshot = &*buffer.read(cx);
 5062            let snippet = &snippet;
 5063            snippet
 5064                .tabstops
 5065                .iter()
 5066                .map(|tabstop| {
 5067                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5068                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5069                    });
 5070                    let mut tabstop_ranges = tabstop
 5071                        .ranges
 5072                        .iter()
 5073                        .flat_map(|tabstop_range| {
 5074                            let mut delta = 0_isize;
 5075                            insertion_ranges.iter().map(move |insertion_range| {
 5076                                let insertion_start = insertion_range.start as isize + delta;
 5077                                delta +=
 5078                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5079
 5080                                let start = ((insertion_start + tabstop_range.start) as usize)
 5081                                    .min(snapshot.len());
 5082                                let end = ((insertion_start + tabstop_range.end) as usize)
 5083                                    .min(snapshot.len());
 5084                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5085                            })
 5086                        })
 5087                        .collect::<Vec<_>>();
 5088                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5089
 5090                    Tabstop {
 5091                        is_end_tabstop,
 5092                        ranges: tabstop_ranges,
 5093                        choices: tabstop.choices.clone(),
 5094                    }
 5095                })
 5096                .collect::<Vec<_>>()
 5097        });
 5098        if let Some(tabstop) = tabstops.first() {
 5099            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5100                s.select_ranges(tabstop.ranges.iter().cloned());
 5101            });
 5102
 5103            if let Some(choices) = &tabstop.choices {
 5104                if let Some(selection) = tabstop.ranges.first() {
 5105                    self.show_snippet_choices(choices, selection.clone(), cx)
 5106                }
 5107            }
 5108
 5109            // If we're already at the last tabstop and it's at the end of the snippet,
 5110            // we're done, we don't need to keep the state around.
 5111            if !tabstop.is_end_tabstop {
 5112                let choices = tabstops
 5113                    .iter()
 5114                    .map(|tabstop| tabstop.choices.clone())
 5115                    .collect();
 5116
 5117                let ranges = tabstops
 5118                    .into_iter()
 5119                    .map(|tabstop| tabstop.ranges)
 5120                    .collect::<Vec<_>>();
 5121
 5122                self.snippet_stack.push(SnippetState {
 5123                    active_index: 0,
 5124                    ranges,
 5125                    choices,
 5126                });
 5127            }
 5128
 5129            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5130            if self.autoclose_regions.is_empty() {
 5131                let snapshot = self.buffer.read(cx).snapshot(cx);
 5132                for selection in &mut self.selections.all::<Point>(cx) {
 5133                    let selection_head = selection.head();
 5134                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5135                        continue;
 5136                    };
 5137
 5138                    let mut bracket_pair = None;
 5139                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5140                    let prev_chars = snapshot
 5141                        .reversed_chars_at(selection_head)
 5142                        .collect::<String>();
 5143                    for (pair, enabled) in scope.brackets() {
 5144                        if enabled
 5145                            && pair.close
 5146                            && prev_chars.starts_with(pair.start.as_str())
 5147                            && next_chars.starts_with(pair.end.as_str())
 5148                        {
 5149                            bracket_pair = Some(pair.clone());
 5150                            break;
 5151                        }
 5152                    }
 5153                    if let Some(pair) = bracket_pair {
 5154                        let start = snapshot.anchor_after(selection_head);
 5155                        let end = snapshot.anchor_after(selection_head);
 5156                        self.autoclose_regions.push(AutocloseRegion {
 5157                            selection_id: selection.id,
 5158                            range: start..end,
 5159                            pair,
 5160                        });
 5161                    }
 5162                }
 5163            }
 5164        }
 5165        Ok(())
 5166    }
 5167
 5168    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5169        self.move_to_snippet_tabstop(Bias::Right, cx)
 5170    }
 5171
 5172    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5173        self.move_to_snippet_tabstop(Bias::Left, cx)
 5174    }
 5175
 5176    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5177        if let Some(mut snippet) = self.snippet_stack.pop() {
 5178            match bias {
 5179                Bias::Left => {
 5180                    if snippet.active_index > 0 {
 5181                        snippet.active_index -= 1;
 5182                    } else {
 5183                        self.snippet_stack.push(snippet);
 5184                        return false;
 5185                    }
 5186                }
 5187                Bias::Right => {
 5188                    if snippet.active_index + 1 < snippet.ranges.len() {
 5189                        snippet.active_index += 1;
 5190                    } else {
 5191                        self.snippet_stack.push(snippet);
 5192                        return false;
 5193                    }
 5194                }
 5195            }
 5196            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5197                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5198                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5199                });
 5200
 5201                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5202                    if let Some(selection) = current_ranges.first() {
 5203                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5204                    }
 5205                }
 5206
 5207                // If snippet state is not at the last tabstop, push it back on the stack
 5208                if snippet.active_index + 1 < snippet.ranges.len() {
 5209                    self.snippet_stack.push(snippet);
 5210                }
 5211                return true;
 5212            }
 5213        }
 5214
 5215        false
 5216    }
 5217
 5218    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5219        self.transact(cx, |this, cx| {
 5220            this.select_all(&SelectAll, cx);
 5221            this.insert("", cx);
 5222        });
 5223    }
 5224
 5225    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5226        self.transact(cx, |this, cx| {
 5227            this.select_autoclose_pair(cx);
 5228            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5229            if !this.linked_edit_ranges.is_empty() {
 5230                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5231                let snapshot = this.buffer.read(cx).snapshot(cx);
 5232
 5233                for selection in selections.iter() {
 5234                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5235                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5236                    if selection_start.buffer_id != selection_end.buffer_id {
 5237                        continue;
 5238                    }
 5239                    if let Some(ranges) =
 5240                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5241                    {
 5242                        for (buffer, entries) in ranges {
 5243                            linked_ranges.entry(buffer).or_default().extend(entries);
 5244                        }
 5245                    }
 5246                }
 5247            }
 5248
 5249            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5250            if !this.selections.line_mode {
 5251                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5252                for selection in &mut selections {
 5253                    if selection.is_empty() {
 5254                        let old_head = selection.head();
 5255                        let mut new_head =
 5256                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5257                                .to_point(&display_map);
 5258                        if let Some((buffer, line_buffer_range)) = display_map
 5259                            .buffer_snapshot
 5260                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5261                        {
 5262                            let indent_size =
 5263                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5264                            let indent_len = match indent_size.kind {
 5265                                IndentKind::Space => {
 5266                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5267                                }
 5268                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5269                            };
 5270                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5271                                let indent_len = indent_len.get();
 5272                                new_head = cmp::min(
 5273                                    new_head,
 5274                                    MultiBufferPoint::new(
 5275                                        old_head.row,
 5276                                        ((old_head.column - 1) / indent_len) * indent_len,
 5277                                    ),
 5278                                );
 5279                            }
 5280                        }
 5281
 5282                        selection.set_head(new_head, SelectionGoal::None);
 5283                    }
 5284                }
 5285            }
 5286
 5287            this.signature_help_state.set_backspace_pressed(true);
 5288            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5289            this.insert("", cx);
 5290            let empty_str: Arc<str> = Arc::from("");
 5291            for (buffer, edits) in linked_ranges {
 5292                let snapshot = buffer.read(cx).snapshot();
 5293                use text::ToPoint as TP;
 5294
 5295                let edits = edits
 5296                    .into_iter()
 5297                    .map(|range| {
 5298                        let end_point = TP::to_point(&range.end, &snapshot);
 5299                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5300
 5301                        if end_point == start_point {
 5302                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5303                                .saturating_sub(1);
 5304                            start_point = TP::to_point(&offset, &snapshot);
 5305                        };
 5306
 5307                        (start_point..end_point, empty_str.clone())
 5308                    })
 5309                    .sorted_by_key(|(range, _)| range.start)
 5310                    .collect::<Vec<_>>();
 5311                buffer.update(cx, |this, cx| {
 5312                    this.edit(edits, None, cx);
 5313                })
 5314            }
 5315            this.refresh_inline_completion(true, false, cx);
 5316            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5317        });
 5318    }
 5319
 5320    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5321        self.transact(cx, |this, cx| {
 5322            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5323                let line_mode = s.line_mode;
 5324                s.move_with(|map, selection| {
 5325                    if selection.is_empty() && !line_mode {
 5326                        let cursor = movement::right(map, selection.head());
 5327                        selection.end = cursor;
 5328                        selection.reversed = true;
 5329                        selection.goal = SelectionGoal::None;
 5330                    }
 5331                })
 5332            });
 5333            this.insert("", cx);
 5334            this.refresh_inline_completion(true, false, cx);
 5335        });
 5336    }
 5337
 5338    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5339        if self.move_to_prev_snippet_tabstop(cx) {
 5340            return;
 5341        }
 5342
 5343        self.outdent(&Outdent, cx);
 5344    }
 5345
 5346    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5347        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5348            return;
 5349        }
 5350
 5351        let mut selections = self.selections.all_adjusted(cx);
 5352        let buffer = self.buffer.read(cx);
 5353        let snapshot = buffer.snapshot(cx);
 5354        let rows_iter = selections.iter().map(|s| s.head().row);
 5355        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5356
 5357        let mut edits = Vec::new();
 5358        let mut prev_edited_row = 0;
 5359        let mut row_delta = 0;
 5360        for selection in &mut selections {
 5361            if selection.start.row != prev_edited_row {
 5362                row_delta = 0;
 5363            }
 5364            prev_edited_row = selection.end.row;
 5365
 5366            // If the selection is non-empty, then increase the indentation of the selected lines.
 5367            if !selection.is_empty() {
 5368                row_delta =
 5369                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5370                continue;
 5371            }
 5372
 5373            // If the selection is empty and the cursor is in the leading whitespace before the
 5374            // suggested indentation, then auto-indent the line.
 5375            let cursor = selection.head();
 5376            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5377            if let Some(suggested_indent) =
 5378                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5379            {
 5380                if cursor.column < suggested_indent.len
 5381                    && cursor.column <= current_indent.len
 5382                    && current_indent.len <= suggested_indent.len
 5383                {
 5384                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5385                    selection.end = selection.start;
 5386                    if row_delta == 0 {
 5387                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5388                            cursor.row,
 5389                            current_indent,
 5390                            suggested_indent,
 5391                        ));
 5392                        row_delta = suggested_indent.len - current_indent.len;
 5393                    }
 5394                    continue;
 5395                }
 5396            }
 5397
 5398            // Otherwise, insert a hard or soft tab.
 5399            let settings = buffer.settings_at(cursor, cx);
 5400            let tab_size = if settings.hard_tabs {
 5401                IndentSize::tab()
 5402            } else {
 5403                let tab_size = settings.tab_size.get();
 5404                let char_column = snapshot
 5405                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5406                    .flat_map(str::chars)
 5407                    .count()
 5408                    + row_delta as usize;
 5409                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5410                IndentSize::spaces(chars_to_next_tab_stop)
 5411            };
 5412            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5413            selection.end = selection.start;
 5414            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5415            row_delta += tab_size.len;
 5416        }
 5417
 5418        self.transact(cx, |this, cx| {
 5419            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5420            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5421            this.refresh_inline_completion(true, false, cx);
 5422        });
 5423    }
 5424
 5425    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5426        if self.read_only(cx) {
 5427            return;
 5428        }
 5429        let mut selections = self.selections.all::<Point>(cx);
 5430        let mut prev_edited_row = 0;
 5431        let mut row_delta = 0;
 5432        let mut edits = Vec::new();
 5433        let buffer = self.buffer.read(cx);
 5434        let snapshot = buffer.snapshot(cx);
 5435        for selection in &mut selections {
 5436            if selection.start.row != prev_edited_row {
 5437                row_delta = 0;
 5438            }
 5439            prev_edited_row = selection.end.row;
 5440
 5441            row_delta =
 5442                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5443        }
 5444
 5445        self.transact(cx, |this, cx| {
 5446            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5447            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5448        });
 5449    }
 5450
 5451    fn indent_selection(
 5452        buffer: &MultiBuffer,
 5453        snapshot: &MultiBufferSnapshot,
 5454        selection: &mut Selection<Point>,
 5455        edits: &mut Vec<(Range<Point>, String)>,
 5456        delta_for_start_row: u32,
 5457        cx: &AppContext,
 5458    ) -> u32 {
 5459        let settings = buffer.settings_at(selection.start, cx);
 5460        let tab_size = settings.tab_size.get();
 5461        let indent_kind = if settings.hard_tabs {
 5462            IndentKind::Tab
 5463        } else {
 5464            IndentKind::Space
 5465        };
 5466        let mut start_row = selection.start.row;
 5467        let mut end_row = selection.end.row + 1;
 5468
 5469        // If a selection ends at the beginning of a line, don't indent
 5470        // that last line.
 5471        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5472            end_row -= 1;
 5473        }
 5474
 5475        // Avoid re-indenting a row that has already been indented by a
 5476        // previous selection, but still update this selection's column
 5477        // to reflect that indentation.
 5478        if delta_for_start_row > 0 {
 5479            start_row += 1;
 5480            selection.start.column += delta_for_start_row;
 5481            if selection.end.row == selection.start.row {
 5482                selection.end.column += delta_for_start_row;
 5483            }
 5484        }
 5485
 5486        let mut delta_for_end_row = 0;
 5487        let has_multiple_rows = start_row + 1 != end_row;
 5488        for row in start_row..end_row {
 5489            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5490            let indent_delta = match (current_indent.kind, indent_kind) {
 5491                (IndentKind::Space, IndentKind::Space) => {
 5492                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5493                    IndentSize::spaces(columns_to_next_tab_stop)
 5494                }
 5495                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5496                (_, IndentKind::Tab) => IndentSize::tab(),
 5497            };
 5498
 5499            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5500                0
 5501            } else {
 5502                selection.start.column
 5503            };
 5504            let row_start = Point::new(row, start);
 5505            edits.push((
 5506                row_start..row_start,
 5507                indent_delta.chars().collect::<String>(),
 5508            ));
 5509
 5510            // Update this selection's endpoints to reflect the indentation.
 5511            if row == selection.start.row {
 5512                selection.start.column += indent_delta.len;
 5513            }
 5514            if row == selection.end.row {
 5515                selection.end.column += indent_delta.len;
 5516                delta_for_end_row = indent_delta.len;
 5517            }
 5518        }
 5519
 5520        if selection.start.row == selection.end.row {
 5521            delta_for_start_row + delta_for_end_row
 5522        } else {
 5523            delta_for_end_row
 5524        }
 5525    }
 5526
 5527    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5528        if self.read_only(cx) {
 5529            return;
 5530        }
 5531        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5532        let selections = self.selections.all::<Point>(cx);
 5533        let mut deletion_ranges = Vec::new();
 5534        let mut last_outdent = None;
 5535        {
 5536            let buffer = self.buffer.read(cx);
 5537            let snapshot = buffer.snapshot(cx);
 5538            for selection in &selections {
 5539                let settings = buffer.settings_at(selection.start, cx);
 5540                let tab_size = settings.tab_size.get();
 5541                let mut rows = selection.spanned_rows(false, &display_map);
 5542
 5543                // Avoid re-outdenting a row that has already been outdented by a
 5544                // previous selection.
 5545                if let Some(last_row) = last_outdent {
 5546                    if last_row == rows.start {
 5547                        rows.start = rows.start.next_row();
 5548                    }
 5549                }
 5550                let has_multiple_rows = rows.len() > 1;
 5551                for row in rows.iter_rows() {
 5552                    let indent_size = snapshot.indent_size_for_line(row);
 5553                    if indent_size.len > 0 {
 5554                        let deletion_len = match indent_size.kind {
 5555                            IndentKind::Space => {
 5556                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5557                                if columns_to_prev_tab_stop == 0 {
 5558                                    tab_size
 5559                                } else {
 5560                                    columns_to_prev_tab_stop
 5561                                }
 5562                            }
 5563                            IndentKind::Tab => 1,
 5564                        };
 5565                        let start = if has_multiple_rows
 5566                            || deletion_len > selection.start.column
 5567                            || indent_size.len < selection.start.column
 5568                        {
 5569                            0
 5570                        } else {
 5571                            selection.start.column - deletion_len
 5572                        };
 5573                        deletion_ranges.push(
 5574                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5575                        );
 5576                        last_outdent = Some(row);
 5577                    }
 5578                }
 5579            }
 5580        }
 5581
 5582        self.transact(cx, |this, cx| {
 5583            this.buffer.update(cx, |buffer, cx| {
 5584                let empty_str: Arc<str> = Arc::default();
 5585                buffer.edit(
 5586                    deletion_ranges
 5587                        .into_iter()
 5588                        .map(|range| (range, empty_str.clone())),
 5589                    None,
 5590                    cx,
 5591                );
 5592            });
 5593            let selections = this.selections.all::<usize>(cx);
 5594            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5595        });
 5596    }
 5597
 5598    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5599        if self.read_only(cx) {
 5600            return;
 5601        }
 5602        let selections = self
 5603            .selections
 5604            .all::<usize>(cx)
 5605            .into_iter()
 5606            .map(|s| s.range());
 5607
 5608        self.transact(cx, |this, cx| {
 5609            this.buffer.update(cx, |buffer, cx| {
 5610                buffer.autoindent_ranges(selections, cx);
 5611            });
 5612            let selections = this.selections.all::<usize>(cx);
 5613            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5614        });
 5615    }
 5616
 5617    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5618        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5619        let selections = self.selections.all::<Point>(cx);
 5620
 5621        let mut new_cursors = Vec::new();
 5622        let mut edit_ranges = Vec::new();
 5623        let mut selections = selections.iter().peekable();
 5624        while let Some(selection) = selections.next() {
 5625            let mut rows = selection.spanned_rows(false, &display_map);
 5626            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5627
 5628            // Accumulate contiguous regions of rows that we want to delete.
 5629            while let Some(next_selection) = selections.peek() {
 5630                let next_rows = next_selection.spanned_rows(false, &display_map);
 5631                if next_rows.start <= rows.end {
 5632                    rows.end = next_rows.end;
 5633                    selections.next().unwrap();
 5634                } else {
 5635                    break;
 5636                }
 5637            }
 5638
 5639            let buffer = &display_map.buffer_snapshot;
 5640            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5641            let edit_end;
 5642            let cursor_buffer_row;
 5643            if buffer.max_point().row >= rows.end.0 {
 5644                // If there's a line after the range, delete the \n from the end of the row range
 5645                // and position the cursor on the next line.
 5646                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5647                cursor_buffer_row = rows.end;
 5648            } else {
 5649                // If there isn't a line after the range, delete the \n from the line before the
 5650                // start of the row range and position the cursor there.
 5651                edit_start = edit_start.saturating_sub(1);
 5652                edit_end = buffer.len();
 5653                cursor_buffer_row = rows.start.previous_row();
 5654            }
 5655
 5656            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5657            *cursor.column_mut() =
 5658                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5659
 5660            new_cursors.push((
 5661                selection.id,
 5662                buffer.anchor_after(cursor.to_point(&display_map)),
 5663            ));
 5664            edit_ranges.push(edit_start..edit_end);
 5665        }
 5666
 5667        self.transact(cx, |this, cx| {
 5668            let buffer = this.buffer.update(cx, |buffer, cx| {
 5669                let empty_str: Arc<str> = Arc::default();
 5670                buffer.edit(
 5671                    edit_ranges
 5672                        .into_iter()
 5673                        .map(|range| (range, empty_str.clone())),
 5674                    None,
 5675                    cx,
 5676                );
 5677                buffer.snapshot(cx)
 5678            });
 5679            let new_selections = new_cursors
 5680                .into_iter()
 5681                .map(|(id, cursor)| {
 5682                    let cursor = cursor.to_point(&buffer);
 5683                    Selection {
 5684                        id,
 5685                        start: cursor,
 5686                        end: cursor,
 5687                        reversed: false,
 5688                        goal: SelectionGoal::None,
 5689                    }
 5690                })
 5691                .collect();
 5692
 5693            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5694                s.select(new_selections);
 5695            });
 5696        });
 5697    }
 5698
 5699    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5700        if self.read_only(cx) {
 5701            return;
 5702        }
 5703        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5704        for selection in self.selections.all::<Point>(cx) {
 5705            let start = MultiBufferRow(selection.start.row);
 5706            // Treat single line selections as if they include the next line. Otherwise this action
 5707            // would do nothing for single line selections individual cursors.
 5708            let end = if selection.start.row == selection.end.row {
 5709                MultiBufferRow(selection.start.row + 1)
 5710            } else {
 5711                MultiBufferRow(selection.end.row)
 5712            };
 5713
 5714            if let Some(last_row_range) = row_ranges.last_mut() {
 5715                if start <= last_row_range.end {
 5716                    last_row_range.end = end;
 5717                    continue;
 5718                }
 5719            }
 5720            row_ranges.push(start..end);
 5721        }
 5722
 5723        let snapshot = self.buffer.read(cx).snapshot(cx);
 5724        let mut cursor_positions = Vec::new();
 5725        for row_range in &row_ranges {
 5726            let anchor = snapshot.anchor_before(Point::new(
 5727                row_range.end.previous_row().0,
 5728                snapshot.line_len(row_range.end.previous_row()),
 5729            ));
 5730            cursor_positions.push(anchor..anchor);
 5731        }
 5732
 5733        self.transact(cx, |this, cx| {
 5734            for row_range in row_ranges.into_iter().rev() {
 5735                for row in row_range.iter_rows().rev() {
 5736                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5737                    let next_line_row = row.next_row();
 5738                    let indent = snapshot.indent_size_for_line(next_line_row);
 5739                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5740
 5741                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5742                        " "
 5743                    } else {
 5744                        ""
 5745                    };
 5746
 5747                    this.buffer.update(cx, |buffer, cx| {
 5748                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5749                    });
 5750                }
 5751            }
 5752
 5753            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5754                s.select_anchor_ranges(cursor_positions)
 5755            });
 5756        });
 5757    }
 5758
 5759    pub fn sort_lines_case_sensitive(
 5760        &mut self,
 5761        _: &SortLinesCaseSensitive,
 5762        cx: &mut ViewContext<Self>,
 5763    ) {
 5764        self.manipulate_lines(cx, |lines| lines.sort())
 5765    }
 5766
 5767    pub fn sort_lines_case_insensitive(
 5768        &mut self,
 5769        _: &SortLinesCaseInsensitive,
 5770        cx: &mut ViewContext<Self>,
 5771    ) {
 5772        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5773    }
 5774
 5775    pub fn unique_lines_case_insensitive(
 5776        &mut self,
 5777        _: &UniqueLinesCaseInsensitive,
 5778        cx: &mut ViewContext<Self>,
 5779    ) {
 5780        self.manipulate_lines(cx, |lines| {
 5781            let mut seen = HashSet::default();
 5782            lines.retain(|line| seen.insert(line.to_lowercase()));
 5783        })
 5784    }
 5785
 5786    pub fn unique_lines_case_sensitive(
 5787        &mut self,
 5788        _: &UniqueLinesCaseSensitive,
 5789        cx: &mut ViewContext<Self>,
 5790    ) {
 5791        self.manipulate_lines(cx, |lines| {
 5792            let mut seen = HashSet::default();
 5793            lines.retain(|line| seen.insert(*line));
 5794        })
 5795    }
 5796
 5797    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5798        let mut revert_changes = HashMap::default();
 5799        let snapshot = self.snapshot(cx);
 5800        for hunk in hunks_for_ranges(
 5801            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5802            &snapshot,
 5803        ) {
 5804            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5805        }
 5806        if !revert_changes.is_empty() {
 5807            self.transact(cx, |editor, cx| {
 5808                editor.revert(revert_changes, cx);
 5809            });
 5810        }
 5811    }
 5812
 5813    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5814        let Some(project) = self.project.clone() else {
 5815            return;
 5816        };
 5817        self.reload(project, cx).detach_and_notify_err(cx);
 5818    }
 5819
 5820    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5821        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5822        if !revert_changes.is_empty() {
 5823            self.transact(cx, |editor, cx| {
 5824                editor.revert(revert_changes, cx);
 5825            });
 5826        }
 5827    }
 5828
 5829    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5830        let snapshot = self.buffer.read(cx).read(cx);
 5831        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5832            drop(snapshot);
 5833            let mut revert_changes = HashMap::default();
 5834            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5835            if !revert_changes.is_empty() {
 5836                self.revert(revert_changes, cx)
 5837            }
 5838        }
 5839    }
 5840
 5841    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5842        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5843            let project_path = buffer.read(cx).project_path(cx)?;
 5844            let project = self.project.as_ref()?.read(cx);
 5845            let entry = project.entry_for_path(&project_path, cx)?;
 5846            let parent = match &entry.canonical_path {
 5847                Some(canonical_path) => canonical_path.to_path_buf(),
 5848                None => project.absolute_path(&project_path, cx)?,
 5849            }
 5850            .parent()?
 5851            .to_path_buf();
 5852            Some(parent)
 5853        }) {
 5854            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5855        }
 5856    }
 5857
 5858    fn gather_revert_changes(
 5859        &mut self,
 5860        selections: &[Selection<Point>],
 5861        cx: &mut ViewContext<'_, Editor>,
 5862    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5863        let mut revert_changes = HashMap::default();
 5864        let snapshot = self.snapshot(cx);
 5865        for hunk in hunks_for_selections(&snapshot, selections) {
 5866            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5867        }
 5868        revert_changes
 5869    }
 5870
 5871    pub fn prepare_revert_change(
 5872        &mut self,
 5873        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5874        hunk: &MultiBufferDiffHunk,
 5875        cx: &AppContext,
 5876    ) -> Option<()> {
 5877        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 5878        let buffer = buffer.read(cx);
 5879        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 5880        let original_text = change_set
 5881            .read(cx)
 5882            .base_text
 5883            .as_ref()?
 5884            .read(cx)
 5885            .as_rope()
 5886            .slice(hunk.diff_base_byte_range.clone());
 5887        let buffer_snapshot = buffer.snapshot();
 5888        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5889        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5890            probe
 5891                .0
 5892                .start
 5893                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5894                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5895        }) {
 5896            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5897            Some(())
 5898        } else {
 5899            None
 5900        }
 5901    }
 5902
 5903    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5904        self.manipulate_lines(cx, |lines| lines.reverse())
 5905    }
 5906
 5907    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5908        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5909    }
 5910
 5911    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5912    where
 5913        Fn: FnMut(&mut Vec<&str>),
 5914    {
 5915        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5916        let buffer = self.buffer.read(cx).snapshot(cx);
 5917
 5918        let mut edits = Vec::new();
 5919
 5920        let selections = self.selections.all::<Point>(cx);
 5921        let mut selections = selections.iter().peekable();
 5922        let mut contiguous_row_selections = Vec::new();
 5923        let mut new_selections = Vec::new();
 5924        let mut added_lines = 0;
 5925        let mut removed_lines = 0;
 5926
 5927        while let Some(selection) = selections.next() {
 5928            let (start_row, end_row) = consume_contiguous_rows(
 5929                &mut contiguous_row_selections,
 5930                selection,
 5931                &display_map,
 5932                &mut selections,
 5933            );
 5934
 5935            let start_point = Point::new(start_row.0, 0);
 5936            let end_point = Point::new(
 5937                end_row.previous_row().0,
 5938                buffer.line_len(end_row.previous_row()),
 5939            );
 5940            let text = buffer
 5941                .text_for_range(start_point..end_point)
 5942                .collect::<String>();
 5943
 5944            let mut lines = text.split('\n').collect_vec();
 5945
 5946            let lines_before = lines.len();
 5947            callback(&mut lines);
 5948            let lines_after = lines.len();
 5949
 5950            edits.push((start_point..end_point, lines.join("\n")));
 5951
 5952            // Selections must change based on added and removed line count
 5953            let start_row =
 5954                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5955            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5956            new_selections.push(Selection {
 5957                id: selection.id,
 5958                start: start_row,
 5959                end: end_row,
 5960                goal: SelectionGoal::None,
 5961                reversed: selection.reversed,
 5962            });
 5963
 5964            if lines_after > lines_before {
 5965                added_lines += lines_after - lines_before;
 5966            } else if lines_before > lines_after {
 5967                removed_lines += lines_before - lines_after;
 5968            }
 5969        }
 5970
 5971        self.transact(cx, |this, cx| {
 5972            let buffer = this.buffer.update(cx, |buffer, cx| {
 5973                buffer.edit(edits, None, cx);
 5974                buffer.snapshot(cx)
 5975            });
 5976
 5977            // Recalculate offsets on newly edited buffer
 5978            let new_selections = new_selections
 5979                .iter()
 5980                .map(|s| {
 5981                    let start_point = Point::new(s.start.0, 0);
 5982                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 5983                    Selection {
 5984                        id: s.id,
 5985                        start: buffer.point_to_offset(start_point),
 5986                        end: buffer.point_to_offset(end_point),
 5987                        goal: s.goal,
 5988                        reversed: s.reversed,
 5989                    }
 5990                })
 5991                .collect();
 5992
 5993            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5994                s.select(new_selections);
 5995            });
 5996
 5997            this.request_autoscroll(Autoscroll::fit(), cx);
 5998        });
 5999    }
 6000
 6001    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6002        self.manipulate_text(cx, |text| text.to_uppercase())
 6003    }
 6004
 6005    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6006        self.manipulate_text(cx, |text| text.to_lowercase())
 6007    }
 6008
 6009    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6010        self.manipulate_text(cx, |text| {
 6011            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6012            // https://github.com/rutrum/convert-case/issues/16
 6013            text.split('\n')
 6014                .map(|line| line.to_case(Case::Title))
 6015                .join("\n")
 6016        })
 6017    }
 6018
 6019    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6020        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6021    }
 6022
 6023    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6024        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6025    }
 6026
 6027    pub fn convert_to_upper_camel_case(
 6028        &mut self,
 6029        _: &ConvertToUpperCamelCase,
 6030        cx: &mut ViewContext<Self>,
 6031    ) {
 6032        self.manipulate_text(cx, |text| {
 6033            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6034            // https://github.com/rutrum/convert-case/issues/16
 6035            text.split('\n')
 6036                .map(|line| line.to_case(Case::UpperCamel))
 6037                .join("\n")
 6038        })
 6039    }
 6040
 6041    pub fn convert_to_lower_camel_case(
 6042        &mut self,
 6043        _: &ConvertToLowerCamelCase,
 6044        cx: &mut ViewContext<Self>,
 6045    ) {
 6046        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6047    }
 6048
 6049    pub fn convert_to_opposite_case(
 6050        &mut self,
 6051        _: &ConvertToOppositeCase,
 6052        cx: &mut ViewContext<Self>,
 6053    ) {
 6054        self.manipulate_text(cx, |text| {
 6055            text.chars()
 6056                .fold(String::with_capacity(text.len()), |mut t, c| {
 6057                    if c.is_uppercase() {
 6058                        t.extend(c.to_lowercase());
 6059                    } else {
 6060                        t.extend(c.to_uppercase());
 6061                    }
 6062                    t
 6063                })
 6064        })
 6065    }
 6066
 6067    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6068    where
 6069        Fn: FnMut(&str) -> String,
 6070    {
 6071        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6072        let buffer = self.buffer.read(cx).snapshot(cx);
 6073
 6074        let mut new_selections = Vec::new();
 6075        let mut edits = Vec::new();
 6076        let mut selection_adjustment = 0i32;
 6077
 6078        for selection in self.selections.all::<usize>(cx) {
 6079            let selection_is_empty = selection.is_empty();
 6080
 6081            let (start, end) = if selection_is_empty {
 6082                let word_range = movement::surrounding_word(
 6083                    &display_map,
 6084                    selection.start.to_display_point(&display_map),
 6085                );
 6086                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6087                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6088                (start, end)
 6089            } else {
 6090                (selection.start, selection.end)
 6091            };
 6092
 6093            let text = buffer.text_for_range(start..end).collect::<String>();
 6094            let old_length = text.len() as i32;
 6095            let text = callback(&text);
 6096
 6097            new_selections.push(Selection {
 6098                start: (start as i32 - selection_adjustment) as usize,
 6099                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6100                goal: SelectionGoal::None,
 6101                ..selection
 6102            });
 6103
 6104            selection_adjustment += old_length - text.len() as i32;
 6105
 6106            edits.push((start..end, text));
 6107        }
 6108
 6109        self.transact(cx, |this, cx| {
 6110            this.buffer.update(cx, |buffer, cx| {
 6111                buffer.edit(edits, None, cx);
 6112            });
 6113
 6114            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6115                s.select(new_selections);
 6116            });
 6117
 6118            this.request_autoscroll(Autoscroll::fit(), cx);
 6119        });
 6120    }
 6121
 6122    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6123        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6124        let buffer = &display_map.buffer_snapshot;
 6125        let selections = self.selections.all::<Point>(cx);
 6126
 6127        let mut edits = Vec::new();
 6128        let mut selections_iter = selections.iter().peekable();
 6129        while let Some(selection) = selections_iter.next() {
 6130            // Avoid duplicating the same lines twice.
 6131            let mut rows = selection.spanned_rows(false, &display_map);
 6132
 6133            while let Some(next_selection) = selections_iter.peek() {
 6134                let next_rows = next_selection.spanned_rows(false, &display_map);
 6135                if next_rows.start < rows.end {
 6136                    rows.end = next_rows.end;
 6137                    selections_iter.next().unwrap();
 6138                } else {
 6139                    break;
 6140                }
 6141            }
 6142
 6143            // Copy the text from the selected row region and splice it either at the start
 6144            // or end of the region.
 6145            let start = Point::new(rows.start.0, 0);
 6146            let end = Point::new(
 6147                rows.end.previous_row().0,
 6148                buffer.line_len(rows.end.previous_row()),
 6149            );
 6150            let text = buffer
 6151                .text_for_range(start..end)
 6152                .chain(Some("\n"))
 6153                .collect::<String>();
 6154            let insert_location = if upwards {
 6155                Point::new(rows.end.0, 0)
 6156            } else {
 6157                start
 6158            };
 6159            edits.push((insert_location..insert_location, text));
 6160        }
 6161
 6162        self.transact(cx, |this, cx| {
 6163            this.buffer.update(cx, |buffer, cx| {
 6164                buffer.edit(edits, None, cx);
 6165            });
 6166
 6167            this.request_autoscroll(Autoscroll::fit(), cx);
 6168        });
 6169    }
 6170
 6171    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6172        self.duplicate_line(true, cx);
 6173    }
 6174
 6175    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6176        self.duplicate_line(false, cx);
 6177    }
 6178
 6179    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6180        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6181        let buffer = self.buffer.read(cx).snapshot(cx);
 6182
 6183        let mut edits = Vec::new();
 6184        let mut unfold_ranges = Vec::new();
 6185        let mut refold_creases = Vec::new();
 6186
 6187        let selections = self.selections.all::<Point>(cx);
 6188        let mut selections = selections.iter().peekable();
 6189        let mut contiguous_row_selections = Vec::new();
 6190        let mut new_selections = Vec::new();
 6191
 6192        while let Some(selection) = selections.next() {
 6193            // Find all the selections that span a contiguous row range
 6194            let (start_row, end_row) = consume_contiguous_rows(
 6195                &mut contiguous_row_selections,
 6196                selection,
 6197                &display_map,
 6198                &mut selections,
 6199            );
 6200
 6201            // Move the text spanned by the row range to be before the line preceding the row range
 6202            if start_row.0 > 0 {
 6203                let range_to_move = Point::new(
 6204                    start_row.previous_row().0,
 6205                    buffer.line_len(start_row.previous_row()),
 6206                )
 6207                    ..Point::new(
 6208                        end_row.previous_row().0,
 6209                        buffer.line_len(end_row.previous_row()),
 6210                    );
 6211                let insertion_point = display_map
 6212                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6213                    .0;
 6214
 6215                // Don't move lines across excerpts
 6216                if buffer
 6217                    .excerpt_boundaries_in_range((
 6218                        Bound::Excluded(insertion_point),
 6219                        Bound::Included(range_to_move.end),
 6220                    ))
 6221                    .next()
 6222                    .is_none()
 6223                {
 6224                    let text = buffer
 6225                        .text_for_range(range_to_move.clone())
 6226                        .flat_map(|s| s.chars())
 6227                        .skip(1)
 6228                        .chain(['\n'])
 6229                        .collect::<String>();
 6230
 6231                    edits.push((
 6232                        buffer.anchor_after(range_to_move.start)
 6233                            ..buffer.anchor_before(range_to_move.end),
 6234                        String::new(),
 6235                    ));
 6236                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6237                    edits.push((insertion_anchor..insertion_anchor, text));
 6238
 6239                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6240
 6241                    // Move selections up
 6242                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6243                        |mut selection| {
 6244                            selection.start.row -= row_delta;
 6245                            selection.end.row -= row_delta;
 6246                            selection
 6247                        },
 6248                    ));
 6249
 6250                    // Move folds up
 6251                    unfold_ranges.push(range_to_move.clone());
 6252                    for fold in display_map.folds_in_range(
 6253                        buffer.anchor_before(range_to_move.start)
 6254                            ..buffer.anchor_after(range_to_move.end),
 6255                    ) {
 6256                        let mut start = fold.range.start.to_point(&buffer);
 6257                        let mut end = fold.range.end.to_point(&buffer);
 6258                        start.row -= row_delta;
 6259                        end.row -= row_delta;
 6260                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6261                    }
 6262                }
 6263            }
 6264
 6265            // If we didn't move line(s), preserve the existing selections
 6266            new_selections.append(&mut contiguous_row_selections);
 6267        }
 6268
 6269        self.transact(cx, |this, cx| {
 6270            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6271            this.buffer.update(cx, |buffer, cx| {
 6272                for (range, text) in edits {
 6273                    buffer.edit([(range, text)], None, cx);
 6274                }
 6275            });
 6276            this.fold_creases(refold_creases, true, cx);
 6277            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6278                s.select(new_selections);
 6279            })
 6280        });
 6281    }
 6282
 6283    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6284        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6285        let buffer = self.buffer.read(cx).snapshot(cx);
 6286
 6287        let mut edits = Vec::new();
 6288        let mut unfold_ranges = Vec::new();
 6289        let mut refold_creases = Vec::new();
 6290
 6291        let selections = self.selections.all::<Point>(cx);
 6292        let mut selections = selections.iter().peekable();
 6293        let mut contiguous_row_selections = Vec::new();
 6294        let mut new_selections = Vec::new();
 6295
 6296        while let Some(selection) = selections.next() {
 6297            // Find all the selections that span a contiguous row range
 6298            let (start_row, end_row) = consume_contiguous_rows(
 6299                &mut contiguous_row_selections,
 6300                selection,
 6301                &display_map,
 6302                &mut selections,
 6303            );
 6304
 6305            // Move the text spanned by the row range to be after the last line of the row range
 6306            if end_row.0 <= buffer.max_point().row {
 6307                let range_to_move =
 6308                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6309                let insertion_point = display_map
 6310                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6311                    .0;
 6312
 6313                // Don't move lines across excerpt boundaries
 6314                if buffer
 6315                    .excerpt_boundaries_in_range((
 6316                        Bound::Excluded(range_to_move.start),
 6317                        Bound::Included(insertion_point),
 6318                    ))
 6319                    .next()
 6320                    .is_none()
 6321                {
 6322                    let mut text = String::from("\n");
 6323                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6324                    text.pop(); // Drop trailing newline
 6325                    edits.push((
 6326                        buffer.anchor_after(range_to_move.start)
 6327                            ..buffer.anchor_before(range_to_move.end),
 6328                        String::new(),
 6329                    ));
 6330                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6331                    edits.push((insertion_anchor..insertion_anchor, text));
 6332
 6333                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6334
 6335                    // Move selections down
 6336                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6337                        |mut selection| {
 6338                            selection.start.row += row_delta;
 6339                            selection.end.row += row_delta;
 6340                            selection
 6341                        },
 6342                    ));
 6343
 6344                    // Move folds down
 6345                    unfold_ranges.push(range_to_move.clone());
 6346                    for fold in display_map.folds_in_range(
 6347                        buffer.anchor_before(range_to_move.start)
 6348                            ..buffer.anchor_after(range_to_move.end),
 6349                    ) {
 6350                        let mut start = fold.range.start.to_point(&buffer);
 6351                        let mut end = fold.range.end.to_point(&buffer);
 6352                        start.row += row_delta;
 6353                        end.row += row_delta;
 6354                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6355                    }
 6356                }
 6357            }
 6358
 6359            // If we didn't move line(s), preserve the existing selections
 6360            new_selections.append(&mut contiguous_row_selections);
 6361        }
 6362
 6363        self.transact(cx, |this, cx| {
 6364            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6365            this.buffer.update(cx, |buffer, cx| {
 6366                for (range, text) in edits {
 6367                    buffer.edit([(range, text)], None, cx);
 6368                }
 6369            });
 6370            this.fold_creases(refold_creases, true, cx);
 6371            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6372        });
 6373    }
 6374
 6375    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6376        let text_layout_details = &self.text_layout_details(cx);
 6377        self.transact(cx, |this, cx| {
 6378            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6379                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6380                let line_mode = s.line_mode;
 6381                s.move_with(|display_map, selection| {
 6382                    if !selection.is_empty() || line_mode {
 6383                        return;
 6384                    }
 6385
 6386                    let mut head = selection.head();
 6387                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6388                    if head.column() == display_map.line_len(head.row()) {
 6389                        transpose_offset = display_map
 6390                            .buffer_snapshot
 6391                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6392                    }
 6393
 6394                    if transpose_offset == 0 {
 6395                        return;
 6396                    }
 6397
 6398                    *head.column_mut() += 1;
 6399                    head = display_map.clip_point(head, Bias::Right);
 6400                    let goal = SelectionGoal::HorizontalPosition(
 6401                        display_map
 6402                            .x_for_display_point(head, text_layout_details)
 6403                            .into(),
 6404                    );
 6405                    selection.collapse_to(head, goal);
 6406
 6407                    let transpose_start = display_map
 6408                        .buffer_snapshot
 6409                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6410                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6411                        let transpose_end = display_map
 6412                            .buffer_snapshot
 6413                            .clip_offset(transpose_offset + 1, Bias::Right);
 6414                        if let Some(ch) =
 6415                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6416                        {
 6417                            edits.push((transpose_start..transpose_offset, String::new()));
 6418                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6419                        }
 6420                    }
 6421                });
 6422                edits
 6423            });
 6424            this.buffer
 6425                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6426            let selections = this.selections.all::<usize>(cx);
 6427            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6428                s.select(selections);
 6429            });
 6430        });
 6431    }
 6432
 6433    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6434        self.rewrap_impl(IsVimMode::No, cx)
 6435    }
 6436
 6437    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6438        let buffer = self.buffer.read(cx).snapshot(cx);
 6439        let selections = self.selections.all::<Point>(cx);
 6440        let mut selections = selections.iter().peekable();
 6441
 6442        let mut edits = Vec::new();
 6443        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6444
 6445        while let Some(selection) = selections.next() {
 6446            let mut start_row = selection.start.row;
 6447            let mut end_row = selection.end.row;
 6448
 6449            // Skip selections that overlap with a range that has already been rewrapped.
 6450            let selection_range = start_row..end_row;
 6451            if rewrapped_row_ranges
 6452                .iter()
 6453                .any(|range| range.overlaps(&selection_range))
 6454            {
 6455                continue;
 6456            }
 6457
 6458            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6459
 6460            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6461                match language_scope.language_name().0.as_ref() {
 6462                    "Markdown" | "Plain Text" => {
 6463                        should_rewrap = true;
 6464                    }
 6465                    _ => {}
 6466                }
 6467            }
 6468
 6469            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6470
 6471            // Since not all lines in the selection may be at the same indent
 6472            // level, choose the indent size that is the most common between all
 6473            // of the lines.
 6474            //
 6475            // If there is a tie, we use the deepest indent.
 6476            let (indent_size, indent_end) = {
 6477                let mut indent_size_occurrences = HashMap::default();
 6478                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6479
 6480                for row in start_row..=end_row {
 6481                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6482                    rows_by_indent_size.entry(indent).or_default().push(row);
 6483                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6484                }
 6485
 6486                let indent_size = indent_size_occurrences
 6487                    .into_iter()
 6488                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6489                    .map(|(indent, _)| indent)
 6490                    .unwrap_or_default();
 6491                let row = rows_by_indent_size[&indent_size][0];
 6492                let indent_end = Point::new(row, indent_size.len);
 6493
 6494                (indent_size, indent_end)
 6495            };
 6496
 6497            let mut line_prefix = indent_size.chars().collect::<String>();
 6498
 6499            if let Some(comment_prefix) =
 6500                buffer
 6501                    .language_scope_at(selection.head())
 6502                    .and_then(|language| {
 6503                        language
 6504                            .line_comment_prefixes()
 6505                            .iter()
 6506                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6507                            .cloned()
 6508                    })
 6509            {
 6510                line_prefix.push_str(&comment_prefix);
 6511                should_rewrap = true;
 6512            }
 6513
 6514            if !should_rewrap {
 6515                continue;
 6516            }
 6517
 6518            if selection.is_empty() {
 6519                'expand_upwards: while start_row > 0 {
 6520                    let prev_row = start_row - 1;
 6521                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6522                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6523                    {
 6524                        start_row = prev_row;
 6525                    } else {
 6526                        break 'expand_upwards;
 6527                    }
 6528                }
 6529
 6530                'expand_downwards: while end_row < buffer.max_point().row {
 6531                    let next_row = end_row + 1;
 6532                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6533                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6534                    {
 6535                        end_row = next_row;
 6536                    } else {
 6537                        break 'expand_downwards;
 6538                    }
 6539                }
 6540            }
 6541
 6542            let start = Point::new(start_row, 0);
 6543            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6544            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6545            let Some(lines_without_prefixes) = selection_text
 6546                .lines()
 6547                .map(|line| {
 6548                    line.strip_prefix(&line_prefix)
 6549                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6550                        .ok_or_else(|| {
 6551                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6552                        })
 6553                })
 6554                .collect::<Result<Vec<_>, _>>()
 6555                .log_err()
 6556            else {
 6557                continue;
 6558            };
 6559
 6560            let wrap_column = buffer
 6561                .settings_at(Point::new(start_row, 0), cx)
 6562                .preferred_line_length as usize;
 6563            let wrapped_text = wrap_with_prefix(
 6564                line_prefix,
 6565                lines_without_prefixes.join(" "),
 6566                wrap_column,
 6567                tab_size,
 6568            );
 6569
 6570            // TODO: should always use char-based diff while still supporting cursor behavior that
 6571            // matches vim.
 6572            let diff = match is_vim_mode {
 6573                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6574                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6575            };
 6576            let mut offset = start.to_offset(&buffer);
 6577            let mut moved_since_edit = true;
 6578
 6579            for change in diff.iter_all_changes() {
 6580                let value = change.value();
 6581                match change.tag() {
 6582                    ChangeTag::Equal => {
 6583                        offset += value.len();
 6584                        moved_since_edit = true;
 6585                    }
 6586                    ChangeTag::Delete => {
 6587                        let start = buffer.anchor_after(offset);
 6588                        let end = buffer.anchor_before(offset + value.len());
 6589
 6590                        if moved_since_edit {
 6591                            edits.push((start..end, String::new()));
 6592                        } else {
 6593                            edits.last_mut().unwrap().0.end = end;
 6594                        }
 6595
 6596                        offset += value.len();
 6597                        moved_since_edit = false;
 6598                    }
 6599                    ChangeTag::Insert => {
 6600                        if moved_since_edit {
 6601                            let anchor = buffer.anchor_after(offset);
 6602                            edits.push((anchor..anchor, value.to_string()));
 6603                        } else {
 6604                            edits.last_mut().unwrap().1.push_str(value);
 6605                        }
 6606
 6607                        moved_since_edit = false;
 6608                    }
 6609                }
 6610            }
 6611
 6612            rewrapped_row_ranges.push(start_row..=end_row);
 6613        }
 6614
 6615        self.buffer
 6616            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6617    }
 6618
 6619    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6620        let mut text = String::new();
 6621        let buffer = self.buffer.read(cx).snapshot(cx);
 6622        let mut selections = self.selections.all::<Point>(cx);
 6623        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6624        {
 6625            let max_point = buffer.max_point();
 6626            let mut is_first = true;
 6627            for selection in &mut selections {
 6628                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6629                if is_entire_line {
 6630                    selection.start = Point::new(selection.start.row, 0);
 6631                    if !selection.is_empty() && selection.end.column == 0 {
 6632                        selection.end = cmp::min(max_point, selection.end);
 6633                    } else {
 6634                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6635                    }
 6636                    selection.goal = SelectionGoal::None;
 6637                }
 6638                if is_first {
 6639                    is_first = false;
 6640                } else {
 6641                    text += "\n";
 6642                }
 6643                let mut len = 0;
 6644                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6645                    text.push_str(chunk);
 6646                    len += chunk.len();
 6647                }
 6648                clipboard_selections.push(ClipboardSelection {
 6649                    len,
 6650                    is_entire_line,
 6651                    first_line_indent: buffer
 6652                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6653                        .len,
 6654                });
 6655            }
 6656        }
 6657
 6658        self.transact(cx, |this, cx| {
 6659            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6660                s.select(selections);
 6661            });
 6662            this.insert("", cx);
 6663        });
 6664        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6665    }
 6666
 6667    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6668        let item = self.cut_common(cx);
 6669        cx.write_to_clipboard(item);
 6670    }
 6671
 6672    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6673        self.change_selections(None, cx, |s| {
 6674            s.move_with(|snapshot, sel| {
 6675                if sel.is_empty() {
 6676                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6677                }
 6678            });
 6679        });
 6680        let item = self.cut_common(cx);
 6681        cx.set_global(KillRing(item))
 6682    }
 6683
 6684    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6685        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6686            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6687                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6688            } else {
 6689                return;
 6690            }
 6691        } else {
 6692            return;
 6693        };
 6694        self.do_paste(&text, metadata, false, cx);
 6695    }
 6696
 6697    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6698        let selections = self.selections.all::<Point>(cx);
 6699        let buffer = self.buffer.read(cx).read(cx);
 6700        let mut text = String::new();
 6701
 6702        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6703        {
 6704            let max_point = buffer.max_point();
 6705            let mut is_first = true;
 6706            for selection in selections.iter() {
 6707                let mut start = selection.start;
 6708                let mut end = selection.end;
 6709                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6710                if is_entire_line {
 6711                    start = Point::new(start.row, 0);
 6712                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6713                }
 6714                if is_first {
 6715                    is_first = false;
 6716                } else {
 6717                    text += "\n";
 6718                }
 6719                let mut len = 0;
 6720                for chunk in buffer.text_for_range(start..end) {
 6721                    text.push_str(chunk);
 6722                    len += chunk.len();
 6723                }
 6724                clipboard_selections.push(ClipboardSelection {
 6725                    len,
 6726                    is_entire_line,
 6727                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6728                });
 6729            }
 6730        }
 6731
 6732        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6733            text,
 6734            clipboard_selections,
 6735        ));
 6736    }
 6737
 6738    pub fn do_paste(
 6739        &mut self,
 6740        text: &String,
 6741        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6742        handle_entire_lines: bool,
 6743        cx: &mut ViewContext<Self>,
 6744    ) {
 6745        if self.read_only(cx) {
 6746            return;
 6747        }
 6748
 6749        let clipboard_text = Cow::Borrowed(text);
 6750
 6751        self.transact(cx, |this, cx| {
 6752            if let Some(mut clipboard_selections) = clipboard_selections {
 6753                let old_selections = this.selections.all::<usize>(cx);
 6754                let all_selections_were_entire_line =
 6755                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6756                let first_selection_indent_column =
 6757                    clipboard_selections.first().map(|s| s.first_line_indent);
 6758                if clipboard_selections.len() != old_selections.len() {
 6759                    clipboard_selections.drain(..);
 6760                }
 6761                let cursor_offset = this.selections.last::<usize>(cx).head();
 6762                let mut auto_indent_on_paste = true;
 6763
 6764                this.buffer.update(cx, |buffer, cx| {
 6765                    let snapshot = buffer.read(cx);
 6766                    auto_indent_on_paste =
 6767                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6768
 6769                    let mut start_offset = 0;
 6770                    let mut edits = Vec::new();
 6771                    let mut original_indent_columns = Vec::new();
 6772                    for (ix, selection) in old_selections.iter().enumerate() {
 6773                        let to_insert;
 6774                        let entire_line;
 6775                        let original_indent_column;
 6776                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6777                            let end_offset = start_offset + clipboard_selection.len;
 6778                            to_insert = &clipboard_text[start_offset..end_offset];
 6779                            entire_line = clipboard_selection.is_entire_line;
 6780                            start_offset = end_offset + 1;
 6781                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6782                        } else {
 6783                            to_insert = clipboard_text.as_str();
 6784                            entire_line = all_selections_were_entire_line;
 6785                            original_indent_column = first_selection_indent_column
 6786                        }
 6787
 6788                        // If the corresponding selection was empty when this slice of the
 6789                        // clipboard text was written, then the entire line containing the
 6790                        // selection was copied. If this selection is also currently empty,
 6791                        // then paste the line before the current line of the buffer.
 6792                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6793                            let column = selection.start.to_point(&snapshot).column as usize;
 6794                            let line_start = selection.start - column;
 6795                            line_start..line_start
 6796                        } else {
 6797                            selection.range()
 6798                        };
 6799
 6800                        edits.push((range, to_insert));
 6801                        original_indent_columns.extend(original_indent_column);
 6802                    }
 6803                    drop(snapshot);
 6804
 6805                    buffer.edit(
 6806                        edits,
 6807                        if auto_indent_on_paste {
 6808                            Some(AutoindentMode::Block {
 6809                                original_indent_columns,
 6810                            })
 6811                        } else {
 6812                            None
 6813                        },
 6814                        cx,
 6815                    );
 6816                });
 6817
 6818                let selections = this.selections.all::<usize>(cx);
 6819                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6820            } else {
 6821                this.insert(&clipboard_text, cx);
 6822            }
 6823        });
 6824    }
 6825
 6826    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6827        if let Some(item) = cx.read_from_clipboard() {
 6828            let entries = item.entries();
 6829
 6830            match entries.first() {
 6831                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6832                // of all the pasted entries.
 6833                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6834                    .do_paste(
 6835                        clipboard_string.text(),
 6836                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 6837                        true,
 6838                        cx,
 6839                    ),
 6840                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 6841            }
 6842        }
 6843    }
 6844
 6845    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6846        if self.read_only(cx) {
 6847            return;
 6848        }
 6849
 6850        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6851            if let Some((selections, _)) =
 6852                self.selection_history.transaction(transaction_id).cloned()
 6853            {
 6854                self.change_selections(None, cx, |s| {
 6855                    s.select_anchors(selections.to_vec());
 6856                });
 6857            }
 6858            self.request_autoscroll(Autoscroll::fit(), cx);
 6859            self.unmark_text(cx);
 6860            self.refresh_inline_completion(true, false, cx);
 6861            cx.emit(EditorEvent::Edited { transaction_id });
 6862            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6863        }
 6864    }
 6865
 6866    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6867        if self.read_only(cx) {
 6868            return;
 6869        }
 6870
 6871        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6872            if let Some((_, Some(selections))) =
 6873                self.selection_history.transaction(transaction_id).cloned()
 6874            {
 6875                self.change_selections(None, cx, |s| {
 6876                    s.select_anchors(selections.to_vec());
 6877                });
 6878            }
 6879            self.request_autoscroll(Autoscroll::fit(), cx);
 6880            self.unmark_text(cx);
 6881            self.refresh_inline_completion(true, false, cx);
 6882            cx.emit(EditorEvent::Edited { transaction_id });
 6883        }
 6884    }
 6885
 6886    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6887        self.buffer
 6888            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6889    }
 6890
 6891    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6892        self.buffer
 6893            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6894    }
 6895
 6896    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6897        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6898            let line_mode = s.line_mode;
 6899            s.move_with(|map, selection| {
 6900                let cursor = if selection.is_empty() && !line_mode {
 6901                    movement::left(map, selection.start)
 6902                } else {
 6903                    selection.start
 6904                };
 6905                selection.collapse_to(cursor, SelectionGoal::None);
 6906            });
 6907        })
 6908    }
 6909
 6910    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6911        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6912            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6913        })
 6914    }
 6915
 6916    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6917        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6918            let line_mode = s.line_mode;
 6919            s.move_with(|map, selection| {
 6920                let cursor = if selection.is_empty() && !line_mode {
 6921                    movement::right(map, selection.end)
 6922                } else {
 6923                    selection.end
 6924                };
 6925                selection.collapse_to(cursor, SelectionGoal::None)
 6926            });
 6927        })
 6928    }
 6929
 6930    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6931        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6932            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6933        })
 6934    }
 6935
 6936    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6937        if self.take_rename(true, cx).is_some() {
 6938            return;
 6939        }
 6940
 6941        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6942            cx.propagate();
 6943            return;
 6944        }
 6945
 6946        let text_layout_details = &self.text_layout_details(cx);
 6947        let selection_count = self.selections.count();
 6948        let first_selection = self.selections.first_anchor();
 6949
 6950        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6951            let line_mode = s.line_mode;
 6952            s.move_with(|map, selection| {
 6953                if !selection.is_empty() && !line_mode {
 6954                    selection.goal = SelectionGoal::None;
 6955                }
 6956                let (cursor, goal) = movement::up(
 6957                    map,
 6958                    selection.start,
 6959                    selection.goal,
 6960                    false,
 6961                    text_layout_details,
 6962                );
 6963                selection.collapse_to(cursor, goal);
 6964            });
 6965        });
 6966
 6967        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6968        {
 6969            cx.propagate();
 6970        }
 6971    }
 6972
 6973    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6974        if self.take_rename(true, cx).is_some() {
 6975            return;
 6976        }
 6977
 6978        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6979            cx.propagate();
 6980            return;
 6981        }
 6982
 6983        let text_layout_details = &self.text_layout_details(cx);
 6984
 6985        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6986            let line_mode = s.line_mode;
 6987            s.move_with(|map, selection| {
 6988                if !selection.is_empty() && !line_mode {
 6989                    selection.goal = SelectionGoal::None;
 6990                }
 6991                let (cursor, goal) = movement::up_by_rows(
 6992                    map,
 6993                    selection.start,
 6994                    action.lines,
 6995                    selection.goal,
 6996                    false,
 6997                    text_layout_details,
 6998                );
 6999                selection.collapse_to(cursor, goal);
 7000            });
 7001        })
 7002    }
 7003
 7004    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7005        if self.take_rename(true, cx).is_some() {
 7006            return;
 7007        }
 7008
 7009        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7010            cx.propagate();
 7011            return;
 7012        }
 7013
 7014        let text_layout_details = &self.text_layout_details(cx);
 7015
 7016        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7017            let line_mode = s.line_mode;
 7018            s.move_with(|map, selection| {
 7019                if !selection.is_empty() && !line_mode {
 7020                    selection.goal = SelectionGoal::None;
 7021                }
 7022                let (cursor, goal) = movement::down_by_rows(
 7023                    map,
 7024                    selection.start,
 7025                    action.lines,
 7026                    selection.goal,
 7027                    false,
 7028                    text_layout_details,
 7029                );
 7030                selection.collapse_to(cursor, goal);
 7031            });
 7032        })
 7033    }
 7034
 7035    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7036        let text_layout_details = &self.text_layout_details(cx);
 7037        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7038            s.move_heads_with(|map, head, goal| {
 7039                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7040            })
 7041        })
 7042    }
 7043
 7044    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7045        let text_layout_details = &self.text_layout_details(cx);
 7046        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7047            s.move_heads_with(|map, head, goal| {
 7048                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7049            })
 7050        })
 7051    }
 7052
 7053    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7054        let Some(row_count) = self.visible_row_count() else {
 7055            return;
 7056        };
 7057
 7058        let text_layout_details = &self.text_layout_details(cx);
 7059
 7060        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7061            s.move_heads_with(|map, head, goal| {
 7062                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7063            })
 7064        })
 7065    }
 7066
 7067    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7068        if self.take_rename(true, cx).is_some() {
 7069            return;
 7070        }
 7071
 7072        if self
 7073            .context_menu
 7074            .write()
 7075            .as_mut()
 7076            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7077            .unwrap_or(false)
 7078        {
 7079            return;
 7080        }
 7081
 7082        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7083            cx.propagate();
 7084            return;
 7085        }
 7086
 7087        let Some(row_count) = self.visible_row_count() else {
 7088            return;
 7089        };
 7090
 7091        let autoscroll = if action.center_cursor {
 7092            Autoscroll::center()
 7093        } else {
 7094            Autoscroll::fit()
 7095        };
 7096
 7097        let text_layout_details = &self.text_layout_details(cx);
 7098
 7099        self.change_selections(Some(autoscroll), cx, |s| {
 7100            let line_mode = s.line_mode;
 7101            s.move_with(|map, selection| {
 7102                if !selection.is_empty() && !line_mode {
 7103                    selection.goal = SelectionGoal::None;
 7104                }
 7105                let (cursor, goal) = movement::up_by_rows(
 7106                    map,
 7107                    selection.end,
 7108                    row_count,
 7109                    selection.goal,
 7110                    false,
 7111                    text_layout_details,
 7112                );
 7113                selection.collapse_to(cursor, goal);
 7114            });
 7115        });
 7116    }
 7117
 7118    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7119        let text_layout_details = &self.text_layout_details(cx);
 7120        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7121            s.move_heads_with(|map, head, goal| {
 7122                movement::up(map, head, goal, false, text_layout_details)
 7123            })
 7124        })
 7125    }
 7126
 7127    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7128        self.take_rename(true, cx);
 7129
 7130        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7131            cx.propagate();
 7132            return;
 7133        }
 7134
 7135        let text_layout_details = &self.text_layout_details(cx);
 7136        let selection_count = self.selections.count();
 7137        let first_selection = self.selections.first_anchor();
 7138
 7139        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7140            let line_mode = s.line_mode;
 7141            s.move_with(|map, selection| {
 7142                if !selection.is_empty() && !line_mode {
 7143                    selection.goal = SelectionGoal::None;
 7144                }
 7145                let (cursor, goal) = movement::down(
 7146                    map,
 7147                    selection.end,
 7148                    selection.goal,
 7149                    false,
 7150                    text_layout_details,
 7151                );
 7152                selection.collapse_to(cursor, goal);
 7153            });
 7154        });
 7155
 7156        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7157        {
 7158            cx.propagate();
 7159        }
 7160    }
 7161
 7162    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7163        let Some(row_count) = self.visible_row_count() else {
 7164            return;
 7165        };
 7166
 7167        let text_layout_details = &self.text_layout_details(cx);
 7168
 7169        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7170            s.move_heads_with(|map, head, goal| {
 7171                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7172            })
 7173        })
 7174    }
 7175
 7176    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7177        if self.take_rename(true, cx).is_some() {
 7178            return;
 7179        }
 7180
 7181        if self
 7182            .context_menu
 7183            .write()
 7184            .as_mut()
 7185            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7186            .unwrap_or(false)
 7187        {
 7188            return;
 7189        }
 7190
 7191        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7192            cx.propagate();
 7193            return;
 7194        }
 7195
 7196        let Some(row_count) = self.visible_row_count() else {
 7197            return;
 7198        };
 7199
 7200        let autoscroll = if action.center_cursor {
 7201            Autoscroll::center()
 7202        } else {
 7203            Autoscroll::fit()
 7204        };
 7205
 7206        let text_layout_details = &self.text_layout_details(cx);
 7207        self.change_selections(Some(autoscroll), cx, |s| {
 7208            let line_mode = s.line_mode;
 7209            s.move_with(|map, selection| {
 7210                if !selection.is_empty() && !line_mode {
 7211                    selection.goal = SelectionGoal::None;
 7212                }
 7213                let (cursor, goal) = movement::down_by_rows(
 7214                    map,
 7215                    selection.end,
 7216                    row_count,
 7217                    selection.goal,
 7218                    false,
 7219                    text_layout_details,
 7220                );
 7221                selection.collapse_to(cursor, goal);
 7222            });
 7223        });
 7224    }
 7225
 7226    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7227        let text_layout_details = &self.text_layout_details(cx);
 7228        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7229            s.move_heads_with(|map, head, goal| {
 7230                movement::down(map, head, goal, false, text_layout_details)
 7231            })
 7232        });
 7233    }
 7234
 7235    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7236        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7237            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7238        }
 7239    }
 7240
 7241    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7242        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7243            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7244        }
 7245    }
 7246
 7247    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7248        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7249            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7250        }
 7251    }
 7252
 7253    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7254        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7255            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7256        }
 7257    }
 7258
 7259    pub fn move_to_previous_word_start(
 7260        &mut self,
 7261        _: &MoveToPreviousWordStart,
 7262        cx: &mut ViewContext<Self>,
 7263    ) {
 7264        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7265            s.move_cursors_with(|map, head, _| {
 7266                (
 7267                    movement::previous_word_start(map, head),
 7268                    SelectionGoal::None,
 7269                )
 7270            });
 7271        })
 7272    }
 7273
 7274    pub fn move_to_previous_subword_start(
 7275        &mut self,
 7276        _: &MoveToPreviousSubwordStart,
 7277        cx: &mut ViewContext<Self>,
 7278    ) {
 7279        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7280            s.move_cursors_with(|map, head, _| {
 7281                (
 7282                    movement::previous_subword_start(map, head),
 7283                    SelectionGoal::None,
 7284                )
 7285            });
 7286        })
 7287    }
 7288
 7289    pub fn select_to_previous_word_start(
 7290        &mut self,
 7291        _: &SelectToPreviousWordStart,
 7292        cx: &mut ViewContext<Self>,
 7293    ) {
 7294        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7295            s.move_heads_with(|map, head, _| {
 7296                (
 7297                    movement::previous_word_start(map, head),
 7298                    SelectionGoal::None,
 7299                )
 7300            });
 7301        })
 7302    }
 7303
 7304    pub fn select_to_previous_subword_start(
 7305        &mut self,
 7306        _: &SelectToPreviousSubwordStart,
 7307        cx: &mut ViewContext<Self>,
 7308    ) {
 7309        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7310            s.move_heads_with(|map, head, _| {
 7311                (
 7312                    movement::previous_subword_start(map, head),
 7313                    SelectionGoal::None,
 7314                )
 7315            });
 7316        })
 7317    }
 7318
 7319    pub fn delete_to_previous_word_start(
 7320        &mut self,
 7321        action: &DeleteToPreviousWordStart,
 7322        cx: &mut ViewContext<Self>,
 7323    ) {
 7324        self.transact(cx, |this, cx| {
 7325            this.select_autoclose_pair(cx);
 7326            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7327                let line_mode = s.line_mode;
 7328                s.move_with(|map, selection| {
 7329                    if selection.is_empty() && !line_mode {
 7330                        let cursor = if action.ignore_newlines {
 7331                            movement::previous_word_start(map, selection.head())
 7332                        } else {
 7333                            movement::previous_word_start_or_newline(map, selection.head())
 7334                        };
 7335                        selection.set_head(cursor, SelectionGoal::None);
 7336                    }
 7337                });
 7338            });
 7339            this.insert("", cx);
 7340        });
 7341    }
 7342
 7343    pub fn delete_to_previous_subword_start(
 7344        &mut self,
 7345        _: &DeleteToPreviousSubwordStart,
 7346        cx: &mut ViewContext<Self>,
 7347    ) {
 7348        self.transact(cx, |this, cx| {
 7349            this.select_autoclose_pair(cx);
 7350            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7351                let line_mode = s.line_mode;
 7352                s.move_with(|map, selection| {
 7353                    if selection.is_empty() && !line_mode {
 7354                        let cursor = movement::previous_subword_start(map, selection.head());
 7355                        selection.set_head(cursor, SelectionGoal::None);
 7356                    }
 7357                });
 7358            });
 7359            this.insert("", cx);
 7360        });
 7361    }
 7362
 7363    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7364        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7365            s.move_cursors_with(|map, head, _| {
 7366                (movement::next_word_end(map, head), SelectionGoal::None)
 7367            });
 7368        })
 7369    }
 7370
 7371    pub fn move_to_next_subword_end(
 7372        &mut self,
 7373        _: &MoveToNextSubwordEnd,
 7374        cx: &mut ViewContext<Self>,
 7375    ) {
 7376        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7377            s.move_cursors_with(|map, head, _| {
 7378                (movement::next_subword_end(map, head), SelectionGoal::None)
 7379            });
 7380        })
 7381    }
 7382
 7383    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7384        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7385            s.move_heads_with(|map, head, _| {
 7386                (movement::next_word_end(map, head), SelectionGoal::None)
 7387            });
 7388        })
 7389    }
 7390
 7391    pub fn select_to_next_subword_end(
 7392        &mut self,
 7393        _: &SelectToNextSubwordEnd,
 7394        cx: &mut ViewContext<Self>,
 7395    ) {
 7396        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7397            s.move_heads_with(|map, head, _| {
 7398                (movement::next_subword_end(map, head), SelectionGoal::None)
 7399            });
 7400        })
 7401    }
 7402
 7403    pub fn delete_to_next_word_end(
 7404        &mut self,
 7405        action: &DeleteToNextWordEnd,
 7406        cx: &mut ViewContext<Self>,
 7407    ) {
 7408        self.transact(cx, |this, cx| {
 7409            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7410                let line_mode = s.line_mode;
 7411                s.move_with(|map, selection| {
 7412                    if selection.is_empty() && !line_mode {
 7413                        let cursor = if action.ignore_newlines {
 7414                            movement::next_word_end(map, selection.head())
 7415                        } else {
 7416                            movement::next_word_end_or_newline(map, selection.head())
 7417                        };
 7418                        selection.set_head(cursor, SelectionGoal::None);
 7419                    }
 7420                });
 7421            });
 7422            this.insert("", cx);
 7423        });
 7424    }
 7425
 7426    pub fn delete_to_next_subword_end(
 7427        &mut self,
 7428        _: &DeleteToNextSubwordEnd,
 7429        cx: &mut ViewContext<Self>,
 7430    ) {
 7431        self.transact(cx, |this, cx| {
 7432            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7433                s.move_with(|map, selection| {
 7434                    if selection.is_empty() {
 7435                        let cursor = movement::next_subword_end(map, selection.head());
 7436                        selection.set_head(cursor, SelectionGoal::None);
 7437                    }
 7438                });
 7439            });
 7440            this.insert("", cx);
 7441        });
 7442    }
 7443
 7444    pub fn move_to_beginning_of_line(
 7445        &mut self,
 7446        action: &MoveToBeginningOfLine,
 7447        cx: &mut ViewContext<Self>,
 7448    ) {
 7449        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7450            s.move_cursors_with(|map, head, _| {
 7451                (
 7452                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7453                    SelectionGoal::None,
 7454                )
 7455            });
 7456        })
 7457    }
 7458
 7459    pub fn select_to_beginning_of_line(
 7460        &mut self,
 7461        action: &SelectToBeginningOfLine,
 7462        cx: &mut ViewContext<Self>,
 7463    ) {
 7464        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7465            s.move_heads_with(|map, head, _| {
 7466                (
 7467                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7468                    SelectionGoal::None,
 7469                )
 7470            });
 7471        });
 7472    }
 7473
 7474    pub fn delete_to_beginning_of_line(
 7475        &mut self,
 7476        _: &DeleteToBeginningOfLine,
 7477        cx: &mut ViewContext<Self>,
 7478    ) {
 7479        self.transact(cx, |this, cx| {
 7480            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7481                s.move_with(|_, selection| {
 7482                    selection.reversed = true;
 7483                });
 7484            });
 7485
 7486            this.select_to_beginning_of_line(
 7487                &SelectToBeginningOfLine {
 7488                    stop_at_soft_wraps: false,
 7489                },
 7490                cx,
 7491            );
 7492            this.backspace(&Backspace, cx);
 7493        });
 7494    }
 7495
 7496    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7497        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7498            s.move_cursors_with(|map, head, _| {
 7499                (
 7500                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7501                    SelectionGoal::None,
 7502                )
 7503            });
 7504        })
 7505    }
 7506
 7507    pub fn select_to_end_of_line(
 7508        &mut self,
 7509        action: &SelectToEndOfLine,
 7510        cx: &mut ViewContext<Self>,
 7511    ) {
 7512        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7513            s.move_heads_with(|map, head, _| {
 7514                (
 7515                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7516                    SelectionGoal::None,
 7517                )
 7518            });
 7519        })
 7520    }
 7521
 7522    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7523        self.transact(cx, |this, cx| {
 7524            this.select_to_end_of_line(
 7525                &SelectToEndOfLine {
 7526                    stop_at_soft_wraps: false,
 7527                },
 7528                cx,
 7529            );
 7530            this.delete(&Delete, cx);
 7531        });
 7532    }
 7533
 7534    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7535        self.transact(cx, |this, cx| {
 7536            this.select_to_end_of_line(
 7537                &SelectToEndOfLine {
 7538                    stop_at_soft_wraps: false,
 7539                },
 7540                cx,
 7541            );
 7542            this.cut(&Cut, cx);
 7543        });
 7544    }
 7545
 7546    pub fn move_to_start_of_paragraph(
 7547        &mut self,
 7548        _: &MoveToStartOfParagraph,
 7549        cx: &mut ViewContext<Self>,
 7550    ) {
 7551        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7552            cx.propagate();
 7553            return;
 7554        }
 7555
 7556        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7557            s.move_with(|map, selection| {
 7558                selection.collapse_to(
 7559                    movement::start_of_paragraph(map, selection.head(), 1),
 7560                    SelectionGoal::None,
 7561                )
 7562            });
 7563        })
 7564    }
 7565
 7566    pub fn move_to_end_of_paragraph(
 7567        &mut self,
 7568        _: &MoveToEndOfParagraph,
 7569        cx: &mut ViewContext<Self>,
 7570    ) {
 7571        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7572            cx.propagate();
 7573            return;
 7574        }
 7575
 7576        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7577            s.move_with(|map, selection| {
 7578                selection.collapse_to(
 7579                    movement::end_of_paragraph(map, selection.head(), 1),
 7580                    SelectionGoal::None,
 7581                )
 7582            });
 7583        })
 7584    }
 7585
 7586    pub fn select_to_start_of_paragraph(
 7587        &mut self,
 7588        _: &SelectToStartOfParagraph,
 7589        cx: &mut ViewContext<Self>,
 7590    ) {
 7591        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7592            cx.propagate();
 7593            return;
 7594        }
 7595
 7596        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7597            s.move_heads_with(|map, head, _| {
 7598                (
 7599                    movement::start_of_paragraph(map, head, 1),
 7600                    SelectionGoal::None,
 7601                )
 7602            });
 7603        })
 7604    }
 7605
 7606    pub fn select_to_end_of_paragraph(
 7607        &mut self,
 7608        _: &SelectToEndOfParagraph,
 7609        cx: &mut ViewContext<Self>,
 7610    ) {
 7611        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7612            cx.propagate();
 7613            return;
 7614        }
 7615
 7616        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7617            s.move_heads_with(|map, head, _| {
 7618                (
 7619                    movement::end_of_paragraph(map, head, 1),
 7620                    SelectionGoal::None,
 7621                )
 7622            });
 7623        })
 7624    }
 7625
 7626    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7627        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7628            cx.propagate();
 7629            return;
 7630        }
 7631
 7632        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7633            s.select_ranges(vec![0..0]);
 7634        });
 7635    }
 7636
 7637    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7638        let mut selection = self.selections.last::<Point>(cx);
 7639        selection.set_head(Point::zero(), SelectionGoal::None);
 7640
 7641        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7642            s.select(vec![selection]);
 7643        });
 7644    }
 7645
 7646    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7647        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7648            cx.propagate();
 7649            return;
 7650        }
 7651
 7652        let cursor = self.buffer.read(cx).read(cx).len();
 7653        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7654            s.select_ranges(vec![cursor..cursor])
 7655        });
 7656    }
 7657
 7658    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7659        self.nav_history = nav_history;
 7660    }
 7661
 7662    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7663        self.nav_history.as_ref()
 7664    }
 7665
 7666    fn push_to_nav_history(
 7667        &mut self,
 7668        cursor_anchor: Anchor,
 7669        new_position: Option<Point>,
 7670        cx: &mut ViewContext<Self>,
 7671    ) {
 7672        if let Some(nav_history) = self.nav_history.as_mut() {
 7673            let buffer = self.buffer.read(cx).read(cx);
 7674            let cursor_position = cursor_anchor.to_point(&buffer);
 7675            let scroll_state = self.scroll_manager.anchor();
 7676            let scroll_top_row = scroll_state.top_row(&buffer);
 7677            drop(buffer);
 7678
 7679            if let Some(new_position) = new_position {
 7680                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7681                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7682                    return;
 7683                }
 7684            }
 7685
 7686            nav_history.push(
 7687                Some(NavigationData {
 7688                    cursor_anchor,
 7689                    cursor_position,
 7690                    scroll_anchor: scroll_state,
 7691                    scroll_top_row,
 7692                }),
 7693                cx,
 7694            );
 7695        }
 7696    }
 7697
 7698    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7699        let buffer = self.buffer.read(cx).snapshot(cx);
 7700        let mut selection = self.selections.first::<usize>(cx);
 7701        selection.set_head(buffer.len(), SelectionGoal::None);
 7702        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7703            s.select(vec![selection]);
 7704        });
 7705    }
 7706
 7707    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7708        let end = self.buffer.read(cx).read(cx).len();
 7709        self.change_selections(None, cx, |s| {
 7710            s.select_ranges(vec![0..end]);
 7711        });
 7712    }
 7713
 7714    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7715        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7716        let mut selections = self.selections.all::<Point>(cx);
 7717        let max_point = display_map.buffer_snapshot.max_point();
 7718        for selection in &mut selections {
 7719            let rows = selection.spanned_rows(true, &display_map);
 7720            selection.start = Point::new(rows.start.0, 0);
 7721            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7722            selection.reversed = false;
 7723        }
 7724        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7725            s.select(selections);
 7726        });
 7727    }
 7728
 7729    pub fn split_selection_into_lines(
 7730        &mut self,
 7731        _: &SplitSelectionIntoLines,
 7732        cx: &mut ViewContext<Self>,
 7733    ) {
 7734        let mut to_unfold = Vec::new();
 7735        let mut new_selection_ranges = Vec::new();
 7736        {
 7737            let selections = self.selections.all::<Point>(cx);
 7738            let buffer = self.buffer.read(cx).read(cx);
 7739            for selection in selections {
 7740                for row in selection.start.row..selection.end.row {
 7741                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7742                    new_selection_ranges.push(cursor..cursor);
 7743                }
 7744                new_selection_ranges.push(selection.end..selection.end);
 7745                to_unfold.push(selection.start..selection.end);
 7746            }
 7747        }
 7748        self.unfold_ranges(&to_unfold, true, true, cx);
 7749        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7750            s.select_ranges(new_selection_ranges);
 7751        });
 7752    }
 7753
 7754    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7755        self.add_selection(true, cx);
 7756    }
 7757
 7758    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7759        self.add_selection(false, cx);
 7760    }
 7761
 7762    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7763        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7764        let mut selections = self.selections.all::<Point>(cx);
 7765        let text_layout_details = self.text_layout_details(cx);
 7766        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7767            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7768            let range = oldest_selection.display_range(&display_map).sorted();
 7769
 7770            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7771            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7772            let positions = start_x.min(end_x)..start_x.max(end_x);
 7773
 7774            selections.clear();
 7775            let mut stack = Vec::new();
 7776            for row in range.start.row().0..=range.end.row().0 {
 7777                if let Some(selection) = self.selections.build_columnar_selection(
 7778                    &display_map,
 7779                    DisplayRow(row),
 7780                    &positions,
 7781                    oldest_selection.reversed,
 7782                    &text_layout_details,
 7783                ) {
 7784                    stack.push(selection.id);
 7785                    selections.push(selection);
 7786                }
 7787            }
 7788
 7789            if above {
 7790                stack.reverse();
 7791            }
 7792
 7793            AddSelectionsState { above, stack }
 7794        });
 7795
 7796        let last_added_selection = *state.stack.last().unwrap();
 7797        let mut new_selections = Vec::new();
 7798        if above == state.above {
 7799            let end_row = if above {
 7800                DisplayRow(0)
 7801            } else {
 7802                display_map.max_point().row()
 7803            };
 7804
 7805            'outer: for selection in selections {
 7806                if selection.id == last_added_selection {
 7807                    let range = selection.display_range(&display_map).sorted();
 7808                    debug_assert_eq!(range.start.row(), range.end.row());
 7809                    let mut row = range.start.row();
 7810                    let positions =
 7811                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7812                            px(start)..px(end)
 7813                        } else {
 7814                            let start_x =
 7815                                display_map.x_for_display_point(range.start, &text_layout_details);
 7816                            let end_x =
 7817                                display_map.x_for_display_point(range.end, &text_layout_details);
 7818                            start_x.min(end_x)..start_x.max(end_x)
 7819                        };
 7820
 7821                    while row != end_row {
 7822                        if above {
 7823                            row.0 -= 1;
 7824                        } else {
 7825                            row.0 += 1;
 7826                        }
 7827
 7828                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7829                            &display_map,
 7830                            row,
 7831                            &positions,
 7832                            selection.reversed,
 7833                            &text_layout_details,
 7834                        ) {
 7835                            state.stack.push(new_selection.id);
 7836                            if above {
 7837                                new_selections.push(new_selection);
 7838                                new_selections.push(selection);
 7839                            } else {
 7840                                new_selections.push(selection);
 7841                                new_selections.push(new_selection);
 7842                            }
 7843
 7844                            continue 'outer;
 7845                        }
 7846                    }
 7847                }
 7848
 7849                new_selections.push(selection);
 7850            }
 7851        } else {
 7852            new_selections = selections;
 7853            new_selections.retain(|s| s.id != last_added_selection);
 7854            state.stack.pop();
 7855        }
 7856
 7857        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7858            s.select(new_selections);
 7859        });
 7860        if state.stack.len() > 1 {
 7861            self.add_selections_state = Some(state);
 7862        }
 7863    }
 7864
 7865    pub fn select_next_match_internal(
 7866        &mut self,
 7867        display_map: &DisplaySnapshot,
 7868        replace_newest: bool,
 7869        autoscroll: Option<Autoscroll>,
 7870        cx: &mut ViewContext<Self>,
 7871    ) -> Result<()> {
 7872        fn select_next_match_ranges(
 7873            this: &mut Editor,
 7874            range: Range<usize>,
 7875            replace_newest: bool,
 7876            auto_scroll: Option<Autoscroll>,
 7877            cx: &mut ViewContext<Editor>,
 7878        ) {
 7879            this.unfold_ranges(&[range.clone()], false, true, cx);
 7880            this.change_selections(auto_scroll, cx, |s| {
 7881                if replace_newest {
 7882                    s.delete(s.newest_anchor().id);
 7883                }
 7884                s.insert_range(range.clone());
 7885            });
 7886        }
 7887
 7888        let buffer = &display_map.buffer_snapshot;
 7889        let mut selections = self.selections.all::<usize>(cx);
 7890        if let Some(mut select_next_state) = self.select_next_state.take() {
 7891            let query = &select_next_state.query;
 7892            if !select_next_state.done {
 7893                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7894                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7895                let mut next_selected_range = None;
 7896
 7897                let bytes_after_last_selection =
 7898                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7899                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7900                let query_matches = query
 7901                    .stream_find_iter(bytes_after_last_selection)
 7902                    .map(|result| (last_selection.end, result))
 7903                    .chain(
 7904                        query
 7905                            .stream_find_iter(bytes_before_first_selection)
 7906                            .map(|result| (0, result)),
 7907                    );
 7908
 7909                for (start_offset, query_match) in query_matches {
 7910                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7911                    let offset_range =
 7912                        start_offset + query_match.start()..start_offset + query_match.end();
 7913                    let display_range = offset_range.start.to_display_point(display_map)
 7914                        ..offset_range.end.to_display_point(display_map);
 7915
 7916                    if !select_next_state.wordwise
 7917                        || (!movement::is_inside_word(display_map, display_range.start)
 7918                            && !movement::is_inside_word(display_map, display_range.end))
 7919                    {
 7920                        // TODO: This is n^2, because we might check all the selections
 7921                        if !selections
 7922                            .iter()
 7923                            .any(|selection| selection.range().overlaps(&offset_range))
 7924                        {
 7925                            next_selected_range = Some(offset_range);
 7926                            break;
 7927                        }
 7928                    }
 7929                }
 7930
 7931                if let Some(next_selected_range) = next_selected_range {
 7932                    select_next_match_ranges(
 7933                        self,
 7934                        next_selected_range,
 7935                        replace_newest,
 7936                        autoscroll,
 7937                        cx,
 7938                    );
 7939                } else {
 7940                    select_next_state.done = true;
 7941                }
 7942            }
 7943
 7944            self.select_next_state = Some(select_next_state);
 7945        } else {
 7946            let mut only_carets = true;
 7947            let mut same_text_selected = true;
 7948            let mut selected_text = None;
 7949
 7950            let mut selections_iter = selections.iter().peekable();
 7951            while let Some(selection) = selections_iter.next() {
 7952                if selection.start != selection.end {
 7953                    only_carets = false;
 7954                }
 7955
 7956                if same_text_selected {
 7957                    if selected_text.is_none() {
 7958                        selected_text =
 7959                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7960                    }
 7961
 7962                    if let Some(next_selection) = selections_iter.peek() {
 7963                        if next_selection.range().len() == selection.range().len() {
 7964                            let next_selected_text = buffer
 7965                                .text_for_range(next_selection.range())
 7966                                .collect::<String>();
 7967                            if Some(next_selected_text) != selected_text {
 7968                                same_text_selected = false;
 7969                                selected_text = None;
 7970                            }
 7971                        } else {
 7972                            same_text_selected = false;
 7973                            selected_text = None;
 7974                        }
 7975                    }
 7976                }
 7977            }
 7978
 7979            if only_carets {
 7980                for selection in &mut selections {
 7981                    let word_range = movement::surrounding_word(
 7982                        display_map,
 7983                        selection.start.to_display_point(display_map),
 7984                    );
 7985                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 7986                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 7987                    selection.goal = SelectionGoal::None;
 7988                    selection.reversed = false;
 7989                    select_next_match_ranges(
 7990                        self,
 7991                        selection.start..selection.end,
 7992                        replace_newest,
 7993                        autoscroll,
 7994                        cx,
 7995                    );
 7996                }
 7997
 7998                if selections.len() == 1 {
 7999                    let selection = selections
 8000                        .last()
 8001                        .expect("ensured that there's only one selection");
 8002                    let query = buffer
 8003                        .text_for_range(selection.start..selection.end)
 8004                        .collect::<String>();
 8005                    let is_empty = query.is_empty();
 8006                    let select_state = SelectNextState {
 8007                        query: AhoCorasick::new(&[query])?,
 8008                        wordwise: true,
 8009                        done: is_empty,
 8010                    };
 8011                    self.select_next_state = Some(select_state);
 8012                } else {
 8013                    self.select_next_state = None;
 8014                }
 8015            } else if let Some(selected_text) = selected_text {
 8016                self.select_next_state = Some(SelectNextState {
 8017                    query: AhoCorasick::new(&[selected_text])?,
 8018                    wordwise: false,
 8019                    done: false,
 8020                });
 8021                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8022            }
 8023        }
 8024        Ok(())
 8025    }
 8026
 8027    pub fn select_all_matches(
 8028        &mut self,
 8029        _action: &SelectAllMatches,
 8030        cx: &mut ViewContext<Self>,
 8031    ) -> Result<()> {
 8032        self.push_to_selection_history();
 8033        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8034
 8035        self.select_next_match_internal(&display_map, false, None, cx)?;
 8036        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8037            return Ok(());
 8038        };
 8039        if select_next_state.done {
 8040            return Ok(());
 8041        }
 8042
 8043        let mut new_selections = self.selections.all::<usize>(cx);
 8044
 8045        let buffer = &display_map.buffer_snapshot;
 8046        let query_matches = select_next_state
 8047            .query
 8048            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8049
 8050        for query_match in query_matches {
 8051            let query_match = query_match.unwrap(); // can only fail due to I/O
 8052            let offset_range = query_match.start()..query_match.end();
 8053            let display_range = offset_range.start.to_display_point(&display_map)
 8054                ..offset_range.end.to_display_point(&display_map);
 8055
 8056            if !select_next_state.wordwise
 8057                || (!movement::is_inside_word(&display_map, display_range.start)
 8058                    && !movement::is_inside_word(&display_map, display_range.end))
 8059            {
 8060                self.selections.change_with(cx, |selections| {
 8061                    new_selections.push(Selection {
 8062                        id: selections.new_selection_id(),
 8063                        start: offset_range.start,
 8064                        end: offset_range.end,
 8065                        reversed: false,
 8066                        goal: SelectionGoal::None,
 8067                    });
 8068                });
 8069            }
 8070        }
 8071
 8072        new_selections.sort_by_key(|selection| selection.start);
 8073        let mut ix = 0;
 8074        while ix + 1 < new_selections.len() {
 8075            let current_selection = &new_selections[ix];
 8076            let next_selection = &new_selections[ix + 1];
 8077            if current_selection.range().overlaps(&next_selection.range()) {
 8078                if current_selection.id < next_selection.id {
 8079                    new_selections.remove(ix + 1);
 8080                } else {
 8081                    new_selections.remove(ix);
 8082                }
 8083            } else {
 8084                ix += 1;
 8085            }
 8086        }
 8087
 8088        select_next_state.done = true;
 8089        self.unfold_ranges(
 8090            &new_selections
 8091                .iter()
 8092                .map(|selection| selection.range())
 8093                .collect::<Vec<_>>(),
 8094            false,
 8095            false,
 8096            cx,
 8097        );
 8098        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8099            selections.select(new_selections)
 8100        });
 8101
 8102        Ok(())
 8103    }
 8104
 8105    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8106        self.push_to_selection_history();
 8107        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8108        self.select_next_match_internal(
 8109            &display_map,
 8110            action.replace_newest,
 8111            Some(Autoscroll::newest()),
 8112            cx,
 8113        )?;
 8114        Ok(())
 8115    }
 8116
 8117    pub fn select_previous(
 8118        &mut self,
 8119        action: &SelectPrevious,
 8120        cx: &mut ViewContext<Self>,
 8121    ) -> Result<()> {
 8122        self.push_to_selection_history();
 8123        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8124        let buffer = &display_map.buffer_snapshot;
 8125        let mut selections = self.selections.all::<usize>(cx);
 8126        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8127            let query = &select_prev_state.query;
 8128            if !select_prev_state.done {
 8129                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8130                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8131                let mut next_selected_range = None;
 8132                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8133                let bytes_before_last_selection =
 8134                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8135                let bytes_after_first_selection =
 8136                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8137                let query_matches = query
 8138                    .stream_find_iter(bytes_before_last_selection)
 8139                    .map(|result| (last_selection.start, result))
 8140                    .chain(
 8141                        query
 8142                            .stream_find_iter(bytes_after_first_selection)
 8143                            .map(|result| (buffer.len(), result)),
 8144                    );
 8145                for (end_offset, query_match) in query_matches {
 8146                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8147                    let offset_range =
 8148                        end_offset - query_match.end()..end_offset - query_match.start();
 8149                    let display_range = offset_range.start.to_display_point(&display_map)
 8150                        ..offset_range.end.to_display_point(&display_map);
 8151
 8152                    if !select_prev_state.wordwise
 8153                        || (!movement::is_inside_word(&display_map, display_range.start)
 8154                            && !movement::is_inside_word(&display_map, display_range.end))
 8155                    {
 8156                        next_selected_range = Some(offset_range);
 8157                        break;
 8158                    }
 8159                }
 8160
 8161                if let Some(next_selected_range) = next_selected_range {
 8162                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8163                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8164                        if action.replace_newest {
 8165                            s.delete(s.newest_anchor().id);
 8166                        }
 8167                        s.insert_range(next_selected_range);
 8168                    });
 8169                } else {
 8170                    select_prev_state.done = true;
 8171                }
 8172            }
 8173
 8174            self.select_prev_state = Some(select_prev_state);
 8175        } else {
 8176            let mut only_carets = true;
 8177            let mut same_text_selected = true;
 8178            let mut selected_text = None;
 8179
 8180            let mut selections_iter = selections.iter().peekable();
 8181            while let Some(selection) = selections_iter.next() {
 8182                if selection.start != selection.end {
 8183                    only_carets = false;
 8184                }
 8185
 8186                if same_text_selected {
 8187                    if selected_text.is_none() {
 8188                        selected_text =
 8189                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8190                    }
 8191
 8192                    if let Some(next_selection) = selections_iter.peek() {
 8193                        if next_selection.range().len() == selection.range().len() {
 8194                            let next_selected_text = buffer
 8195                                .text_for_range(next_selection.range())
 8196                                .collect::<String>();
 8197                            if Some(next_selected_text) != selected_text {
 8198                                same_text_selected = false;
 8199                                selected_text = None;
 8200                            }
 8201                        } else {
 8202                            same_text_selected = false;
 8203                            selected_text = None;
 8204                        }
 8205                    }
 8206                }
 8207            }
 8208
 8209            if only_carets {
 8210                for selection in &mut selections {
 8211                    let word_range = movement::surrounding_word(
 8212                        &display_map,
 8213                        selection.start.to_display_point(&display_map),
 8214                    );
 8215                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8216                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8217                    selection.goal = SelectionGoal::None;
 8218                    selection.reversed = false;
 8219                }
 8220                if selections.len() == 1 {
 8221                    let selection = selections
 8222                        .last()
 8223                        .expect("ensured that there's only one selection");
 8224                    let query = buffer
 8225                        .text_for_range(selection.start..selection.end)
 8226                        .collect::<String>();
 8227                    let is_empty = query.is_empty();
 8228                    let select_state = SelectNextState {
 8229                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8230                        wordwise: true,
 8231                        done: is_empty,
 8232                    };
 8233                    self.select_prev_state = Some(select_state);
 8234                } else {
 8235                    self.select_prev_state = None;
 8236                }
 8237
 8238                self.unfold_ranges(
 8239                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8240                    false,
 8241                    true,
 8242                    cx,
 8243                );
 8244                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8245                    s.select(selections);
 8246                });
 8247            } else if let Some(selected_text) = selected_text {
 8248                self.select_prev_state = Some(SelectNextState {
 8249                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8250                    wordwise: false,
 8251                    done: false,
 8252                });
 8253                self.select_previous(action, cx)?;
 8254            }
 8255        }
 8256        Ok(())
 8257    }
 8258
 8259    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8260        if self.read_only(cx) {
 8261            return;
 8262        }
 8263        let text_layout_details = &self.text_layout_details(cx);
 8264        self.transact(cx, |this, cx| {
 8265            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8266            let mut edits = Vec::new();
 8267            let mut selection_edit_ranges = Vec::new();
 8268            let mut last_toggled_row = None;
 8269            let snapshot = this.buffer.read(cx).read(cx);
 8270            let empty_str: Arc<str> = Arc::default();
 8271            let mut suffixes_inserted = Vec::new();
 8272            let ignore_indent = action.ignore_indent;
 8273
 8274            fn comment_prefix_range(
 8275                snapshot: &MultiBufferSnapshot,
 8276                row: MultiBufferRow,
 8277                comment_prefix: &str,
 8278                comment_prefix_whitespace: &str,
 8279                ignore_indent: bool,
 8280            ) -> Range<Point> {
 8281                let indent_size = if ignore_indent {
 8282                    0
 8283                } else {
 8284                    snapshot.indent_size_for_line(row).len
 8285                };
 8286
 8287                let start = Point::new(row.0, indent_size);
 8288
 8289                let mut line_bytes = snapshot
 8290                    .bytes_in_range(start..snapshot.max_point())
 8291                    .flatten()
 8292                    .copied();
 8293
 8294                // If this line currently begins with the line comment prefix, then record
 8295                // the range containing the prefix.
 8296                if line_bytes
 8297                    .by_ref()
 8298                    .take(comment_prefix.len())
 8299                    .eq(comment_prefix.bytes())
 8300                {
 8301                    // Include any whitespace that matches the comment prefix.
 8302                    let matching_whitespace_len = line_bytes
 8303                        .zip(comment_prefix_whitespace.bytes())
 8304                        .take_while(|(a, b)| a == b)
 8305                        .count() as u32;
 8306                    let end = Point::new(
 8307                        start.row,
 8308                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8309                    );
 8310                    start..end
 8311                } else {
 8312                    start..start
 8313                }
 8314            }
 8315
 8316            fn comment_suffix_range(
 8317                snapshot: &MultiBufferSnapshot,
 8318                row: MultiBufferRow,
 8319                comment_suffix: &str,
 8320                comment_suffix_has_leading_space: bool,
 8321            ) -> Range<Point> {
 8322                let end = Point::new(row.0, snapshot.line_len(row));
 8323                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8324
 8325                let mut line_end_bytes = snapshot
 8326                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8327                    .flatten()
 8328                    .copied();
 8329
 8330                let leading_space_len = if suffix_start_column > 0
 8331                    && line_end_bytes.next() == Some(b' ')
 8332                    && comment_suffix_has_leading_space
 8333                {
 8334                    1
 8335                } else {
 8336                    0
 8337                };
 8338
 8339                // If this line currently begins with the line comment prefix, then record
 8340                // the range containing the prefix.
 8341                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8342                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8343                    start..end
 8344                } else {
 8345                    end..end
 8346                }
 8347            }
 8348
 8349            // TODO: Handle selections that cross excerpts
 8350            for selection in &mut selections {
 8351                let start_column = snapshot
 8352                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8353                    .len;
 8354                let language = if let Some(language) =
 8355                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8356                {
 8357                    language
 8358                } else {
 8359                    continue;
 8360                };
 8361
 8362                selection_edit_ranges.clear();
 8363
 8364                // If multiple selections contain a given row, avoid processing that
 8365                // row more than once.
 8366                let mut start_row = MultiBufferRow(selection.start.row);
 8367                if last_toggled_row == Some(start_row) {
 8368                    start_row = start_row.next_row();
 8369                }
 8370                let end_row =
 8371                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8372                        MultiBufferRow(selection.end.row - 1)
 8373                    } else {
 8374                        MultiBufferRow(selection.end.row)
 8375                    };
 8376                last_toggled_row = Some(end_row);
 8377
 8378                if start_row > end_row {
 8379                    continue;
 8380                }
 8381
 8382                // If the language has line comments, toggle those.
 8383                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8384
 8385                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8386                if ignore_indent {
 8387                    full_comment_prefixes = full_comment_prefixes
 8388                        .into_iter()
 8389                        .map(|s| Arc::from(s.trim_end()))
 8390                        .collect();
 8391                }
 8392
 8393                if !full_comment_prefixes.is_empty() {
 8394                    let first_prefix = full_comment_prefixes
 8395                        .first()
 8396                        .expect("prefixes is non-empty");
 8397                    let prefix_trimmed_lengths = full_comment_prefixes
 8398                        .iter()
 8399                        .map(|p| p.trim_end_matches(' ').len())
 8400                        .collect::<SmallVec<[usize; 4]>>();
 8401
 8402                    let mut all_selection_lines_are_comments = true;
 8403
 8404                    for row in start_row.0..=end_row.0 {
 8405                        let row = MultiBufferRow(row);
 8406                        if start_row < end_row && snapshot.is_line_blank(row) {
 8407                            continue;
 8408                        }
 8409
 8410                        let prefix_range = full_comment_prefixes
 8411                            .iter()
 8412                            .zip(prefix_trimmed_lengths.iter().copied())
 8413                            .map(|(prefix, trimmed_prefix_len)| {
 8414                                comment_prefix_range(
 8415                                    snapshot.deref(),
 8416                                    row,
 8417                                    &prefix[..trimmed_prefix_len],
 8418                                    &prefix[trimmed_prefix_len..],
 8419                                    ignore_indent,
 8420                                )
 8421                            })
 8422                            .max_by_key(|range| range.end.column - range.start.column)
 8423                            .expect("prefixes is non-empty");
 8424
 8425                        if prefix_range.is_empty() {
 8426                            all_selection_lines_are_comments = false;
 8427                        }
 8428
 8429                        selection_edit_ranges.push(prefix_range);
 8430                    }
 8431
 8432                    if all_selection_lines_are_comments {
 8433                        edits.extend(
 8434                            selection_edit_ranges
 8435                                .iter()
 8436                                .cloned()
 8437                                .map(|range| (range, empty_str.clone())),
 8438                        );
 8439                    } else {
 8440                        let min_column = selection_edit_ranges
 8441                            .iter()
 8442                            .map(|range| range.start.column)
 8443                            .min()
 8444                            .unwrap_or(0);
 8445                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8446                            let position = Point::new(range.start.row, min_column);
 8447                            (position..position, first_prefix.clone())
 8448                        }));
 8449                    }
 8450                } else if let Some((full_comment_prefix, comment_suffix)) =
 8451                    language.block_comment_delimiters()
 8452                {
 8453                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8454                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8455                    let prefix_range = comment_prefix_range(
 8456                        snapshot.deref(),
 8457                        start_row,
 8458                        comment_prefix,
 8459                        comment_prefix_whitespace,
 8460                        ignore_indent,
 8461                    );
 8462                    let suffix_range = comment_suffix_range(
 8463                        snapshot.deref(),
 8464                        end_row,
 8465                        comment_suffix.trim_start_matches(' '),
 8466                        comment_suffix.starts_with(' '),
 8467                    );
 8468
 8469                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8470                        edits.push((
 8471                            prefix_range.start..prefix_range.start,
 8472                            full_comment_prefix.clone(),
 8473                        ));
 8474                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8475                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8476                    } else {
 8477                        edits.push((prefix_range, empty_str.clone()));
 8478                        edits.push((suffix_range, empty_str.clone()));
 8479                    }
 8480                } else {
 8481                    continue;
 8482                }
 8483            }
 8484
 8485            drop(snapshot);
 8486            this.buffer.update(cx, |buffer, cx| {
 8487                buffer.edit(edits, None, cx);
 8488            });
 8489
 8490            // Adjust selections so that they end before any comment suffixes that
 8491            // were inserted.
 8492            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8493            let mut selections = this.selections.all::<Point>(cx);
 8494            let snapshot = this.buffer.read(cx).read(cx);
 8495            for selection in &mut selections {
 8496                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8497                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8498                        Ordering::Less => {
 8499                            suffixes_inserted.next();
 8500                            continue;
 8501                        }
 8502                        Ordering::Greater => break,
 8503                        Ordering::Equal => {
 8504                            if selection.end.column == snapshot.line_len(row) {
 8505                                if selection.is_empty() {
 8506                                    selection.start.column -= suffix_len as u32;
 8507                                }
 8508                                selection.end.column -= suffix_len as u32;
 8509                            }
 8510                            break;
 8511                        }
 8512                    }
 8513                }
 8514            }
 8515
 8516            drop(snapshot);
 8517            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8518
 8519            let selections = this.selections.all::<Point>(cx);
 8520            let selections_on_single_row = selections.windows(2).all(|selections| {
 8521                selections[0].start.row == selections[1].start.row
 8522                    && selections[0].end.row == selections[1].end.row
 8523                    && selections[0].start.row == selections[0].end.row
 8524            });
 8525            let selections_selecting = selections
 8526                .iter()
 8527                .any(|selection| selection.start != selection.end);
 8528            let advance_downwards = action.advance_downwards
 8529                && selections_on_single_row
 8530                && !selections_selecting
 8531                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8532
 8533            if advance_downwards {
 8534                let snapshot = this.buffer.read(cx).snapshot(cx);
 8535
 8536                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8537                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8538                        let mut point = display_point.to_point(display_snapshot);
 8539                        point.row += 1;
 8540                        point = snapshot.clip_point(point, Bias::Left);
 8541                        let display_point = point.to_display_point(display_snapshot);
 8542                        let goal = SelectionGoal::HorizontalPosition(
 8543                            display_snapshot
 8544                                .x_for_display_point(display_point, text_layout_details)
 8545                                .into(),
 8546                        );
 8547                        (display_point, goal)
 8548                    })
 8549                });
 8550            }
 8551        });
 8552    }
 8553
 8554    pub fn select_enclosing_symbol(
 8555        &mut self,
 8556        _: &SelectEnclosingSymbol,
 8557        cx: &mut ViewContext<Self>,
 8558    ) {
 8559        let buffer = self.buffer.read(cx).snapshot(cx);
 8560        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8561
 8562        fn update_selection(
 8563            selection: &Selection<usize>,
 8564            buffer_snap: &MultiBufferSnapshot,
 8565        ) -> Option<Selection<usize>> {
 8566            let cursor = selection.head();
 8567            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8568            for symbol in symbols.iter().rev() {
 8569                let start = symbol.range.start.to_offset(buffer_snap);
 8570                let end = symbol.range.end.to_offset(buffer_snap);
 8571                let new_range = start..end;
 8572                if start < selection.start || end > selection.end {
 8573                    return Some(Selection {
 8574                        id: selection.id,
 8575                        start: new_range.start,
 8576                        end: new_range.end,
 8577                        goal: SelectionGoal::None,
 8578                        reversed: selection.reversed,
 8579                    });
 8580                }
 8581            }
 8582            None
 8583        }
 8584
 8585        let mut selected_larger_symbol = false;
 8586        let new_selections = old_selections
 8587            .iter()
 8588            .map(|selection| match update_selection(selection, &buffer) {
 8589                Some(new_selection) => {
 8590                    if new_selection.range() != selection.range() {
 8591                        selected_larger_symbol = true;
 8592                    }
 8593                    new_selection
 8594                }
 8595                None => selection.clone(),
 8596            })
 8597            .collect::<Vec<_>>();
 8598
 8599        if selected_larger_symbol {
 8600            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8601                s.select(new_selections);
 8602            });
 8603        }
 8604    }
 8605
 8606    pub fn select_larger_syntax_node(
 8607        &mut self,
 8608        _: &SelectLargerSyntaxNode,
 8609        cx: &mut ViewContext<Self>,
 8610    ) {
 8611        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8612        let buffer = self.buffer.read(cx).snapshot(cx);
 8613        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8614
 8615        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8616        let mut selected_larger_node = false;
 8617        let new_selections = old_selections
 8618            .iter()
 8619            .map(|selection| {
 8620                let old_range = selection.start..selection.end;
 8621                let mut new_range = old_range.clone();
 8622                while let Some(containing_range) =
 8623                    buffer.range_for_syntax_ancestor(new_range.clone())
 8624                {
 8625                    new_range = containing_range;
 8626                    if !display_map.intersects_fold(new_range.start)
 8627                        && !display_map.intersects_fold(new_range.end)
 8628                    {
 8629                        break;
 8630                    }
 8631                }
 8632
 8633                selected_larger_node |= new_range != old_range;
 8634                Selection {
 8635                    id: selection.id,
 8636                    start: new_range.start,
 8637                    end: new_range.end,
 8638                    goal: SelectionGoal::None,
 8639                    reversed: selection.reversed,
 8640                }
 8641            })
 8642            .collect::<Vec<_>>();
 8643
 8644        if selected_larger_node {
 8645            stack.push(old_selections);
 8646            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8647                s.select(new_selections);
 8648            });
 8649        }
 8650        self.select_larger_syntax_node_stack = stack;
 8651    }
 8652
 8653    pub fn select_smaller_syntax_node(
 8654        &mut self,
 8655        _: &SelectSmallerSyntaxNode,
 8656        cx: &mut ViewContext<Self>,
 8657    ) {
 8658        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8659        if let Some(selections) = stack.pop() {
 8660            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8661                s.select(selections.to_vec());
 8662            });
 8663        }
 8664        self.select_larger_syntax_node_stack = stack;
 8665    }
 8666
 8667    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8668        if !EditorSettings::get_global(cx).gutter.runnables {
 8669            self.clear_tasks();
 8670            return Task::ready(());
 8671        }
 8672        let project = self.project.as_ref().map(Model::downgrade);
 8673        cx.spawn(|this, mut cx| async move {
 8674            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8675            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8676                return;
 8677            };
 8678            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8679                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8680            }) else {
 8681                return;
 8682            };
 8683
 8684            let hide_runnables = project
 8685                .update(&mut cx, |project, cx| {
 8686                    // Do not display any test indicators in non-dev server remote projects.
 8687                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8688                })
 8689                .unwrap_or(true);
 8690            if hide_runnables {
 8691                return;
 8692            }
 8693            let new_rows =
 8694                cx.background_executor()
 8695                    .spawn({
 8696                        let snapshot = display_snapshot.clone();
 8697                        async move {
 8698                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8699                        }
 8700                    })
 8701                    .await;
 8702            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8703
 8704            this.update(&mut cx, |this, _| {
 8705                this.clear_tasks();
 8706                for (key, value) in rows {
 8707                    this.insert_tasks(key, value);
 8708                }
 8709            })
 8710            .ok();
 8711        })
 8712    }
 8713    fn fetch_runnable_ranges(
 8714        snapshot: &DisplaySnapshot,
 8715        range: Range<Anchor>,
 8716    ) -> Vec<language::RunnableRange> {
 8717        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8718    }
 8719
 8720    fn runnable_rows(
 8721        project: Model<Project>,
 8722        snapshot: DisplaySnapshot,
 8723        runnable_ranges: Vec<RunnableRange>,
 8724        mut cx: AsyncWindowContext,
 8725    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8726        runnable_ranges
 8727            .into_iter()
 8728            .filter_map(|mut runnable| {
 8729                let tasks = cx
 8730                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8731                    .ok()?;
 8732                if tasks.is_empty() {
 8733                    return None;
 8734                }
 8735
 8736                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8737
 8738                let row = snapshot
 8739                    .buffer_snapshot
 8740                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8741                    .1
 8742                    .start
 8743                    .row;
 8744
 8745                let context_range =
 8746                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8747                Some((
 8748                    (runnable.buffer_id, row),
 8749                    RunnableTasks {
 8750                        templates: tasks,
 8751                        offset: MultiBufferOffset(runnable.run_range.start),
 8752                        context_range,
 8753                        column: point.column,
 8754                        extra_variables: runnable.extra_captures,
 8755                    },
 8756                ))
 8757            })
 8758            .collect()
 8759    }
 8760
 8761    fn templates_with_tags(
 8762        project: &Model<Project>,
 8763        runnable: &mut Runnable,
 8764        cx: &WindowContext<'_>,
 8765    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8766        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8767            let (worktree_id, file) = project
 8768                .buffer_for_id(runnable.buffer, cx)
 8769                .and_then(|buffer| buffer.read(cx).file())
 8770                .map(|file| (file.worktree_id(cx), file.clone()))
 8771                .unzip();
 8772
 8773            (
 8774                project.task_store().read(cx).task_inventory().cloned(),
 8775                worktree_id,
 8776                file,
 8777            )
 8778        });
 8779
 8780        let tags = mem::take(&mut runnable.tags);
 8781        let mut tags: Vec<_> = tags
 8782            .into_iter()
 8783            .flat_map(|tag| {
 8784                let tag = tag.0.clone();
 8785                inventory
 8786                    .as_ref()
 8787                    .into_iter()
 8788                    .flat_map(|inventory| {
 8789                        inventory.read(cx).list_tasks(
 8790                            file.clone(),
 8791                            Some(runnable.language.clone()),
 8792                            worktree_id,
 8793                            cx,
 8794                        )
 8795                    })
 8796                    .filter(move |(_, template)| {
 8797                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8798                    })
 8799            })
 8800            .sorted_by_key(|(kind, _)| kind.to_owned())
 8801            .collect();
 8802        if let Some((leading_tag_source, _)) = tags.first() {
 8803            // Strongest source wins; if we have worktree tag binding, prefer that to
 8804            // global and language bindings;
 8805            // if we have a global binding, prefer that to language binding.
 8806            let first_mismatch = tags
 8807                .iter()
 8808                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8809            if let Some(index) = first_mismatch {
 8810                tags.truncate(index);
 8811            }
 8812        }
 8813
 8814        tags
 8815    }
 8816
 8817    pub fn move_to_enclosing_bracket(
 8818        &mut self,
 8819        _: &MoveToEnclosingBracket,
 8820        cx: &mut ViewContext<Self>,
 8821    ) {
 8822        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8823            s.move_offsets_with(|snapshot, selection| {
 8824                let Some(enclosing_bracket_ranges) =
 8825                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8826                else {
 8827                    return;
 8828                };
 8829
 8830                let mut best_length = usize::MAX;
 8831                let mut best_inside = false;
 8832                let mut best_in_bracket_range = false;
 8833                let mut best_destination = None;
 8834                for (open, close) in enclosing_bracket_ranges {
 8835                    let close = close.to_inclusive();
 8836                    let length = close.end() - open.start;
 8837                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8838                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8839                        || close.contains(&selection.head());
 8840
 8841                    // If best is next to a bracket and current isn't, skip
 8842                    if !in_bracket_range && best_in_bracket_range {
 8843                        continue;
 8844                    }
 8845
 8846                    // Prefer smaller lengths unless best is inside and current isn't
 8847                    if length > best_length && (best_inside || !inside) {
 8848                        continue;
 8849                    }
 8850
 8851                    best_length = length;
 8852                    best_inside = inside;
 8853                    best_in_bracket_range = in_bracket_range;
 8854                    best_destination = Some(
 8855                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8856                            if inside {
 8857                                open.end
 8858                            } else {
 8859                                open.start
 8860                            }
 8861                        } else if inside {
 8862                            *close.start()
 8863                        } else {
 8864                            *close.end()
 8865                        },
 8866                    );
 8867                }
 8868
 8869                if let Some(destination) = best_destination {
 8870                    selection.collapse_to(destination, SelectionGoal::None);
 8871                }
 8872            })
 8873        });
 8874    }
 8875
 8876    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8877        self.end_selection(cx);
 8878        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8879        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8880            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8881            self.select_next_state = entry.select_next_state;
 8882            self.select_prev_state = entry.select_prev_state;
 8883            self.add_selections_state = entry.add_selections_state;
 8884            self.request_autoscroll(Autoscroll::newest(), cx);
 8885        }
 8886        self.selection_history.mode = SelectionHistoryMode::Normal;
 8887    }
 8888
 8889    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8890        self.end_selection(cx);
 8891        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8892        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8893            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8894            self.select_next_state = entry.select_next_state;
 8895            self.select_prev_state = entry.select_prev_state;
 8896            self.add_selections_state = entry.add_selections_state;
 8897            self.request_autoscroll(Autoscroll::newest(), cx);
 8898        }
 8899        self.selection_history.mode = SelectionHistoryMode::Normal;
 8900    }
 8901
 8902    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8903        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8904    }
 8905
 8906    pub fn expand_excerpts_down(
 8907        &mut self,
 8908        action: &ExpandExcerptsDown,
 8909        cx: &mut ViewContext<Self>,
 8910    ) {
 8911        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8912    }
 8913
 8914    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8915        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8916    }
 8917
 8918    pub fn expand_excerpts_for_direction(
 8919        &mut self,
 8920        lines: u32,
 8921        direction: ExpandExcerptDirection,
 8922        cx: &mut ViewContext<Self>,
 8923    ) {
 8924        let selections = self.selections.disjoint_anchors();
 8925
 8926        let lines = if lines == 0 {
 8927            EditorSettings::get_global(cx).expand_excerpt_lines
 8928        } else {
 8929            lines
 8930        };
 8931
 8932        self.buffer.update(cx, |buffer, cx| {
 8933            buffer.expand_excerpts(
 8934                selections
 8935                    .iter()
 8936                    .map(|selection| selection.head().excerpt_id)
 8937                    .dedup(),
 8938                lines,
 8939                direction,
 8940                cx,
 8941            )
 8942        })
 8943    }
 8944
 8945    pub fn expand_excerpt(
 8946        &mut self,
 8947        excerpt: ExcerptId,
 8948        direction: ExpandExcerptDirection,
 8949        cx: &mut ViewContext<Self>,
 8950    ) {
 8951        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8952        self.buffer.update(cx, |buffer, cx| {
 8953            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8954        })
 8955    }
 8956
 8957    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8958        self.go_to_diagnostic_impl(Direction::Next, cx)
 8959    }
 8960
 8961    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8962        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8963    }
 8964
 8965    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8966        let buffer = self.buffer.read(cx).snapshot(cx);
 8967        let selection = self.selections.newest::<usize>(cx);
 8968
 8969        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8970        if direction == Direction::Next {
 8971            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8972                let (group_id, jump_to) = popover.activation_info();
 8973                if self.activate_diagnostics(group_id, cx) {
 8974                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8975                        let mut new_selection = s.newest_anchor().clone();
 8976                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8977                        s.select_anchors(vec![new_selection.clone()]);
 8978                    });
 8979                }
 8980                return;
 8981            }
 8982        }
 8983
 8984        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8985            active_diagnostics
 8986                .primary_range
 8987                .to_offset(&buffer)
 8988                .to_inclusive()
 8989        });
 8990        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8991            if active_primary_range.contains(&selection.head()) {
 8992                *active_primary_range.start()
 8993            } else {
 8994                selection.head()
 8995            }
 8996        } else {
 8997            selection.head()
 8998        };
 8999        let snapshot = self.snapshot(cx);
 9000        loop {
 9001            let diagnostics = if direction == Direction::Prev {
 9002                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9003            } else {
 9004                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9005            }
 9006            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9007            let group = diagnostics
 9008                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9009                // be sorted in a stable way
 9010                // skip until we are at current active diagnostic, if it exists
 9011                .skip_while(|entry| {
 9012                    (match direction {
 9013                        Direction::Prev => entry.range.start >= search_start,
 9014                        Direction::Next => entry.range.start <= search_start,
 9015                    }) && self
 9016                        .active_diagnostics
 9017                        .as_ref()
 9018                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9019                })
 9020                .find_map(|entry| {
 9021                    if entry.diagnostic.is_primary
 9022                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9023                        && !entry.range.is_empty()
 9024                        // if we match with the active diagnostic, skip it
 9025                        && Some(entry.diagnostic.group_id)
 9026                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9027                    {
 9028                        Some((entry.range, entry.diagnostic.group_id))
 9029                    } else {
 9030                        None
 9031                    }
 9032                });
 9033
 9034            if let Some((primary_range, group_id)) = group {
 9035                if self.activate_diagnostics(group_id, cx) {
 9036                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9037                        s.select(vec![Selection {
 9038                            id: selection.id,
 9039                            start: primary_range.start,
 9040                            end: primary_range.start,
 9041                            reversed: false,
 9042                            goal: SelectionGoal::None,
 9043                        }]);
 9044                    });
 9045                }
 9046                break;
 9047            } else {
 9048                // Cycle around to the start of the buffer, potentially moving back to the start of
 9049                // the currently active diagnostic.
 9050                active_primary_range.take();
 9051                if direction == Direction::Prev {
 9052                    if search_start == buffer.len() {
 9053                        break;
 9054                    } else {
 9055                        search_start = buffer.len();
 9056                    }
 9057                } else if search_start == 0 {
 9058                    break;
 9059                } else {
 9060                    search_start = 0;
 9061                }
 9062            }
 9063        }
 9064    }
 9065
 9066    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9067        let snapshot = self.snapshot(cx);
 9068        let selection = self.selections.newest::<Point>(cx);
 9069        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9070    }
 9071
 9072    fn go_to_hunk_after_position(
 9073        &mut self,
 9074        snapshot: &EditorSnapshot,
 9075        position: Point,
 9076        cx: &mut ViewContext<'_, Editor>,
 9077    ) -> Option<MultiBufferDiffHunk> {
 9078        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9079            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9080                snapshot,
 9081                position,
 9082                ix > 0,
 9083                snapshot.diff_map.diff_hunks_in_range(
 9084                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9085                    &snapshot.buffer_snapshot,
 9086                ),
 9087                cx,
 9088            ) {
 9089                return Some(hunk);
 9090            }
 9091        }
 9092        None
 9093    }
 9094
 9095    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9096        let snapshot = self.snapshot(cx);
 9097        let selection = self.selections.newest::<Point>(cx);
 9098        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9099    }
 9100
 9101    fn go_to_hunk_before_position(
 9102        &mut self,
 9103        snapshot: &EditorSnapshot,
 9104        position: Point,
 9105        cx: &mut ViewContext<'_, Editor>,
 9106    ) -> Option<MultiBufferDiffHunk> {
 9107        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9108            .into_iter()
 9109            .enumerate()
 9110        {
 9111            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9112                snapshot,
 9113                position,
 9114                ix > 0,
 9115                snapshot
 9116                    .diff_map
 9117                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9118                cx,
 9119            ) {
 9120                return Some(hunk);
 9121            }
 9122        }
 9123        None
 9124    }
 9125
 9126    fn go_to_next_hunk_in_direction(
 9127        &mut self,
 9128        snapshot: &DisplaySnapshot,
 9129        initial_point: Point,
 9130        is_wrapped: bool,
 9131        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9132        cx: &mut ViewContext<Editor>,
 9133    ) -> Option<MultiBufferDiffHunk> {
 9134        let display_point = initial_point.to_display_point(snapshot);
 9135        let mut hunks = hunks
 9136            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9137            .filter(|(display_hunk, _)| {
 9138                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9139            })
 9140            .dedup();
 9141
 9142        if let Some((display_hunk, hunk)) = hunks.next() {
 9143            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9144                let row = display_hunk.start_display_row();
 9145                let point = DisplayPoint::new(row, 0);
 9146                s.select_display_ranges([point..point]);
 9147            });
 9148
 9149            Some(hunk)
 9150        } else {
 9151            None
 9152        }
 9153    }
 9154
 9155    pub fn go_to_definition(
 9156        &mut self,
 9157        _: &GoToDefinition,
 9158        cx: &mut ViewContext<Self>,
 9159    ) -> Task<Result<Navigated>> {
 9160        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9161        cx.spawn(|editor, mut cx| async move {
 9162            if definition.await? == Navigated::Yes {
 9163                return Ok(Navigated::Yes);
 9164            }
 9165            match editor.update(&mut cx, |editor, cx| {
 9166                editor.find_all_references(&FindAllReferences, cx)
 9167            })? {
 9168                Some(references) => references.await,
 9169                None => Ok(Navigated::No),
 9170            }
 9171        })
 9172    }
 9173
 9174    pub fn go_to_declaration(
 9175        &mut self,
 9176        _: &GoToDeclaration,
 9177        cx: &mut ViewContext<Self>,
 9178    ) -> Task<Result<Navigated>> {
 9179        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9180    }
 9181
 9182    pub fn go_to_declaration_split(
 9183        &mut self,
 9184        _: &GoToDeclaration,
 9185        cx: &mut ViewContext<Self>,
 9186    ) -> Task<Result<Navigated>> {
 9187        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9188    }
 9189
 9190    pub fn go_to_implementation(
 9191        &mut self,
 9192        _: &GoToImplementation,
 9193        cx: &mut ViewContext<Self>,
 9194    ) -> Task<Result<Navigated>> {
 9195        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9196    }
 9197
 9198    pub fn go_to_implementation_split(
 9199        &mut self,
 9200        _: &GoToImplementationSplit,
 9201        cx: &mut ViewContext<Self>,
 9202    ) -> Task<Result<Navigated>> {
 9203        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9204    }
 9205
 9206    pub fn go_to_type_definition(
 9207        &mut self,
 9208        _: &GoToTypeDefinition,
 9209        cx: &mut ViewContext<Self>,
 9210    ) -> Task<Result<Navigated>> {
 9211        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9212    }
 9213
 9214    pub fn go_to_definition_split(
 9215        &mut self,
 9216        _: &GoToDefinitionSplit,
 9217        cx: &mut ViewContext<Self>,
 9218    ) -> Task<Result<Navigated>> {
 9219        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9220    }
 9221
 9222    pub fn go_to_type_definition_split(
 9223        &mut self,
 9224        _: &GoToTypeDefinitionSplit,
 9225        cx: &mut ViewContext<Self>,
 9226    ) -> Task<Result<Navigated>> {
 9227        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9228    }
 9229
 9230    fn go_to_definition_of_kind(
 9231        &mut self,
 9232        kind: GotoDefinitionKind,
 9233        split: bool,
 9234        cx: &mut ViewContext<Self>,
 9235    ) -> Task<Result<Navigated>> {
 9236        let Some(provider) = self.semantics_provider.clone() else {
 9237            return Task::ready(Ok(Navigated::No));
 9238        };
 9239        let head = self.selections.newest::<usize>(cx).head();
 9240        let buffer = self.buffer.read(cx);
 9241        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9242            text_anchor
 9243        } else {
 9244            return Task::ready(Ok(Navigated::No));
 9245        };
 9246
 9247        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9248            return Task::ready(Ok(Navigated::No));
 9249        };
 9250
 9251        cx.spawn(|editor, mut cx| async move {
 9252            let definitions = definitions.await?;
 9253            let navigated = editor
 9254                .update(&mut cx, |editor, cx| {
 9255                    editor.navigate_to_hover_links(
 9256                        Some(kind),
 9257                        definitions
 9258                            .into_iter()
 9259                            .filter(|location| {
 9260                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9261                            })
 9262                            .map(HoverLink::Text)
 9263                            .collect::<Vec<_>>(),
 9264                        split,
 9265                        cx,
 9266                    )
 9267                })?
 9268                .await?;
 9269            anyhow::Ok(navigated)
 9270        })
 9271    }
 9272
 9273    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9274        let position = self.selections.newest_anchor().head();
 9275        let Some((buffer, buffer_position)) =
 9276            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9277        else {
 9278            return;
 9279        };
 9280
 9281        cx.spawn(|editor, mut cx| async move {
 9282            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9283                editor.update(&mut cx, |_, cx| {
 9284                    cx.open_url(&url);
 9285                })
 9286            } else {
 9287                Ok(())
 9288            }
 9289        })
 9290        .detach();
 9291    }
 9292
 9293    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9294        let Some(workspace) = self.workspace() else {
 9295            return;
 9296        };
 9297
 9298        let position = self.selections.newest_anchor().head();
 9299
 9300        let Some((buffer, buffer_position)) =
 9301            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9302        else {
 9303            return;
 9304        };
 9305
 9306        let project = self.project.clone();
 9307
 9308        cx.spawn(|_, mut cx| async move {
 9309            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9310
 9311            if let Some((_, path)) = result {
 9312                workspace
 9313                    .update(&mut cx, |workspace, cx| {
 9314                        workspace.open_resolved_path(path, cx)
 9315                    })?
 9316                    .await?;
 9317            }
 9318            anyhow::Ok(())
 9319        })
 9320        .detach();
 9321    }
 9322
 9323    pub(crate) fn navigate_to_hover_links(
 9324        &mut self,
 9325        kind: Option<GotoDefinitionKind>,
 9326        mut definitions: Vec<HoverLink>,
 9327        split: bool,
 9328        cx: &mut ViewContext<Editor>,
 9329    ) -> Task<Result<Navigated>> {
 9330        // If there is one definition, just open it directly
 9331        if definitions.len() == 1 {
 9332            let definition = definitions.pop().unwrap();
 9333
 9334            enum TargetTaskResult {
 9335                Location(Option<Location>),
 9336                AlreadyNavigated,
 9337            }
 9338
 9339            let target_task = match definition {
 9340                HoverLink::Text(link) => {
 9341                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9342                }
 9343                HoverLink::InlayHint(lsp_location, server_id) => {
 9344                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9345                    cx.background_executor().spawn(async move {
 9346                        let location = computation.await?;
 9347                        Ok(TargetTaskResult::Location(location))
 9348                    })
 9349                }
 9350                HoverLink::Url(url) => {
 9351                    cx.open_url(&url);
 9352                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9353                }
 9354                HoverLink::File(path) => {
 9355                    if let Some(workspace) = self.workspace() {
 9356                        cx.spawn(|_, mut cx| async move {
 9357                            workspace
 9358                                .update(&mut cx, |workspace, cx| {
 9359                                    workspace.open_resolved_path(path, cx)
 9360                                })?
 9361                                .await
 9362                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9363                        })
 9364                    } else {
 9365                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9366                    }
 9367                }
 9368            };
 9369            cx.spawn(|editor, mut cx| async move {
 9370                let target = match target_task.await.context("target resolution task")? {
 9371                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9372                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9373                    TargetTaskResult::Location(Some(target)) => target,
 9374                };
 9375
 9376                editor.update(&mut cx, |editor, cx| {
 9377                    let Some(workspace) = editor.workspace() else {
 9378                        return Navigated::No;
 9379                    };
 9380                    let pane = workspace.read(cx).active_pane().clone();
 9381
 9382                    let range = target.range.to_offset(target.buffer.read(cx));
 9383                    let range = editor.range_for_match(&range);
 9384
 9385                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9386                        let buffer = target.buffer.read(cx);
 9387                        let range = check_multiline_range(buffer, range);
 9388                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9389                            s.select_ranges([range]);
 9390                        });
 9391                    } else {
 9392                        cx.window_context().defer(move |cx| {
 9393                            let target_editor: View<Self> =
 9394                                workspace.update(cx, |workspace, cx| {
 9395                                    let pane = if split {
 9396                                        workspace.adjacent_pane(cx)
 9397                                    } else {
 9398                                        workspace.active_pane().clone()
 9399                                    };
 9400
 9401                                    workspace.open_project_item(
 9402                                        pane,
 9403                                        target.buffer.clone(),
 9404                                        true,
 9405                                        true,
 9406                                        cx,
 9407                                    )
 9408                                });
 9409                            target_editor.update(cx, |target_editor, cx| {
 9410                                // When selecting a definition in a different buffer, disable the nav history
 9411                                // to avoid creating a history entry at the previous cursor location.
 9412                                pane.update(cx, |pane, _| pane.disable_history());
 9413                                let buffer = target.buffer.read(cx);
 9414                                let range = check_multiline_range(buffer, range);
 9415                                target_editor.change_selections(
 9416                                    Some(Autoscroll::focused()),
 9417                                    cx,
 9418                                    |s| {
 9419                                        s.select_ranges([range]);
 9420                                    },
 9421                                );
 9422                                pane.update(cx, |pane, _| pane.enable_history());
 9423                            });
 9424                        });
 9425                    }
 9426                    Navigated::Yes
 9427                })
 9428            })
 9429        } else if !definitions.is_empty() {
 9430            cx.spawn(|editor, mut cx| async move {
 9431                let (title, location_tasks, workspace) = editor
 9432                    .update(&mut cx, |editor, cx| {
 9433                        let tab_kind = match kind {
 9434                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9435                            _ => "Definitions",
 9436                        };
 9437                        let title = definitions
 9438                            .iter()
 9439                            .find_map(|definition| match definition {
 9440                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9441                                    let buffer = origin.buffer.read(cx);
 9442                                    format!(
 9443                                        "{} for {}",
 9444                                        tab_kind,
 9445                                        buffer
 9446                                            .text_for_range(origin.range.clone())
 9447                                            .collect::<String>()
 9448                                    )
 9449                                }),
 9450                                HoverLink::InlayHint(_, _) => None,
 9451                                HoverLink::Url(_) => None,
 9452                                HoverLink::File(_) => None,
 9453                            })
 9454                            .unwrap_or(tab_kind.to_string());
 9455                        let location_tasks = definitions
 9456                            .into_iter()
 9457                            .map(|definition| match definition {
 9458                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9459                                HoverLink::InlayHint(lsp_location, server_id) => {
 9460                                    editor.compute_target_location(lsp_location, server_id, cx)
 9461                                }
 9462                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9463                                HoverLink::File(_) => Task::ready(Ok(None)),
 9464                            })
 9465                            .collect::<Vec<_>>();
 9466                        (title, location_tasks, editor.workspace().clone())
 9467                    })
 9468                    .context("location tasks preparation")?;
 9469
 9470                let locations = future::join_all(location_tasks)
 9471                    .await
 9472                    .into_iter()
 9473                    .filter_map(|location| location.transpose())
 9474                    .collect::<Result<_>>()
 9475                    .context("location tasks")?;
 9476
 9477                let Some(workspace) = workspace else {
 9478                    return Ok(Navigated::No);
 9479                };
 9480                let opened = workspace
 9481                    .update(&mut cx, |workspace, cx| {
 9482                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9483                    })
 9484                    .ok();
 9485
 9486                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9487            })
 9488        } else {
 9489            Task::ready(Ok(Navigated::No))
 9490        }
 9491    }
 9492
 9493    fn compute_target_location(
 9494        &self,
 9495        lsp_location: lsp::Location,
 9496        server_id: LanguageServerId,
 9497        cx: &mut ViewContext<Self>,
 9498    ) -> Task<anyhow::Result<Option<Location>>> {
 9499        let Some(project) = self.project.clone() else {
 9500            return Task::Ready(Some(Ok(None)));
 9501        };
 9502
 9503        cx.spawn(move |editor, mut cx| async move {
 9504            let location_task = editor.update(&mut cx, |_, cx| {
 9505                project.update(cx, |project, cx| {
 9506                    let language_server_name = project
 9507                        .language_server_statuses(cx)
 9508                        .find(|(id, _)| server_id == *id)
 9509                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9510                    language_server_name.map(|language_server_name| {
 9511                        project.open_local_buffer_via_lsp(
 9512                            lsp_location.uri.clone(),
 9513                            server_id,
 9514                            language_server_name,
 9515                            cx,
 9516                        )
 9517                    })
 9518                })
 9519            })?;
 9520            let location = match location_task {
 9521                Some(task) => Some({
 9522                    let target_buffer_handle = task.await.context("open local buffer")?;
 9523                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9524                        let target_start = target_buffer
 9525                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9526                        let target_end = target_buffer
 9527                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9528                        target_buffer.anchor_after(target_start)
 9529                            ..target_buffer.anchor_before(target_end)
 9530                    })?;
 9531                    Location {
 9532                        buffer: target_buffer_handle,
 9533                        range,
 9534                    }
 9535                }),
 9536                None => None,
 9537            };
 9538            Ok(location)
 9539        })
 9540    }
 9541
 9542    pub fn find_all_references(
 9543        &mut self,
 9544        _: &FindAllReferences,
 9545        cx: &mut ViewContext<Self>,
 9546    ) -> Option<Task<Result<Navigated>>> {
 9547        let selection = self.selections.newest::<usize>(cx);
 9548        let multi_buffer = self.buffer.read(cx);
 9549        let head = selection.head();
 9550
 9551        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9552        let head_anchor = multi_buffer_snapshot.anchor_at(
 9553            head,
 9554            if head < selection.tail() {
 9555                Bias::Right
 9556            } else {
 9557                Bias::Left
 9558            },
 9559        );
 9560
 9561        match self
 9562            .find_all_references_task_sources
 9563            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9564        {
 9565            Ok(_) => {
 9566                log::info!(
 9567                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9568                );
 9569                return None;
 9570            }
 9571            Err(i) => {
 9572                self.find_all_references_task_sources.insert(i, head_anchor);
 9573            }
 9574        }
 9575
 9576        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9577        let workspace = self.workspace()?;
 9578        let project = workspace.read(cx).project().clone();
 9579        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9580        Some(cx.spawn(|editor, mut cx| async move {
 9581            let _cleanup = defer({
 9582                let mut cx = cx.clone();
 9583                move || {
 9584                    let _ = editor.update(&mut cx, |editor, _| {
 9585                        if let Ok(i) =
 9586                            editor
 9587                                .find_all_references_task_sources
 9588                                .binary_search_by(|anchor| {
 9589                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9590                                })
 9591                        {
 9592                            editor.find_all_references_task_sources.remove(i);
 9593                        }
 9594                    });
 9595                }
 9596            });
 9597
 9598            let locations = references.await?;
 9599            if locations.is_empty() {
 9600                return anyhow::Ok(Navigated::No);
 9601            }
 9602
 9603            workspace.update(&mut cx, |workspace, cx| {
 9604                let title = locations
 9605                    .first()
 9606                    .as_ref()
 9607                    .map(|location| {
 9608                        let buffer = location.buffer.read(cx);
 9609                        format!(
 9610                            "References to `{}`",
 9611                            buffer
 9612                                .text_for_range(location.range.clone())
 9613                                .collect::<String>()
 9614                        )
 9615                    })
 9616                    .unwrap();
 9617                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9618                Navigated::Yes
 9619            })
 9620        }))
 9621    }
 9622
 9623    /// Opens a multibuffer with the given project locations in it
 9624    pub fn open_locations_in_multibuffer(
 9625        workspace: &mut Workspace,
 9626        mut locations: Vec<Location>,
 9627        title: String,
 9628        split: bool,
 9629        cx: &mut ViewContext<Workspace>,
 9630    ) {
 9631        // If there are multiple definitions, open them in a multibuffer
 9632        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9633        let mut locations = locations.into_iter().peekable();
 9634        let mut ranges_to_highlight = Vec::new();
 9635        let capability = workspace.project().read(cx).capability();
 9636
 9637        let excerpt_buffer = cx.new_model(|cx| {
 9638            let mut multibuffer = MultiBuffer::new(capability);
 9639            while let Some(location) = locations.next() {
 9640                let buffer = location.buffer.read(cx);
 9641                let mut ranges_for_buffer = Vec::new();
 9642                let range = location.range.to_offset(buffer);
 9643                ranges_for_buffer.push(range.clone());
 9644
 9645                while let Some(next_location) = locations.peek() {
 9646                    if next_location.buffer == location.buffer {
 9647                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9648                        locations.next();
 9649                    } else {
 9650                        break;
 9651                    }
 9652                }
 9653
 9654                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9655                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9656                    location.buffer.clone(),
 9657                    ranges_for_buffer,
 9658                    DEFAULT_MULTIBUFFER_CONTEXT,
 9659                    cx,
 9660                ))
 9661            }
 9662
 9663            multibuffer.with_title(title)
 9664        });
 9665
 9666        let editor = cx.new_view(|cx| {
 9667            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9668        });
 9669        editor.update(cx, |editor, cx| {
 9670            if let Some(first_range) = ranges_to_highlight.first() {
 9671                editor.change_selections(None, cx, |selections| {
 9672                    selections.clear_disjoint();
 9673                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9674                });
 9675            }
 9676            editor.highlight_background::<Self>(
 9677                &ranges_to_highlight,
 9678                |theme| theme.editor_highlighted_line_background,
 9679                cx,
 9680            );
 9681            editor.register_buffers_with_language_servers(cx);
 9682        });
 9683
 9684        let item = Box::new(editor);
 9685        let item_id = item.item_id();
 9686
 9687        if split {
 9688            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9689        } else {
 9690            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9691                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9692                    pane.close_current_preview_item(cx)
 9693                } else {
 9694                    None
 9695                }
 9696            });
 9697            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9698        }
 9699        workspace.active_pane().update(cx, |pane, cx| {
 9700            pane.set_preview_item_id(Some(item_id), cx);
 9701        });
 9702    }
 9703
 9704    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9705        use language::ToOffset as _;
 9706
 9707        let provider = self.semantics_provider.clone()?;
 9708        let selection = self.selections.newest_anchor().clone();
 9709        let (cursor_buffer, cursor_buffer_position) = self
 9710            .buffer
 9711            .read(cx)
 9712            .text_anchor_for_position(selection.head(), cx)?;
 9713        let (tail_buffer, cursor_buffer_position_end) = self
 9714            .buffer
 9715            .read(cx)
 9716            .text_anchor_for_position(selection.tail(), cx)?;
 9717        if tail_buffer != cursor_buffer {
 9718            return None;
 9719        }
 9720
 9721        let snapshot = cursor_buffer.read(cx).snapshot();
 9722        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9723        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9724        let prepare_rename = provider
 9725            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9726            .unwrap_or_else(|| Task::ready(Ok(None)));
 9727        drop(snapshot);
 9728
 9729        Some(cx.spawn(|this, mut cx| async move {
 9730            let rename_range = if let Some(range) = prepare_rename.await? {
 9731                Some(range)
 9732            } else {
 9733                this.update(&mut cx, |this, cx| {
 9734                    let buffer = this.buffer.read(cx).snapshot(cx);
 9735                    let mut buffer_highlights = this
 9736                        .document_highlights_for_position(selection.head(), &buffer)
 9737                        .filter(|highlight| {
 9738                            highlight.start.excerpt_id == selection.head().excerpt_id
 9739                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9740                        });
 9741                    buffer_highlights
 9742                        .next()
 9743                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9744                })?
 9745            };
 9746            if let Some(rename_range) = rename_range {
 9747                this.update(&mut cx, |this, cx| {
 9748                    let snapshot = cursor_buffer.read(cx).snapshot();
 9749                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9750                    let cursor_offset_in_rename_range =
 9751                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9752                    let cursor_offset_in_rename_range_end =
 9753                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9754
 9755                    this.take_rename(false, cx);
 9756                    let buffer = this.buffer.read(cx).read(cx);
 9757                    let cursor_offset = selection.head().to_offset(&buffer);
 9758                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9759                    let rename_end = rename_start + rename_buffer_range.len();
 9760                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9761                    let mut old_highlight_id = None;
 9762                    let old_name: Arc<str> = buffer
 9763                        .chunks(rename_start..rename_end, true)
 9764                        .map(|chunk| {
 9765                            if old_highlight_id.is_none() {
 9766                                old_highlight_id = chunk.syntax_highlight_id;
 9767                            }
 9768                            chunk.text
 9769                        })
 9770                        .collect::<String>()
 9771                        .into();
 9772
 9773                    drop(buffer);
 9774
 9775                    // Position the selection in the rename editor so that it matches the current selection.
 9776                    this.show_local_selections = false;
 9777                    let rename_editor = cx.new_view(|cx| {
 9778                        let mut editor = Editor::single_line(cx);
 9779                        editor.buffer.update(cx, |buffer, cx| {
 9780                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9781                        });
 9782                        let rename_selection_range = match cursor_offset_in_rename_range
 9783                            .cmp(&cursor_offset_in_rename_range_end)
 9784                        {
 9785                            Ordering::Equal => {
 9786                                editor.select_all(&SelectAll, cx);
 9787                                return editor;
 9788                            }
 9789                            Ordering::Less => {
 9790                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9791                            }
 9792                            Ordering::Greater => {
 9793                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9794                            }
 9795                        };
 9796                        if rename_selection_range.end > old_name.len() {
 9797                            editor.select_all(&SelectAll, cx);
 9798                        } else {
 9799                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9800                                s.select_ranges([rename_selection_range]);
 9801                            });
 9802                        }
 9803                        editor
 9804                    });
 9805                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9806                        if e == &EditorEvent::Focused {
 9807                            cx.emit(EditorEvent::FocusedIn)
 9808                        }
 9809                    })
 9810                    .detach();
 9811
 9812                    let write_highlights =
 9813                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9814                    let read_highlights =
 9815                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9816                    let ranges = write_highlights
 9817                        .iter()
 9818                        .flat_map(|(_, ranges)| ranges.iter())
 9819                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9820                        .cloned()
 9821                        .collect();
 9822
 9823                    this.highlight_text::<Rename>(
 9824                        ranges,
 9825                        HighlightStyle {
 9826                            fade_out: Some(0.6),
 9827                            ..Default::default()
 9828                        },
 9829                        cx,
 9830                    );
 9831                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9832                    cx.focus(&rename_focus_handle);
 9833                    let block_id = this.insert_blocks(
 9834                        [BlockProperties {
 9835                            style: BlockStyle::Flex,
 9836                            placement: BlockPlacement::Below(range.start),
 9837                            height: 1,
 9838                            render: Arc::new({
 9839                                let rename_editor = rename_editor.clone();
 9840                                move |cx: &mut BlockContext| {
 9841                                    let mut text_style = cx.editor_style.text.clone();
 9842                                    if let Some(highlight_style) = old_highlight_id
 9843                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9844                                    {
 9845                                        text_style = text_style.highlight(highlight_style);
 9846                                    }
 9847                                    div()
 9848                                        .block_mouse_down()
 9849                                        .pl(cx.anchor_x)
 9850                                        .child(EditorElement::new(
 9851                                            &rename_editor,
 9852                                            EditorStyle {
 9853                                                background: cx.theme().system().transparent,
 9854                                                local_player: cx.editor_style.local_player,
 9855                                                text: text_style,
 9856                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9857                                                syntax: cx.editor_style.syntax.clone(),
 9858                                                status: cx.editor_style.status.clone(),
 9859                                                inlay_hints_style: HighlightStyle {
 9860                                                    font_weight: Some(FontWeight::BOLD),
 9861                                                    ..make_inlay_hints_style(cx)
 9862                                                },
 9863                                                suggestions_style: HighlightStyle {
 9864                                                    color: Some(cx.theme().status().predictive),
 9865                                                    ..HighlightStyle::default()
 9866                                                },
 9867                                                ..EditorStyle::default()
 9868                                            },
 9869                                        ))
 9870                                        .into_any_element()
 9871                                }
 9872                            }),
 9873                            priority: 0,
 9874                        }],
 9875                        Some(Autoscroll::fit()),
 9876                        cx,
 9877                    )[0];
 9878                    this.pending_rename = Some(RenameState {
 9879                        range,
 9880                        old_name,
 9881                        editor: rename_editor,
 9882                        block_id,
 9883                    });
 9884                })?;
 9885            }
 9886
 9887            Ok(())
 9888        }))
 9889    }
 9890
 9891    pub fn confirm_rename(
 9892        &mut self,
 9893        _: &ConfirmRename,
 9894        cx: &mut ViewContext<Self>,
 9895    ) -> Option<Task<Result<()>>> {
 9896        let rename = self.take_rename(false, cx)?;
 9897        let workspace = self.workspace()?.downgrade();
 9898        let (buffer, start) = self
 9899            .buffer
 9900            .read(cx)
 9901            .text_anchor_for_position(rename.range.start, cx)?;
 9902        let (end_buffer, _) = self
 9903            .buffer
 9904            .read(cx)
 9905            .text_anchor_for_position(rename.range.end, cx)?;
 9906        if buffer != end_buffer {
 9907            return None;
 9908        }
 9909
 9910        let old_name = rename.old_name;
 9911        let new_name = rename.editor.read(cx).text(cx);
 9912
 9913        let rename = self.semantics_provider.as_ref()?.perform_rename(
 9914            &buffer,
 9915            start,
 9916            new_name.clone(),
 9917            cx,
 9918        )?;
 9919
 9920        Some(cx.spawn(|editor, mut cx| async move {
 9921            let project_transaction = rename.await?;
 9922            Self::open_project_transaction(
 9923                &editor,
 9924                workspace,
 9925                project_transaction,
 9926                format!("Rename: {}{}", old_name, new_name),
 9927                cx.clone(),
 9928            )
 9929            .await?;
 9930
 9931            editor.update(&mut cx, |editor, cx| {
 9932                editor.refresh_document_highlights(cx);
 9933            })?;
 9934            Ok(())
 9935        }))
 9936    }
 9937
 9938    fn take_rename(
 9939        &mut self,
 9940        moving_cursor: bool,
 9941        cx: &mut ViewContext<Self>,
 9942    ) -> Option<RenameState> {
 9943        let rename = self.pending_rename.take()?;
 9944        if rename.editor.focus_handle(cx).is_focused(cx) {
 9945            cx.focus(&self.focus_handle);
 9946        }
 9947
 9948        self.remove_blocks(
 9949            [rename.block_id].into_iter().collect(),
 9950            Some(Autoscroll::fit()),
 9951            cx,
 9952        );
 9953        self.clear_highlights::<Rename>(cx);
 9954        self.show_local_selections = true;
 9955
 9956        if moving_cursor {
 9957            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
 9958                editor.selections.newest::<usize>(cx).head()
 9959            });
 9960
 9961            // Update the selection to match the position of the selection inside
 9962            // the rename editor.
 9963            let snapshot = self.buffer.read(cx).read(cx);
 9964            let rename_range = rename.range.to_offset(&snapshot);
 9965            let cursor_in_editor = snapshot
 9966                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9967                .min(rename_range.end);
 9968            drop(snapshot);
 9969
 9970            self.change_selections(None, cx, |s| {
 9971                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9972            });
 9973        } else {
 9974            self.refresh_document_highlights(cx);
 9975        }
 9976
 9977        Some(rename)
 9978    }
 9979
 9980    pub fn pending_rename(&self) -> Option<&RenameState> {
 9981        self.pending_rename.as_ref()
 9982    }
 9983
 9984    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9985        let project = match &self.project {
 9986            Some(project) => project.clone(),
 9987            None => return None,
 9988        };
 9989
 9990        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
 9991    }
 9992
 9993    fn format_selections(
 9994        &mut self,
 9995        _: &FormatSelections,
 9996        cx: &mut ViewContext<Self>,
 9997    ) -> Option<Task<Result<()>>> {
 9998        let project = match &self.project {
 9999            Some(project) => project.clone(),
10000            None => return None,
10001        };
10002
10003        let selections = self
10004            .selections
10005            .all_adjusted(cx)
10006            .into_iter()
10007            .filter(|s| !s.is_empty())
10008            .collect_vec();
10009
10010        Some(self.perform_format(
10011            project,
10012            FormatTrigger::Manual,
10013            FormatTarget::Ranges(selections),
10014            cx,
10015        ))
10016    }
10017
10018    fn perform_format(
10019        &mut self,
10020        project: Model<Project>,
10021        trigger: FormatTrigger,
10022        target: FormatTarget,
10023        cx: &mut ViewContext<Self>,
10024    ) -> Task<Result<()>> {
10025        let buffer = self.buffer().clone();
10026        let mut buffers = buffer.read(cx).all_buffers();
10027        if trigger == FormatTrigger::Save {
10028            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10029        }
10030
10031        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10032        let format = project.update(cx, |project, cx| {
10033            project.format(buffers, true, trigger, target, cx)
10034        });
10035
10036        cx.spawn(|_, mut cx| async move {
10037            let transaction = futures::select_biased! {
10038                () = timeout => {
10039                    log::warn!("timed out waiting for formatting");
10040                    None
10041                }
10042                transaction = format.log_err().fuse() => transaction,
10043            };
10044
10045            buffer
10046                .update(&mut cx, |buffer, cx| {
10047                    if let Some(transaction) = transaction {
10048                        if !buffer.is_singleton() {
10049                            buffer.push_transaction(&transaction.0, cx);
10050                        }
10051                    }
10052
10053                    cx.notify();
10054                })
10055                .ok();
10056
10057            Ok(())
10058        })
10059    }
10060
10061    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10062        if let Some(project) = self.project.clone() {
10063            self.buffer.update(cx, |multi_buffer, cx| {
10064                project.update(cx, |project, cx| {
10065                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10066                });
10067            })
10068        }
10069    }
10070
10071    fn cancel_language_server_work(
10072        &mut self,
10073        _: &actions::CancelLanguageServerWork,
10074        cx: &mut ViewContext<Self>,
10075    ) {
10076        if let Some(project) = self.project.clone() {
10077            self.buffer.update(cx, |multi_buffer, cx| {
10078                project.update(cx, |project, cx| {
10079                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10080                });
10081            })
10082        }
10083    }
10084
10085    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10086        cx.show_character_palette();
10087    }
10088
10089    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10090        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10091            let buffer = self.buffer.read(cx).snapshot(cx);
10092            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10093            let is_valid = buffer
10094                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10095                .any(|entry| {
10096                    entry.diagnostic.is_primary
10097                        && !entry.range.is_empty()
10098                        && entry.range.start == primary_range_start
10099                        && entry.diagnostic.message == active_diagnostics.primary_message
10100                });
10101
10102            if is_valid != active_diagnostics.is_valid {
10103                active_diagnostics.is_valid = is_valid;
10104                let mut new_styles = HashMap::default();
10105                for (block_id, diagnostic) in &active_diagnostics.blocks {
10106                    new_styles.insert(
10107                        *block_id,
10108                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10109                    );
10110                }
10111                self.display_map.update(cx, |display_map, _cx| {
10112                    display_map.replace_blocks(new_styles)
10113                });
10114            }
10115        }
10116    }
10117
10118    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10119        self.dismiss_diagnostics(cx);
10120        let snapshot = self.snapshot(cx);
10121        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10122            let buffer = self.buffer.read(cx).snapshot(cx);
10123
10124            let mut primary_range = None;
10125            let mut primary_message = None;
10126            let mut group_end = Point::zero();
10127            let diagnostic_group = buffer
10128                .diagnostic_group::<MultiBufferPoint>(group_id)
10129                .filter_map(|entry| {
10130                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10131                        && (entry.range.start.row == entry.range.end.row
10132                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10133                    {
10134                        return None;
10135                    }
10136                    if entry.range.end > group_end {
10137                        group_end = entry.range.end;
10138                    }
10139                    if entry.diagnostic.is_primary {
10140                        primary_range = Some(entry.range.clone());
10141                        primary_message = Some(entry.diagnostic.message.clone());
10142                    }
10143                    Some(entry)
10144                })
10145                .collect::<Vec<_>>();
10146            let primary_range = primary_range?;
10147            let primary_message = primary_message?;
10148            let primary_range =
10149                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10150
10151            let blocks = display_map
10152                .insert_blocks(
10153                    diagnostic_group.iter().map(|entry| {
10154                        let diagnostic = entry.diagnostic.clone();
10155                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10156                        BlockProperties {
10157                            style: BlockStyle::Fixed,
10158                            placement: BlockPlacement::Below(
10159                                buffer.anchor_after(entry.range.start),
10160                            ),
10161                            height: message_height,
10162                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10163                            priority: 0,
10164                        }
10165                    }),
10166                    cx,
10167                )
10168                .into_iter()
10169                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10170                .collect();
10171
10172            Some(ActiveDiagnosticGroup {
10173                primary_range,
10174                primary_message,
10175                group_id,
10176                blocks,
10177                is_valid: true,
10178            })
10179        });
10180        self.active_diagnostics.is_some()
10181    }
10182
10183    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10184        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10185            self.display_map.update(cx, |display_map, cx| {
10186                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10187            });
10188            cx.notify();
10189        }
10190    }
10191
10192    pub fn set_selections_from_remote(
10193        &mut self,
10194        selections: Vec<Selection<Anchor>>,
10195        pending_selection: Option<Selection<Anchor>>,
10196        cx: &mut ViewContext<Self>,
10197    ) {
10198        let old_cursor_position = self.selections.newest_anchor().head();
10199        self.selections.change_with(cx, |s| {
10200            s.select_anchors(selections);
10201            if let Some(pending_selection) = pending_selection {
10202                s.set_pending(pending_selection, SelectMode::Character);
10203            } else {
10204                s.clear_pending();
10205            }
10206        });
10207        self.selections_did_change(false, &old_cursor_position, true, cx);
10208    }
10209
10210    fn push_to_selection_history(&mut self) {
10211        self.selection_history.push(SelectionHistoryEntry {
10212            selections: self.selections.disjoint_anchors(),
10213            select_next_state: self.select_next_state.clone(),
10214            select_prev_state: self.select_prev_state.clone(),
10215            add_selections_state: self.add_selections_state.clone(),
10216        });
10217    }
10218
10219    pub fn transact(
10220        &mut self,
10221        cx: &mut ViewContext<Self>,
10222        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10223    ) -> Option<TransactionId> {
10224        self.start_transaction_at(Instant::now(), cx);
10225        update(self, cx);
10226        self.end_transaction_at(Instant::now(), cx)
10227    }
10228
10229    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10230        self.end_selection(cx);
10231        if let Some(tx_id) = self
10232            .buffer
10233            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10234        {
10235            self.selection_history
10236                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10237            cx.emit(EditorEvent::TransactionBegun {
10238                transaction_id: tx_id,
10239            })
10240        }
10241    }
10242
10243    fn end_transaction_at(
10244        &mut self,
10245        now: Instant,
10246        cx: &mut ViewContext<Self>,
10247    ) -> Option<TransactionId> {
10248        if let Some(transaction_id) = self
10249            .buffer
10250            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10251        {
10252            if let Some((_, end_selections)) =
10253                self.selection_history.transaction_mut(transaction_id)
10254            {
10255                *end_selections = Some(self.selections.disjoint_anchors());
10256            } else {
10257                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10258            }
10259
10260            cx.emit(EditorEvent::Edited { transaction_id });
10261            Some(transaction_id)
10262        } else {
10263            None
10264        }
10265    }
10266
10267    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10268        let selection = self.selections.newest::<Point>(cx);
10269
10270        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10271        let range = if selection.is_empty() {
10272            let point = selection.head().to_display_point(&display_map);
10273            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10274            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10275                .to_point(&display_map);
10276            start..end
10277        } else {
10278            selection.range()
10279        };
10280        if display_map.folds_in_range(range).next().is_some() {
10281            self.unfold_lines(&Default::default(), cx)
10282        } else {
10283            self.fold(&Default::default(), cx)
10284        }
10285    }
10286
10287    pub fn toggle_fold_recursive(
10288        &mut self,
10289        _: &actions::ToggleFoldRecursive,
10290        cx: &mut ViewContext<Self>,
10291    ) {
10292        let selection = self.selections.newest::<Point>(cx);
10293
10294        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10295        let range = if selection.is_empty() {
10296            let point = selection.head().to_display_point(&display_map);
10297            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10298            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10299                .to_point(&display_map);
10300            start..end
10301        } else {
10302            selection.range()
10303        };
10304        if display_map.folds_in_range(range).next().is_some() {
10305            self.unfold_recursive(&Default::default(), cx)
10306        } else {
10307            self.fold_recursive(&Default::default(), cx)
10308        }
10309    }
10310
10311    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10312        let mut to_fold = Vec::new();
10313        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10314        let selections = self.selections.all_adjusted(cx);
10315
10316        for selection in selections {
10317            let range = selection.range().sorted();
10318            let buffer_start_row = range.start.row;
10319
10320            if range.start.row != range.end.row {
10321                let mut found = false;
10322                let mut row = range.start.row;
10323                while row <= range.end.row {
10324                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10325                        found = true;
10326                        row = crease.range().end.row + 1;
10327                        to_fold.push(crease);
10328                    } else {
10329                        row += 1
10330                    }
10331                }
10332                if found {
10333                    continue;
10334                }
10335            }
10336
10337            for row in (0..=range.start.row).rev() {
10338                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10339                    if crease.range().end.row >= buffer_start_row {
10340                        to_fold.push(crease);
10341                        if row <= range.start.row {
10342                            break;
10343                        }
10344                    }
10345                }
10346            }
10347        }
10348
10349        self.fold_creases(to_fold, true, cx);
10350    }
10351
10352    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10353        if !self.buffer.read(cx).is_singleton() {
10354            return;
10355        }
10356
10357        let fold_at_level = fold_at.level;
10358        let snapshot = self.buffer.read(cx).snapshot(cx);
10359        let mut to_fold = Vec::new();
10360        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10361
10362        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10363            while start_row < end_row {
10364                match self
10365                    .snapshot(cx)
10366                    .crease_for_buffer_row(MultiBufferRow(start_row))
10367                {
10368                    Some(crease) => {
10369                        let nested_start_row = crease.range().start.row + 1;
10370                        let nested_end_row = crease.range().end.row;
10371
10372                        if current_level < fold_at_level {
10373                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10374                        } else if current_level == fold_at_level {
10375                            to_fold.push(crease);
10376                        }
10377
10378                        start_row = nested_end_row + 1;
10379                    }
10380                    None => start_row += 1,
10381                }
10382            }
10383        }
10384
10385        self.fold_creases(to_fold, true, cx);
10386    }
10387
10388    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10389        if !self.buffer.read(cx).is_singleton() {
10390            return;
10391        }
10392
10393        let mut fold_ranges = Vec::new();
10394        let snapshot = self.buffer.read(cx).snapshot(cx);
10395
10396        for row in 0..snapshot.max_row().0 {
10397            if let Some(foldable_range) =
10398                self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10399            {
10400                fold_ranges.push(foldable_range);
10401            }
10402        }
10403
10404        self.fold_creases(fold_ranges, true, cx);
10405    }
10406
10407    pub fn fold_function_bodies(
10408        &mut self,
10409        _: &actions::FoldFunctionBodies,
10410        cx: &mut ViewContext<Self>,
10411    ) {
10412        let snapshot = self.buffer.read(cx).snapshot(cx);
10413        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10414            return;
10415        };
10416        let creases = buffer
10417            .function_body_fold_ranges(0..buffer.len())
10418            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10419            .collect();
10420
10421        self.fold_creases(creases, true, cx);
10422    }
10423
10424    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10425        let mut to_fold = Vec::new();
10426        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10427        let selections = self.selections.all_adjusted(cx);
10428
10429        for selection in selections {
10430            let range = selection.range().sorted();
10431            let buffer_start_row = range.start.row;
10432
10433            if range.start.row != range.end.row {
10434                let mut found = false;
10435                for row in range.start.row..=range.end.row {
10436                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10437                        found = true;
10438                        to_fold.push(crease);
10439                    }
10440                }
10441                if found {
10442                    continue;
10443                }
10444            }
10445
10446            for row in (0..=range.start.row).rev() {
10447                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10448                    if crease.range().end.row >= buffer_start_row {
10449                        to_fold.push(crease);
10450                    } else {
10451                        break;
10452                    }
10453                }
10454            }
10455        }
10456
10457        self.fold_creases(to_fold, true, cx);
10458    }
10459
10460    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10461        let buffer_row = fold_at.buffer_row;
10462        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10463
10464        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10465            let autoscroll = self
10466                .selections
10467                .all::<Point>(cx)
10468                .iter()
10469                .any(|selection| crease.range().overlaps(&selection.range()));
10470
10471            self.fold_creases(vec![crease], autoscroll, cx);
10472        }
10473    }
10474
10475    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10476        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10477        let buffer = &display_map.buffer_snapshot;
10478        let selections = self.selections.all::<Point>(cx);
10479        let ranges = selections
10480            .iter()
10481            .map(|s| {
10482                let range = s.display_range(&display_map).sorted();
10483                let mut start = range.start.to_point(&display_map);
10484                let mut end = range.end.to_point(&display_map);
10485                start.column = 0;
10486                end.column = buffer.line_len(MultiBufferRow(end.row));
10487                start..end
10488            })
10489            .collect::<Vec<_>>();
10490
10491        self.unfold_ranges(&ranges, true, true, cx);
10492    }
10493
10494    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10495        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10496        let selections = self.selections.all::<Point>(cx);
10497        let ranges = selections
10498            .iter()
10499            .map(|s| {
10500                let mut range = s.display_range(&display_map).sorted();
10501                *range.start.column_mut() = 0;
10502                *range.end.column_mut() = display_map.line_len(range.end.row());
10503                let start = range.start.to_point(&display_map);
10504                let end = range.end.to_point(&display_map);
10505                start..end
10506            })
10507            .collect::<Vec<_>>();
10508
10509        self.unfold_ranges(&ranges, true, true, cx);
10510    }
10511
10512    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10513        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10514
10515        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10516            ..Point::new(
10517                unfold_at.buffer_row.0,
10518                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10519            );
10520
10521        let autoscroll = self
10522            .selections
10523            .all::<Point>(cx)
10524            .iter()
10525            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10526
10527        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10528    }
10529
10530    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10531        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10532        self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10533    }
10534
10535    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10536        let selections = self.selections.all::<Point>(cx);
10537        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10538        let line_mode = self.selections.line_mode;
10539        let ranges = selections
10540            .into_iter()
10541            .map(|s| {
10542                if line_mode {
10543                    let start = Point::new(s.start.row, 0);
10544                    let end = Point::new(
10545                        s.end.row,
10546                        display_map
10547                            .buffer_snapshot
10548                            .line_len(MultiBufferRow(s.end.row)),
10549                    );
10550                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10551                } else {
10552                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10553                }
10554            })
10555            .collect::<Vec<_>>();
10556        self.fold_creases(ranges, true, cx);
10557    }
10558
10559    pub fn fold_creases<T: ToOffset + Clone>(
10560        &mut self,
10561        creases: Vec<Crease<T>>,
10562        auto_scroll: bool,
10563        cx: &mut ViewContext<Self>,
10564    ) {
10565        if creases.is_empty() {
10566            return;
10567        }
10568
10569        let mut buffers_affected = HashSet::default();
10570        let multi_buffer = self.buffer().read(cx);
10571        for crease in &creases {
10572            if let Some((_, buffer, _)) =
10573                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10574            {
10575                buffers_affected.insert(buffer.read(cx).remote_id());
10576            };
10577        }
10578
10579        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10580
10581        if auto_scroll {
10582            self.request_autoscroll(Autoscroll::fit(), cx);
10583        }
10584
10585        for buffer_id in buffers_affected {
10586            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10587        }
10588
10589        cx.notify();
10590
10591        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10592            // Clear diagnostics block when folding a range that contains it.
10593            let snapshot = self.snapshot(cx);
10594            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10595                drop(snapshot);
10596                self.active_diagnostics = Some(active_diagnostics);
10597                self.dismiss_diagnostics(cx);
10598            } else {
10599                self.active_diagnostics = Some(active_diagnostics);
10600            }
10601        }
10602
10603        self.scrollbar_marker_state.dirty = true;
10604    }
10605
10606    /// Removes any folds whose ranges intersect any of the given ranges.
10607    pub fn unfold_ranges<T: ToOffset + Clone>(
10608        &mut self,
10609        ranges: &[Range<T>],
10610        inclusive: bool,
10611        auto_scroll: bool,
10612        cx: &mut ViewContext<Self>,
10613    ) {
10614        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10615            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10616        });
10617    }
10618
10619    /// Removes any folds with the given ranges.
10620    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10621        &mut self,
10622        ranges: &[Range<T>],
10623        type_id: TypeId,
10624        auto_scroll: bool,
10625        cx: &mut ViewContext<Self>,
10626    ) {
10627        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10628            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10629        });
10630    }
10631
10632    fn remove_folds_with<T: ToOffset + Clone>(
10633        &mut self,
10634        ranges: &[Range<T>],
10635        auto_scroll: bool,
10636        cx: &mut ViewContext<Self>,
10637        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10638    ) {
10639        if ranges.is_empty() {
10640            return;
10641        }
10642
10643        let mut buffers_affected = HashSet::default();
10644        let multi_buffer = self.buffer().read(cx);
10645        for range in ranges {
10646            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10647                buffers_affected.insert(buffer.read(cx).remote_id());
10648            };
10649        }
10650
10651        self.display_map.update(cx, update);
10652
10653        if auto_scroll {
10654            self.request_autoscroll(Autoscroll::fit(), cx);
10655        }
10656
10657        for buffer_id in buffers_affected {
10658            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10659        }
10660
10661        cx.notify();
10662        self.scrollbar_marker_state.dirty = true;
10663        self.active_indent_guides_state.dirty = true;
10664    }
10665
10666    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10667        self.display_map.read(cx).fold_placeholder.clone()
10668    }
10669
10670    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10671        if hovered != self.gutter_hovered {
10672            self.gutter_hovered = hovered;
10673            cx.notify();
10674        }
10675    }
10676
10677    pub fn insert_blocks(
10678        &mut self,
10679        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10680        autoscroll: Option<Autoscroll>,
10681        cx: &mut ViewContext<Self>,
10682    ) -> Vec<CustomBlockId> {
10683        let blocks = self
10684            .display_map
10685            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10686        if let Some(autoscroll) = autoscroll {
10687            self.request_autoscroll(autoscroll, cx);
10688        }
10689        cx.notify();
10690        blocks
10691    }
10692
10693    pub fn resize_blocks(
10694        &mut self,
10695        heights: HashMap<CustomBlockId, u32>,
10696        autoscroll: Option<Autoscroll>,
10697        cx: &mut ViewContext<Self>,
10698    ) {
10699        self.display_map
10700            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10701        if let Some(autoscroll) = autoscroll {
10702            self.request_autoscroll(autoscroll, cx);
10703        }
10704        cx.notify();
10705    }
10706
10707    pub fn replace_blocks(
10708        &mut self,
10709        renderers: HashMap<CustomBlockId, RenderBlock>,
10710        autoscroll: Option<Autoscroll>,
10711        cx: &mut ViewContext<Self>,
10712    ) {
10713        self.display_map
10714            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10715        if let Some(autoscroll) = autoscroll {
10716            self.request_autoscroll(autoscroll, cx);
10717        }
10718        cx.notify();
10719    }
10720
10721    pub fn remove_blocks(
10722        &mut self,
10723        block_ids: HashSet<CustomBlockId>,
10724        autoscroll: Option<Autoscroll>,
10725        cx: &mut ViewContext<Self>,
10726    ) {
10727        self.display_map.update(cx, |display_map, cx| {
10728            display_map.remove_blocks(block_ids, cx)
10729        });
10730        if let Some(autoscroll) = autoscroll {
10731            self.request_autoscroll(autoscroll, cx);
10732        }
10733        cx.notify();
10734    }
10735
10736    pub fn row_for_block(
10737        &self,
10738        block_id: CustomBlockId,
10739        cx: &mut ViewContext<Self>,
10740    ) -> Option<DisplayRow> {
10741        self.display_map
10742            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10743    }
10744
10745    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10746        self.focused_block = Some(focused_block);
10747    }
10748
10749    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10750        self.focused_block.take()
10751    }
10752
10753    pub fn insert_creases(
10754        &mut self,
10755        creases: impl IntoIterator<Item = Crease<Anchor>>,
10756        cx: &mut ViewContext<Self>,
10757    ) -> Vec<CreaseId> {
10758        self.display_map
10759            .update(cx, |map, cx| map.insert_creases(creases, cx))
10760    }
10761
10762    pub fn remove_creases(
10763        &mut self,
10764        ids: impl IntoIterator<Item = CreaseId>,
10765        cx: &mut ViewContext<Self>,
10766    ) {
10767        self.display_map
10768            .update(cx, |map, cx| map.remove_creases(ids, cx));
10769    }
10770
10771    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10772        self.display_map
10773            .update(cx, |map, cx| map.snapshot(cx))
10774            .longest_row()
10775    }
10776
10777    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10778        self.display_map
10779            .update(cx, |map, cx| map.snapshot(cx))
10780            .max_point()
10781    }
10782
10783    pub fn text(&self, cx: &AppContext) -> String {
10784        self.buffer.read(cx).read(cx).text()
10785    }
10786
10787    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10788        let text = self.text(cx);
10789        let text = text.trim();
10790
10791        if text.is_empty() {
10792            return None;
10793        }
10794
10795        Some(text.to_string())
10796    }
10797
10798    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10799        self.transact(cx, |this, cx| {
10800            this.buffer
10801                .read(cx)
10802                .as_singleton()
10803                .expect("you can only call set_text on editors for singleton buffers")
10804                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10805        });
10806    }
10807
10808    pub fn display_text(&self, cx: &mut AppContext) -> String {
10809        self.display_map
10810            .update(cx, |map, cx| map.snapshot(cx))
10811            .text()
10812    }
10813
10814    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10815        let mut wrap_guides = smallvec::smallvec![];
10816
10817        if self.show_wrap_guides == Some(false) {
10818            return wrap_guides;
10819        }
10820
10821        let settings = self.buffer.read(cx).settings_at(0, cx);
10822        if settings.show_wrap_guides {
10823            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10824                wrap_guides.push((soft_wrap as usize, true));
10825            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10826                wrap_guides.push((soft_wrap as usize, true));
10827            }
10828            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10829        }
10830
10831        wrap_guides
10832    }
10833
10834    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10835        let settings = self.buffer.read(cx).settings_at(0, cx);
10836        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10837        match mode {
10838            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
10839                SoftWrap::None
10840            }
10841            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10842            language_settings::SoftWrap::PreferredLineLength => {
10843                SoftWrap::Column(settings.preferred_line_length)
10844            }
10845            language_settings::SoftWrap::Bounded => {
10846                SoftWrap::Bounded(settings.preferred_line_length)
10847            }
10848        }
10849    }
10850
10851    pub fn set_soft_wrap_mode(
10852        &mut self,
10853        mode: language_settings::SoftWrap,
10854        cx: &mut ViewContext<Self>,
10855    ) {
10856        self.soft_wrap_mode_override = Some(mode);
10857        cx.notify();
10858    }
10859
10860    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
10861        self.text_style_refinement = Some(style);
10862    }
10863
10864    /// called by the Element so we know what style we were most recently rendered with.
10865    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10866        let rem_size = cx.rem_size();
10867        self.display_map.update(cx, |map, cx| {
10868            map.set_font(
10869                style.text.font(),
10870                style.text.font_size.to_pixels(rem_size),
10871                cx,
10872            )
10873        });
10874        self.style = Some(style);
10875    }
10876
10877    pub fn style(&self) -> Option<&EditorStyle> {
10878        self.style.as_ref()
10879    }
10880
10881    // Called by the element. This method is not designed to be called outside of the editor
10882    // element's layout code because it does not notify when rewrapping is computed synchronously.
10883    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10884        self.display_map
10885            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10886    }
10887
10888    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10889        if self.soft_wrap_mode_override.is_some() {
10890            self.soft_wrap_mode_override.take();
10891        } else {
10892            let soft_wrap = match self.soft_wrap_mode(cx) {
10893                SoftWrap::GitDiff => return,
10894                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
10895                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10896                    language_settings::SoftWrap::None
10897                }
10898            };
10899            self.soft_wrap_mode_override = Some(soft_wrap);
10900        }
10901        cx.notify();
10902    }
10903
10904    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10905        let Some(workspace) = self.workspace() else {
10906            return;
10907        };
10908        let fs = workspace.read(cx).app_state().fs.clone();
10909        let current_show = TabBarSettings::get_global(cx).show;
10910        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10911            setting.show = Some(!current_show);
10912        });
10913    }
10914
10915    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10916        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10917            self.buffer
10918                .read(cx)
10919                .settings_at(0, cx)
10920                .indent_guides
10921                .enabled
10922        });
10923        self.show_indent_guides = Some(!currently_enabled);
10924        cx.notify();
10925    }
10926
10927    fn should_show_indent_guides(&self) -> Option<bool> {
10928        self.show_indent_guides
10929    }
10930
10931    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10932        let mut editor_settings = EditorSettings::get_global(cx).clone();
10933        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10934        EditorSettings::override_global(editor_settings, cx);
10935    }
10936
10937    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10938        self.use_relative_line_numbers
10939            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10940    }
10941
10942    pub fn toggle_relative_line_numbers(
10943        &mut self,
10944        _: &ToggleRelativeLineNumbers,
10945        cx: &mut ViewContext<Self>,
10946    ) {
10947        let is_relative = self.should_use_relative_line_numbers(cx);
10948        self.set_relative_line_number(Some(!is_relative), cx)
10949    }
10950
10951    pub fn set_relative_line_number(
10952        &mut self,
10953        is_relative: Option<bool>,
10954        cx: &mut ViewContext<Self>,
10955    ) {
10956        self.use_relative_line_numbers = is_relative;
10957        cx.notify();
10958    }
10959
10960    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10961        self.show_gutter = show_gutter;
10962        cx.notify();
10963    }
10964
10965    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10966        self.show_line_numbers = Some(show_line_numbers);
10967        cx.notify();
10968    }
10969
10970    pub fn set_show_git_diff_gutter(
10971        &mut self,
10972        show_git_diff_gutter: bool,
10973        cx: &mut ViewContext<Self>,
10974    ) {
10975        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10976        cx.notify();
10977    }
10978
10979    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10980        self.show_code_actions = Some(show_code_actions);
10981        cx.notify();
10982    }
10983
10984    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10985        self.show_runnables = Some(show_runnables);
10986        cx.notify();
10987    }
10988
10989    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10990        if self.display_map.read(cx).masked != masked {
10991            self.display_map.update(cx, |map, _| map.masked = masked);
10992        }
10993        cx.notify()
10994    }
10995
10996    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10997        self.show_wrap_guides = Some(show_wrap_guides);
10998        cx.notify();
10999    }
11000
11001    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11002        self.show_indent_guides = Some(show_indent_guides);
11003        cx.notify();
11004    }
11005
11006    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11007        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11008            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11009                if let Some(dir) = file.abs_path(cx).parent() {
11010                    return Some(dir.to_owned());
11011                }
11012            }
11013
11014            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11015                return Some(project_path.path.to_path_buf());
11016            }
11017        }
11018
11019        None
11020    }
11021
11022    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11023        self.active_excerpt(cx)?
11024            .1
11025            .read(cx)
11026            .file()
11027            .and_then(|f| f.as_local())
11028    }
11029
11030    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11031        if let Some(target) = self.target_file(cx) {
11032            cx.reveal_path(&target.abs_path(cx));
11033        }
11034    }
11035
11036    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11037        if let Some(file) = self.target_file(cx) {
11038            if let Some(path) = file.abs_path(cx).to_str() {
11039                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11040            }
11041        }
11042    }
11043
11044    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11045        if let Some(file) = self.target_file(cx) {
11046            if let Some(path) = file.path().to_str() {
11047                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11048            }
11049        }
11050    }
11051
11052    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11053        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11054
11055        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11056            self.start_git_blame(true, cx);
11057        }
11058
11059        cx.notify();
11060    }
11061
11062    pub fn toggle_git_blame_inline(
11063        &mut self,
11064        _: &ToggleGitBlameInline,
11065        cx: &mut ViewContext<Self>,
11066    ) {
11067        self.toggle_git_blame_inline_internal(true, cx);
11068        cx.notify();
11069    }
11070
11071    pub fn git_blame_inline_enabled(&self) -> bool {
11072        self.git_blame_inline_enabled
11073    }
11074
11075    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11076        self.show_selection_menu = self
11077            .show_selection_menu
11078            .map(|show_selections_menu| !show_selections_menu)
11079            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11080
11081        cx.notify();
11082    }
11083
11084    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11085        self.show_selection_menu
11086            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11087    }
11088
11089    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11090        if let Some(project) = self.project.as_ref() {
11091            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11092                return;
11093            };
11094
11095            if buffer.read(cx).file().is_none() {
11096                return;
11097            }
11098
11099            let focused = self.focus_handle(cx).contains_focused(cx);
11100
11101            let project = project.clone();
11102            let blame =
11103                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11104            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11105            self.blame = Some(blame);
11106        }
11107    }
11108
11109    fn toggle_git_blame_inline_internal(
11110        &mut self,
11111        user_triggered: bool,
11112        cx: &mut ViewContext<Self>,
11113    ) {
11114        if self.git_blame_inline_enabled {
11115            self.git_blame_inline_enabled = false;
11116            self.show_git_blame_inline = false;
11117            self.show_git_blame_inline_delay_task.take();
11118        } else {
11119            self.git_blame_inline_enabled = true;
11120            self.start_git_blame_inline(user_triggered, cx);
11121        }
11122
11123        cx.notify();
11124    }
11125
11126    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11127        self.start_git_blame(user_triggered, cx);
11128
11129        if ProjectSettings::get_global(cx)
11130            .git
11131            .inline_blame_delay()
11132            .is_some()
11133        {
11134            self.start_inline_blame_timer(cx);
11135        } else {
11136            self.show_git_blame_inline = true
11137        }
11138    }
11139
11140    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11141        self.blame.as_ref()
11142    }
11143
11144    pub fn show_git_blame_gutter(&self) -> bool {
11145        self.show_git_blame_gutter
11146    }
11147
11148    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11149        self.show_git_blame_gutter && self.has_blame_entries(cx)
11150    }
11151
11152    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11153        self.show_git_blame_inline
11154            && self.focus_handle.is_focused(cx)
11155            && !self.newest_selection_head_on_empty_line(cx)
11156            && self.has_blame_entries(cx)
11157    }
11158
11159    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11160        self.blame()
11161            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11162    }
11163
11164    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11165        let cursor_anchor = self.selections.newest_anchor().head();
11166
11167        let snapshot = self.buffer.read(cx).snapshot(cx);
11168        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11169
11170        snapshot.line_len(buffer_row) == 0
11171    }
11172
11173    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11174        let buffer_and_selection = maybe!({
11175            let selection = self.selections.newest::<Point>(cx);
11176            let selection_range = selection.range();
11177
11178            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11179                (buffer, selection_range.start.row..selection_range.end.row)
11180            } else {
11181                let buffer_ranges = self
11182                    .buffer()
11183                    .read(cx)
11184                    .range_to_buffer_ranges(selection_range, cx);
11185
11186                let (buffer, range, _) = if selection.reversed {
11187                    buffer_ranges.first()
11188                } else {
11189                    buffer_ranges.last()
11190                }?;
11191
11192                let snapshot = buffer.read(cx).snapshot();
11193                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11194                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11195                (buffer.clone(), selection)
11196            };
11197
11198            Some((buffer, selection))
11199        });
11200
11201        let Some((buffer, selection)) = buffer_and_selection else {
11202            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11203        };
11204
11205        let Some(project) = self.project.as_ref() else {
11206            return Task::ready(Err(anyhow!("editor does not have project")));
11207        };
11208
11209        project.update(cx, |project, cx| {
11210            project.get_permalink_to_line(&buffer, selection, cx)
11211        })
11212    }
11213
11214    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11215        let permalink_task = self.get_permalink_to_line(cx);
11216        let workspace = self.workspace();
11217
11218        cx.spawn(|_, mut cx| async move {
11219            match permalink_task.await {
11220                Ok(permalink) => {
11221                    cx.update(|cx| {
11222                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11223                    })
11224                    .ok();
11225                }
11226                Err(err) => {
11227                    let message = format!("Failed to copy permalink: {err}");
11228
11229                    Err::<(), anyhow::Error>(err).log_err();
11230
11231                    if let Some(workspace) = workspace {
11232                        workspace
11233                            .update(&mut cx, |workspace, cx| {
11234                                struct CopyPermalinkToLine;
11235
11236                                workspace.show_toast(
11237                                    Toast::new(
11238                                        NotificationId::unique::<CopyPermalinkToLine>(),
11239                                        message,
11240                                    ),
11241                                    cx,
11242                                )
11243                            })
11244                            .ok();
11245                    }
11246                }
11247            }
11248        })
11249        .detach();
11250    }
11251
11252    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11253        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11254        if let Some(file) = self.target_file(cx) {
11255            if let Some(path) = file.path().to_str() {
11256                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11257            }
11258        }
11259    }
11260
11261    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11262        let permalink_task = self.get_permalink_to_line(cx);
11263        let workspace = self.workspace();
11264
11265        cx.spawn(|_, mut cx| async move {
11266            match permalink_task.await {
11267                Ok(permalink) => {
11268                    cx.update(|cx| {
11269                        cx.open_url(permalink.as_ref());
11270                    })
11271                    .ok();
11272                }
11273                Err(err) => {
11274                    let message = format!("Failed to open permalink: {err}");
11275
11276                    Err::<(), anyhow::Error>(err).log_err();
11277
11278                    if let Some(workspace) = workspace {
11279                        workspace
11280                            .update(&mut cx, |workspace, cx| {
11281                                struct OpenPermalinkToLine;
11282
11283                                workspace.show_toast(
11284                                    Toast::new(
11285                                        NotificationId::unique::<OpenPermalinkToLine>(),
11286                                        message,
11287                                    ),
11288                                    cx,
11289                                )
11290                            })
11291                            .ok();
11292                    }
11293                }
11294            }
11295        })
11296        .detach();
11297    }
11298
11299    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11300        self.insert_uuid(UuidVersion::V4, cx);
11301    }
11302
11303    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11304        self.insert_uuid(UuidVersion::V7, cx);
11305    }
11306
11307    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11308        self.transact(cx, |this, cx| {
11309            let edits = this
11310                .selections
11311                .all::<Point>(cx)
11312                .into_iter()
11313                .map(|selection| {
11314                    let uuid = match version {
11315                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11316                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11317                    };
11318
11319                    (selection.range(), uuid.to_string())
11320                });
11321            this.edit(edits, cx);
11322            this.refresh_inline_completion(true, false, cx);
11323        });
11324    }
11325
11326    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11327    /// last highlight added will be used.
11328    ///
11329    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11330    pub fn highlight_rows<T: 'static>(
11331        &mut self,
11332        range: Range<Anchor>,
11333        color: Hsla,
11334        should_autoscroll: bool,
11335        cx: &mut ViewContext<Self>,
11336    ) {
11337        let snapshot = self.buffer().read(cx).snapshot(cx);
11338        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11339        let ix = row_highlights.binary_search_by(|highlight| {
11340            Ordering::Equal
11341                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11342                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11343        });
11344
11345        if let Err(mut ix) = ix {
11346            let index = post_inc(&mut self.highlight_order);
11347
11348            // If this range intersects with the preceding highlight, then merge it with
11349            // the preceding highlight. Otherwise insert a new highlight.
11350            let mut merged = false;
11351            if ix > 0 {
11352                let prev_highlight = &mut row_highlights[ix - 1];
11353                if prev_highlight
11354                    .range
11355                    .end
11356                    .cmp(&range.start, &snapshot)
11357                    .is_ge()
11358                {
11359                    ix -= 1;
11360                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11361                        prev_highlight.range.end = range.end;
11362                    }
11363                    merged = true;
11364                    prev_highlight.index = index;
11365                    prev_highlight.color = color;
11366                    prev_highlight.should_autoscroll = should_autoscroll;
11367                }
11368            }
11369
11370            if !merged {
11371                row_highlights.insert(
11372                    ix,
11373                    RowHighlight {
11374                        range: range.clone(),
11375                        index,
11376                        color,
11377                        should_autoscroll,
11378                    },
11379                );
11380            }
11381
11382            // If any of the following highlights intersect with this one, merge them.
11383            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11384                let highlight = &row_highlights[ix];
11385                if next_highlight
11386                    .range
11387                    .start
11388                    .cmp(&highlight.range.end, &snapshot)
11389                    .is_le()
11390                {
11391                    if next_highlight
11392                        .range
11393                        .end
11394                        .cmp(&highlight.range.end, &snapshot)
11395                        .is_gt()
11396                    {
11397                        row_highlights[ix].range.end = next_highlight.range.end;
11398                    }
11399                    row_highlights.remove(ix + 1);
11400                } else {
11401                    break;
11402                }
11403            }
11404        }
11405    }
11406
11407    /// Remove any highlighted row ranges of the given type that intersect the
11408    /// given ranges.
11409    pub fn remove_highlighted_rows<T: 'static>(
11410        &mut self,
11411        ranges_to_remove: Vec<Range<Anchor>>,
11412        cx: &mut ViewContext<Self>,
11413    ) {
11414        let snapshot = self.buffer().read(cx).snapshot(cx);
11415        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11416        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11417        row_highlights.retain(|highlight| {
11418            while let Some(range_to_remove) = ranges_to_remove.peek() {
11419                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11420                    Ordering::Less | Ordering::Equal => {
11421                        ranges_to_remove.next();
11422                    }
11423                    Ordering::Greater => {
11424                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11425                            Ordering::Less | Ordering::Equal => {
11426                                return false;
11427                            }
11428                            Ordering::Greater => break,
11429                        }
11430                    }
11431                }
11432            }
11433
11434            true
11435        })
11436    }
11437
11438    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11439    pub fn clear_row_highlights<T: 'static>(&mut self) {
11440        self.highlighted_rows.remove(&TypeId::of::<T>());
11441    }
11442
11443    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11444    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11445        self.highlighted_rows
11446            .get(&TypeId::of::<T>())
11447            .map_or(&[] as &[_], |vec| vec.as_slice())
11448            .iter()
11449            .map(|highlight| (highlight.range.clone(), highlight.color))
11450    }
11451
11452    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11453    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11454    /// Allows to ignore certain kinds of highlights.
11455    pub fn highlighted_display_rows(
11456        &mut self,
11457        cx: &mut WindowContext,
11458    ) -> BTreeMap<DisplayRow, Hsla> {
11459        let snapshot = self.snapshot(cx);
11460        let mut used_highlight_orders = HashMap::default();
11461        self.highlighted_rows
11462            .iter()
11463            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11464            .fold(
11465                BTreeMap::<DisplayRow, Hsla>::new(),
11466                |mut unique_rows, highlight| {
11467                    let start = highlight.range.start.to_display_point(&snapshot);
11468                    let end = highlight.range.end.to_display_point(&snapshot);
11469                    let start_row = start.row().0;
11470                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11471                        && end.column() == 0
11472                    {
11473                        end.row().0.saturating_sub(1)
11474                    } else {
11475                        end.row().0
11476                    };
11477                    for row in start_row..=end_row {
11478                        let used_index =
11479                            used_highlight_orders.entry(row).or_insert(highlight.index);
11480                        if highlight.index >= *used_index {
11481                            *used_index = highlight.index;
11482                            unique_rows.insert(DisplayRow(row), highlight.color);
11483                        }
11484                    }
11485                    unique_rows
11486                },
11487            )
11488    }
11489
11490    pub fn highlighted_display_row_for_autoscroll(
11491        &self,
11492        snapshot: &DisplaySnapshot,
11493    ) -> Option<DisplayRow> {
11494        self.highlighted_rows
11495            .values()
11496            .flat_map(|highlighted_rows| highlighted_rows.iter())
11497            .filter_map(|highlight| {
11498                if highlight.should_autoscroll {
11499                    Some(highlight.range.start.to_display_point(snapshot).row())
11500                } else {
11501                    None
11502                }
11503            })
11504            .min()
11505    }
11506
11507    pub fn set_search_within_ranges(
11508        &mut self,
11509        ranges: &[Range<Anchor>],
11510        cx: &mut ViewContext<Self>,
11511    ) {
11512        self.highlight_background::<SearchWithinRange>(
11513            ranges,
11514            |colors| colors.editor_document_highlight_read_background,
11515            cx,
11516        )
11517    }
11518
11519    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11520        self.breadcrumb_header = Some(new_header);
11521    }
11522
11523    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11524        self.clear_background_highlights::<SearchWithinRange>(cx);
11525    }
11526
11527    pub fn highlight_background<T: 'static>(
11528        &mut self,
11529        ranges: &[Range<Anchor>],
11530        color_fetcher: fn(&ThemeColors) -> Hsla,
11531        cx: &mut ViewContext<Self>,
11532    ) {
11533        self.background_highlights
11534            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11535        self.scrollbar_marker_state.dirty = true;
11536        cx.notify();
11537    }
11538
11539    pub fn clear_background_highlights<T: 'static>(
11540        &mut self,
11541        cx: &mut ViewContext<Self>,
11542    ) -> Option<BackgroundHighlight> {
11543        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11544        if !text_highlights.1.is_empty() {
11545            self.scrollbar_marker_state.dirty = true;
11546            cx.notify();
11547        }
11548        Some(text_highlights)
11549    }
11550
11551    pub fn highlight_gutter<T: 'static>(
11552        &mut self,
11553        ranges: &[Range<Anchor>],
11554        color_fetcher: fn(&AppContext) -> Hsla,
11555        cx: &mut ViewContext<Self>,
11556    ) {
11557        self.gutter_highlights
11558            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11559        cx.notify();
11560    }
11561
11562    pub fn clear_gutter_highlights<T: 'static>(
11563        &mut self,
11564        cx: &mut ViewContext<Self>,
11565    ) -> Option<GutterHighlight> {
11566        cx.notify();
11567        self.gutter_highlights.remove(&TypeId::of::<T>())
11568    }
11569
11570    #[cfg(feature = "test-support")]
11571    pub fn all_text_background_highlights(
11572        &mut self,
11573        cx: &mut ViewContext<Self>,
11574    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11575        let snapshot = self.snapshot(cx);
11576        let buffer = &snapshot.buffer_snapshot;
11577        let start = buffer.anchor_before(0);
11578        let end = buffer.anchor_after(buffer.len());
11579        let theme = cx.theme().colors();
11580        self.background_highlights_in_range(start..end, &snapshot, theme)
11581    }
11582
11583    #[cfg(feature = "test-support")]
11584    pub fn search_background_highlights(
11585        &mut self,
11586        cx: &mut ViewContext<Self>,
11587    ) -> Vec<Range<Point>> {
11588        let snapshot = self.buffer().read(cx).snapshot(cx);
11589
11590        let highlights = self
11591            .background_highlights
11592            .get(&TypeId::of::<items::BufferSearchHighlights>());
11593
11594        if let Some((_color, ranges)) = highlights {
11595            ranges
11596                .iter()
11597                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11598                .collect_vec()
11599        } else {
11600            vec![]
11601        }
11602    }
11603
11604    fn document_highlights_for_position<'a>(
11605        &'a self,
11606        position: Anchor,
11607        buffer: &'a MultiBufferSnapshot,
11608    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11609        let read_highlights = self
11610            .background_highlights
11611            .get(&TypeId::of::<DocumentHighlightRead>())
11612            .map(|h| &h.1);
11613        let write_highlights = self
11614            .background_highlights
11615            .get(&TypeId::of::<DocumentHighlightWrite>())
11616            .map(|h| &h.1);
11617        let left_position = position.bias_left(buffer);
11618        let right_position = position.bias_right(buffer);
11619        read_highlights
11620            .into_iter()
11621            .chain(write_highlights)
11622            .flat_map(move |ranges| {
11623                let start_ix = match ranges.binary_search_by(|probe| {
11624                    let cmp = probe.end.cmp(&left_position, buffer);
11625                    if cmp.is_ge() {
11626                        Ordering::Greater
11627                    } else {
11628                        Ordering::Less
11629                    }
11630                }) {
11631                    Ok(i) | Err(i) => i,
11632                };
11633
11634                ranges[start_ix..]
11635                    .iter()
11636                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11637            })
11638    }
11639
11640    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11641        self.background_highlights
11642            .get(&TypeId::of::<T>())
11643            .map_or(false, |(_, highlights)| !highlights.is_empty())
11644    }
11645
11646    pub fn background_highlights_in_range(
11647        &self,
11648        search_range: Range<Anchor>,
11649        display_snapshot: &DisplaySnapshot,
11650        theme: &ThemeColors,
11651    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11652        let mut results = Vec::new();
11653        for (color_fetcher, ranges) in self.background_highlights.values() {
11654            let color = color_fetcher(theme);
11655            let start_ix = match ranges.binary_search_by(|probe| {
11656                let cmp = probe
11657                    .end
11658                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11659                if cmp.is_gt() {
11660                    Ordering::Greater
11661                } else {
11662                    Ordering::Less
11663                }
11664            }) {
11665                Ok(i) | Err(i) => i,
11666            };
11667            for range in &ranges[start_ix..] {
11668                if range
11669                    .start
11670                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11671                    .is_ge()
11672                {
11673                    break;
11674                }
11675
11676                let start = range.start.to_display_point(display_snapshot);
11677                let end = range.end.to_display_point(display_snapshot);
11678                results.push((start..end, color))
11679            }
11680        }
11681        results
11682    }
11683
11684    pub fn background_highlight_row_ranges<T: 'static>(
11685        &self,
11686        search_range: Range<Anchor>,
11687        display_snapshot: &DisplaySnapshot,
11688        count: usize,
11689    ) -> Vec<RangeInclusive<DisplayPoint>> {
11690        let mut results = Vec::new();
11691        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11692            return vec![];
11693        };
11694
11695        let start_ix = match ranges.binary_search_by(|probe| {
11696            let cmp = probe
11697                .end
11698                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11699            if cmp.is_gt() {
11700                Ordering::Greater
11701            } else {
11702                Ordering::Less
11703            }
11704        }) {
11705            Ok(i) | Err(i) => i,
11706        };
11707        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11708            if let (Some(start_display), Some(end_display)) = (start, end) {
11709                results.push(
11710                    start_display.to_display_point(display_snapshot)
11711                        ..=end_display.to_display_point(display_snapshot),
11712                );
11713            }
11714        };
11715        let mut start_row: Option<Point> = None;
11716        let mut end_row: Option<Point> = None;
11717        if ranges.len() > count {
11718            return Vec::new();
11719        }
11720        for range in &ranges[start_ix..] {
11721            if range
11722                .start
11723                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11724                .is_ge()
11725            {
11726                break;
11727            }
11728            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11729            if let Some(current_row) = &end_row {
11730                if end.row == current_row.row {
11731                    continue;
11732                }
11733            }
11734            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11735            if start_row.is_none() {
11736                assert_eq!(end_row, None);
11737                start_row = Some(start);
11738                end_row = Some(end);
11739                continue;
11740            }
11741            if let Some(current_end) = end_row.as_mut() {
11742                if start.row > current_end.row + 1 {
11743                    push_region(start_row, end_row);
11744                    start_row = Some(start);
11745                    end_row = Some(end);
11746                } else {
11747                    // Merge two hunks.
11748                    *current_end = end;
11749                }
11750            } else {
11751                unreachable!();
11752            }
11753        }
11754        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11755        push_region(start_row, end_row);
11756        results
11757    }
11758
11759    pub fn gutter_highlights_in_range(
11760        &self,
11761        search_range: Range<Anchor>,
11762        display_snapshot: &DisplaySnapshot,
11763        cx: &AppContext,
11764    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11765        let mut results = Vec::new();
11766        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11767            let color = color_fetcher(cx);
11768            let start_ix = match ranges.binary_search_by(|probe| {
11769                let cmp = probe
11770                    .end
11771                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11772                if cmp.is_gt() {
11773                    Ordering::Greater
11774                } else {
11775                    Ordering::Less
11776                }
11777            }) {
11778                Ok(i) | Err(i) => i,
11779            };
11780            for range in &ranges[start_ix..] {
11781                if range
11782                    .start
11783                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11784                    .is_ge()
11785                {
11786                    break;
11787                }
11788
11789                let start = range.start.to_display_point(display_snapshot);
11790                let end = range.end.to_display_point(display_snapshot);
11791                results.push((start..end, color))
11792            }
11793        }
11794        results
11795    }
11796
11797    /// Get the text ranges corresponding to the redaction query
11798    pub fn redacted_ranges(
11799        &self,
11800        search_range: Range<Anchor>,
11801        display_snapshot: &DisplaySnapshot,
11802        cx: &WindowContext,
11803    ) -> Vec<Range<DisplayPoint>> {
11804        display_snapshot
11805            .buffer_snapshot
11806            .redacted_ranges(search_range, |file| {
11807                if let Some(file) = file {
11808                    file.is_private()
11809                        && EditorSettings::get(
11810                            Some(SettingsLocation {
11811                                worktree_id: file.worktree_id(cx),
11812                                path: file.path().as_ref(),
11813                            }),
11814                            cx,
11815                        )
11816                        .redact_private_values
11817                } else {
11818                    false
11819                }
11820            })
11821            .map(|range| {
11822                range.start.to_display_point(display_snapshot)
11823                    ..range.end.to_display_point(display_snapshot)
11824            })
11825            .collect()
11826    }
11827
11828    pub fn highlight_text<T: 'static>(
11829        &mut self,
11830        ranges: Vec<Range<Anchor>>,
11831        style: HighlightStyle,
11832        cx: &mut ViewContext<Self>,
11833    ) {
11834        self.display_map.update(cx, |map, _| {
11835            map.highlight_text(TypeId::of::<T>(), ranges, style)
11836        });
11837        cx.notify();
11838    }
11839
11840    pub(crate) fn highlight_inlays<T: 'static>(
11841        &mut self,
11842        highlights: Vec<InlayHighlight>,
11843        style: HighlightStyle,
11844        cx: &mut ViewContext<Self>,
11845    ) {
11846        self.display_map.update(cx, |map, _| {
11847            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11848        });
11849        cx.notify();
11850    }
11851
11852    pub fn text_highlights<'a, T: 'static>(
11853        &'a self,
11854        cx: &'a AppContext,
11855    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11856        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11857    }
11858
11859    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11860        let cleared = self
11861            .display_map
11862            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11863        if cleared {
11864            cx.notify();
11865        }
11866    }
11867
11868    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11869        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11870            && self.focus_handle.is_focused(cx)
11871    }
11872
11873    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11874        self.show_cursor_when_unfocused = is_enabled;
11875        cx.notify();
11876    }
11877
11878    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
11879        self.project
11880            .as_ref()
11881            .map(|project| project.read(cx).lsp_store())
11882    }
11883
11884    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11885        cx.notify();
11886    }
11887
11888    fn on_buffer_event(
11889        &mut self,
11890        multibuffer: Model<MultiBuffer>,
11891        event: &multi_buffer::Event,
11892        cx: &mut ViewContext<Self>,
11893    ) {
11894        match event {
11895            multi_buffer::Event::Edited {
11896                singleton_buffer_edited,
11897                edited_buffer: buffer_edited,
11898            } => {
11899                self.scrollbar_marker_state.dirty = true;
11900                self.active_indent_guides_state.dirty = true;
11901                self.refresh_active_diagnostics(cx);
11902                self.refresh_code_actions(cx);
11903                if self.has_active_inline_completion() {
11904                    self.update_visible_inline_completion(cx);
11905                }
11906                if let Some(buffer) = buffer_edited {
11907                    let buffer_id = buffer.read(cx).remote_id();
11908                    if !self.registered_buffers.contains_key(&buffer_id) {
11909                        if let Some(lsp_store) = self.lsp_store(cx) {
11910                            lsp_store.update(cx, |lsp_store, cx| {
11911                                self.registered_buffers.insert(
11912                                    buffer_id,
11913                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
11914                                );
11915                            })
11916                        }
11917                    }
11918                }
11919                cx.emit(EditorEvent::BufferEdited);
11920                cx.emit(SearchEvent::MatchesInvalidated);
11921                if *singleton_buffer_edited {
11922                    if let Some(project) = &self.project {
11923                        let project = project.read(cx);
11924                        #[allow(clippy::mutable_key_type)]
11925                        let languages_affected = multibuffer
11926                            .read(cx)
11927                            .all_buffers()
11928                            .into_iter()
11929                            .filter_map(|buffer| {
11930                                let buffer = buffer.read(cx);
11931                                let language = buffer.language()?;
11932                                if project.is_local()
11933                                    && project
11934                                        .language_servers_for_local_buffer(buffer, cx)
11935                                        .count()
11936                                        == 0
11937                                {
11938                                    None
11939                                } else {
11940                                    Some(language)
11941                                }
11942                            })
11943                            .cloned()
11944                            .collect::<HashSet<_>>();
11945                        if !languages_affected.is_empty() {
11946                            self.refresh_inlay_hints(
11947                                InlayHintRefreshReason::BufferEdited(languages_affected),
11948                                cx,
11949                            );
11950                        }
11951                    }
11952                }
11953
11954                let Some(project) = &self.project else { return };
11955                let (telemetry, is_via_ssh) = {
11956                    let project = project.read(cx);
11957                    let telemetry = project.client().telemetry().clone();
11958                    let is_via_ssh = project.is_via_ssh();
11959                    (telemetry, is_via_ssh)
11960                };
11961                refresh_linked_ranges(self, cx);
11962                telemetry.log_edit_event("editor", is_via_ssh);
11963            }
11964            multi_buffer::Event::ExcerptsAdded {
11965                buffer,
11966                predecessor,
11967                excerpts,
11968            } => {
11969                self.tasks_update_task = Some(self.refresh_runnables(cx));
11970                let buffer_id = buffer.read(cx).remote_id();
11971                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
11972                    if let Some(project) = &self.project {
11973                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
11974                    }
11975                }
11976                cx.emit(EditorEvent::ExcerptsAdded {
11977                    buffer: buffer.clone(),
11978                    predecessor: *predecessor,
11979                    excerpts: excerpts.clone(),
11980                });
11981                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11982            }
11983            multi_buffer::Event::ExcerptsRemoved { ids } => {
11984                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11985                let buffer = self.buffer.read(cx);
11986                self.registered_buffers
11987                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
11988                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11989            }
11990            multi_buffer::Event::ExcerptsEdited { ids } => {
11991                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11992            }
11993            multi_buffer::Event::ExcerptsExpanded { ids } => {
11994                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11995            }
11996            multi_buffer::Event::Reparsed(buffer_id) => {
11997                self.tasks_update_task = Some(self.refresh_runnables(cx));
11998
11999                cx.emit(EditorEvent::Reparsed(*buffer_id));
12000            }
12001            multi_buffer::Event::LanguageChanged(buffer_id) => {
12002                linked_editing_ranges::refresh_linked_ranges(self, cx);
12003                cx.emit(EditorEvent::Reparsed(*buffer_id));
12004                cx.notify();
12005            }
12006            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12007            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12008            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12009                cx.emit(EditorEvent::TitleChanged)
12010            }
12011            // multi_buffer::Event::DiffBaseChanged => {
12012            //     self.scrollbar_marker_state.dirty = true;
12013            //     cx.emit(EditorEvent::DiffBaseChanged);
12014            //     cx.notify();
12015            // }
12016            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12017            multi_buffer::Event::DiagnosticsUpdated => {
12018                self.refresh_active_diagnostics(cx);
12019                self.scrollbar_marker_state.dirty = true;
12020                cx.notify();
12021            }
12022            _ => {}
12023        };
12024    }
12025
12026    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12027        cx.notify();
12028    }
12029
12030    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12031        self.tasks_update_task = Some(self.refresh_runnables(cx));
12032        self.refresh_inline_completion(true, false, cx);
12033        self.refresh_inlay_hints(
12034            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12035                self.selections.newest_anchor().head(),
12036                &self.buffer.read(cx).snapshot(cx),
12037                cx,
12038            )),
12039            cx,
12040        );
12041
12042        let old_cursor_shape = self.cursor_shape;
12043
12044        {
12045            let editor_settings = EditorSettings::get_global(cx);
12046            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12047            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12048            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12049        }
12050
12051        if old_cursor_shape != self.cursor_shape {
12052            cx.emit(EditorEvent::CursorShapeChanged);
12053        }
12054
12055        let project_settings = ProjectSettings::get_global(cx);
12056        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12057
12058        if self.mode == EditorMode::Full {
12059            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12060            if self.git_blame_inline_enabled != inline_blame_enabled {
12061                self.toggle_git_blame_inline_internal(false, cx);
12062            }
12063        }
12064
12065        cx.notify();
12066    }
12067
12068    pub fn set_searchable(&mut self, searchable: bool) {
12069        self.searchable = searchable;
12070    }
12071
12072    pub fn searchable(&self) -> bool {
12073        self.searchable
12074    }
12075
12076    fn open_proposed_changes_editor(
12077        &mut self,
12078        _: &OpenProposedChangesEditor,
12079        cx: &mut ViewContext<Self>,
12080    ) {
12081        let Some(workspace) = self.workspace() else {
12082            cx.propagate();
12083            return;
12084        };
12085
12086        let selections = self.selections.all::<usize>(cx);
12087        let buffer = self.buffer.read(cx);
12088        let mut new_selections_by_buffer = HashMap::default();
12089        for selection in selections {
12090            for (buffer, range, _) in
12091                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12092            {
12093                let mut range = range.to_point(buffer.read(cx));
12094                range.start.column = 0;
12095                range.end.column = buffer.read(cx).line_len(range.end.row);
12096                new_selections_by_buffer
12097                    .entry(buffer)
12098                    .or_insert(Vec::new())
12099                    .push(range)
12100            }
12101        }
12102
12103        let proposed_changes_buffers = new_selections_by_buffer
12104            .into_iter()
12105            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12106            .collect::<Vec<_>>();
12107        let proposed_changes_editor = cx.new_view(|cx| {
12108            ProposedChangesEditor::new(
12109                "Proposed changes",
12110                proposed_changes_buffers,
12111                self.project.clone(),
12112                cx,
12113            )
12114        });
12115
12116        cx.window_context().defer(move |cx| {
12117            workspace.update(cx, |workspace, cx| {
12118                workspace.active_pane().update(cx, |pane, cx| {
12119                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12120                });
12121            });
12122        });
12123    }
12124
12125    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12126        self.open_excerpts_common(None, true, cx)
12127    }
12128
12129    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12130        self.open_excerpts_common(None, false, cx)
12131    }
12132
12133    fn open_excerpts_common(
12134        &mut self,
12135        jump_data: Option<JumpData>,
12136        split: bool,
12137        cx: &mut ViewContext<Self>,
12138    ) {
12139        let Some(workspace) = self.workspace() else {
12140            cx.propagate();
12141            return;
12142        };
12143
12144        if self.buffer.read(cx).is_singleton() {
12145            cx.propagate();
12146            return;
12147        }
12148
12149        let mut new_selections_by_buffer = HashMap::default();
12150        match &jump_data {
12151            Some(jump_data) => {
12152                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12153                if let Some(buffer) = multi_buffer_snapshot
12154                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12155                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12156                {
12157                    let buffer_snapshot = buffer.read(cx).snapshot();
12158                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12159                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12160                    } else {
12161                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12162                    };
12163                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12164                    new_selections_by_buffer.insert(
12165                        buffer,
12166                        (
12167                            vec![jump_to_offset..jump_to_offset],
12168                            Some(jump_data.line_offset_from_top),
12169                        ),
12170                    );
12171                }
12172            }
12173            None => {
12174                let selections = self.selections.all::<usize>(cx);
12175                let buffer = self.buffer.read(cx);
12176                for selection in selections {
12177                    for (mut buffer_handle, mut range, _) in
12178                        buffer.range_to_buffer_ranges(selection.range(), cx)
12179                    {
12180                        // When editing branch buffers, jump to the corresponding location
12181                        // in their base buffer.
12182                        let buffer = buffer_handle.read(cx);
12183                        if let Some(base_buffer) = buffer.base_buffer() {
12184                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12185                            buffer_handle = base_buffer;
12186                        }
12187
12188                        if selection.reversed {
12189                            mem::swap(&mut range.start, &mut range.end);
12190                        }
12191                        new_selections_by_buffer
12192                            .entry(buffer_handle)
12193                            .or_insert((Vec::new(), None))
12194                            .0
12195                            .push(range)
12196                    }
12197                }
12198            }
12199        }
12200
12201        if new_selections_by_buffer.is_empty() {
12202            return;
12203        }
12204
12205        // We defer the pane interaction because we ourselves are a workspace item
12206        // and activating a new item causes the pane to call a method on us reentrantly,
12207        // which panics if we're on the stack.
12208        cx.window_context().defer(move |cx| {
12209            workspace.update(cx, |workspace, cx| {
12210                let pane = if split {
12211                    workspace.adjacent_pane(cx)
12212                } else {
12213                    workspace.active_pane().clone()
12214                };
12215
12216                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12217                    let editor = buffer
12218                        .read(cx)
12219                        .file()
12220                        .is_none()
12221                        .then(|| {
12222                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12223                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12224                            // Instead, we try to activate the existing editor in the pane first.
12225                            let (editor, pane_item_index) =
12226                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12227                                    let editor = item.downcast::<Editor>()?;
12228                                    let singleton_buffer =
12229                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12230                                    if singleton_buffer == buffer {
12231                                        Some((editor, i))
12232                                    } else {
12233                                        None
12234                                    }
12235                                })?;
12236                            pane.update(cx, |pane, cx| {
12237                                pane.activate_item(pane_item_index, true, true, cx)
12238                            });
12239                            Some(editor)
12240                        })
12241                        .flatten()
12242                        .unwrap_or_else(|| {
12243                            workspace.open_project_item::<Self>(
12244                                pane.clone(),
12245                                buffer,
12246                                true,
12247                                true,
12248                                cx,
12249                            )
12250                        });
12251
12252                    editor.update(cx, |editor, cx| {
12253                        let autoscroll = match scroll_offset {
12254                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12255                            None => Autoscroll::newest(),
12256                        };
12257                        let nav_history = editor.nav_history.take();
12258                        editor.change_selections(Some(autoscroll), cx, |s| {
12259                            s.select_ranges(ranges);
12260                        });
12261                        editor.nav_history = nav_history;
12262                    });
12263                }
12264            })
12265        });
12266    }
12267
12268    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12269        let snapshot = self.buffer.read(cx).read(cx);
12270        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12271        Some(
12272            ranges
12273                .iter()
12274                .map(move |range| {
12275                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12276                })
12277                .collect(),
12278        )
12279    }
12280
12281    fn selection_replacement_ranges(
12282        &self,
12283        range: Range<OffsetUtf16>,
12284        cx: &mut AppContext,
12285    ) -> Vec<Range<OffsetUtf16>> {
12286        let selections = self.selections.all::<OffsetUtf16>(cx);
12287        let newest_selection = selections
12288            .iter()
12289            .max_by_key(|selection| selection.id)
12290            .unwrap();
12291        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12292        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12293        let snapshot = self.buffer.read(cx).read(cx);
12294        selections
12295            .into_iter()
12296            .map(|mut selection| {
12297                selection.start.0 =
12298                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12299                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12300                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12301                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12302            })
12303            .collect()
12304    }
12305
12306    fn report_editor_event(
12307        &self,
12308        operation: &'static str,
12309        file_extension: Option<String>,
12310        cx: &AppContext,
12311    ) {
12312        if cfg!(any(test, feature = "test-support")) {
12313            return;
12314        }
12315
12316        let Some(project) = &self.project else { return };
12317
12318        // If None, we are in a file without an extension
12319        let file = self
12320            .buffer
12321            .read(cx)
12322            .as_singleton()
12323            .and_then(|b| b.read(cx).file());
12324        let file_extension = file_extension.or(file
12325            .as_ref()
12326            .and_then(|file| Path::new(file.file_name(cx)).extension())
12327            .and_then(|e| e.to_str())
12328            .map(|a| a.to_string()));
12329
12330        let vim_mode = cx
12331            .global::<SettingsStore>()
12332            .raw_user_settings()
12333            .get("vim_mode")
12334            == Some(&serde_json::Value::Bool(true));
12335
12336        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12337            == language::language_settings::InlineCompletionProvider::Copilot;
12338        let copilot_enabled_for_language = self
12339            .buffer
12340            .read(cx)
12341            .settings_at(0, cx)
12342            .show_inline_completions;
12343
12344        let project = project.read(cx);
12345        let telemetry = project.client().telemetry().clone();
12346        telemetry.report_editor_event(
12347            file_extension,
12348            vim_mode,
12349            operation,
12350            copilot_enabled,
12351            copilot_enabled_for_language,
12352            project.is_via_ssh(),
12353        )
12354    }
12355
12356    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12357    /// with each line being an array of {text, highlight} objects.
12358    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12359        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12360            return;
12361        };
12362
12363        #[derive(Serialize)]
12364        struct Chunk<'a> {
12365            text: String,
12366            highlight: Option<&'a str>,
12367        }
12368
12369        let snapshot = buffer.read(cx).snapshot();
12370        let range = self
12371            .selected_text_range(false, cx)
12372            .and_then(|selection| {
12373                if selection.range.is_empty() {
12374                    None
12375                } else {
12376                    Some(selection.range)
12377                }
12378            })
12379            .unwrap_or_else(|| 0..snapshot.len());
12380
12381        let chunks = snapshot.chunks(range, true);
12382        let mut lines = Vec::new();
12383        let mut line: VecDeque<Chunk> = VecDeque::new();
12384
12385        let Some(style) = self.style.as_ref() else {
12386            return;
12387        };
12388
12389        for chunk in chunks {
12390            let highlight = chunk
12391                .syntax_highlight_id
12392                .and_then(|id| id.name(&style.syntax));
12393            let mut chunk_lines = chunk.text.split('\n').peekable();
12394            while let Some(text) = chunk_lines.next() {
12395                let mut merged_with_last_token = false;
12396                if let Some(last_token) = line.back_mut() {
12397                    if last_token.highlight == highlight {
12398                        last_token.text.push_str(text);
12399                        merged_with_last_token = true;
12400                    }
12401                }
12402
12403                if !merged_with_last_token {
12404                    line.push_back(Chunk {
12405                        text: text.into(),
12406                        highlight,
12407                    });
12408                }
12409
12410                if chunk_lines.peek().is_some() {
12411                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12412                        line.pop_front();
12413                    }
12414                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12415                        line.pop_back();
12416                    }
12417
12418                    lines.push(mem::take(&mut line));
12419                }
12420            }
12421        }
12422
12423        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12424            return;
12425        };
12426        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12427    }
12428
12429    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12430        self.request_autoscroll(Autoscroll::newest(), cx);
12431        let position = self.selections.newest_display(cx).start;
12432        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12433    }
12434
12435    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12436        &self.inlay_hint_cache
12437    }
12438
12439    pub fn replay_insert_event(
12440        &mut self,
12441        text: &str,
12442        relative_utf16_range: Option<Range<isize>>,
12443        cx: &mut ViewContext<Self>,
12444    ) {
12445        if !self.input_enabled {
12446            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12447            return;
12448        }
12449        if let Some(relative_utf16_range) = relative_utf16_range {
12450            let selections = self.selections.all::<OffsetUtf16>(cx);
12451            self.change_selections(None, cx, |s| {
12452                let new_ranges = selections.into_iter().map(|range| {
12453                    let start = OffsetUtf16(
12454                        range
12455                            .head()
12456                            .0
12457                            .saturating_add_signed(relative_utf16_range.start),
12458                    );
12459                    let end = OffsetUtf16(
12460                        range
12461                            .head()
12462                            .0
12463                            .saturating_add_signed(relative_utf16_range.end),
12464                    );
12465                    start..end
12466                });
12467                s.select_ranges(new_ranges);
12468            });
12469        }
12470
12471        self.handle_input(text, cx);
12472    }
12473
12474    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12475        let Some(provider) = self.semantics_provider.as_ref() else {
12476            return false;
12477        };
12478
12479        let mut supports = false;
12480        self.buffer().read(cx).for_each_buffer(|buffer| {
12481            supports |= provider.supports_inlay_hints(buffer, cx);
12482        });
12483        supports
12484    }
12485
12486    pub fn focus(&self, cx: &mut WindowContext) {
12487        cx.focus(&self.focus_handle)
12488    }
12489
12490    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12491        self.focus_handle.is_focused(cx)
12492    }
12493
12494    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12495        cx.emit(EditorEvent::Focused);
12496
12497        if let Some(descendant) = self
12498            .last_focused_descendant
12499            .take()
12500            .and_then(|descendant| descendant.upgrade())
12501        {
12502            cx.focus(&descendant);
12503        } else {
12504            if let Some(blame) = self.blame.as_ref() {
12505                blame.update(cx, GitBlame::focus)
12506            }
12507
12508            self.blink_manager.update(cx, BlinkManager::enable);
12509            self.show_cursor_names(cx);
12510            self.buffer.update(cx, |buffer, cx| {
12511                buffer.finalize_last_transaction(cx);
12512                if self.leader_peer_id.is_none() {
12513                    buffer.set_active_selections(
12514                        &self.selections.disjoint_anchors(),
12515                        self.selections.line_mode,
12516                        self.cursor_shape,
12517                        cx,
12518                    );
12519                }
12520            });
12521        }
12522    }
12523
12524    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12525        cx.emit(EditorEvent::FocusedIn)
12526    }
12527
12528    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12529        if event.blurred != self.focus_handle {
12530            self.last_focused_descendant = Some(event.blurred);
12531        }
12532    }
12533
12534    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12535        self.blink_manager.update(cx, BlinkManager::disable);
12536        self.buffer
12537            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12538
12539        if let Some(blame) = self.blame.as_ref() {
12540            blame.update(cx, GitBlame::blur)
12541        }
12542        if !self.hover_state.focused(cx) {
12543            hide_hover(self, cx);
12544        }
12545
12546        self.hide_context_menu(cx);
12547        cx.emit(EditorEvent::Blurred);
12548        cx.notify();
12549    }
12550
12551    pub fn register_action<A: Action>(
12552        &mut self,
12553        listener: impl Fn(&A, &mut WindowContext) + 'static,
12554    ) -> Subscription {
12555        let id = self.next_editor_action_id.post_inc();
12556        let listener = Arc::new(listener);
12557        self.editor_actions.borrow_mut().insert(
12558            id,
12559            Box::new(move |cx| {
12560                let cx = cx.window_context();
12561                let listener = listener.clone();
12562                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12563                    let action = action.downcast_ref().unwrap();
12564                    if phase == DispatchPhase::Bubble {
12565                        listener(action, cx)
12566                    }
12567                })
12568            }),
12569        );
12570
12571        let editor_actions = self.editor_actions.clone();
12572        Subscription::new(move || {
12573            editor_actions.borrow_mut().remove(&id);
12574        })
12575    }
12576
12577    pub fn file_header_size(&self) -> u32 {
12578        FILE_HEADER_HEIGHT
12579    }
12580
12581    pub fn revert(
12582        &mut self,
12583        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12584        cx: &mut ViewContext<Self>,
12585    ) {
12586        self.buffer().update(cx, |multi_buffer, cx| {
12587            for (buffer_id, changes) in revert_changes {
12588                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12589                    buffer.update(cx, |buffer, cx| {
12590                        buffer.edit(
12591                            changes.into_iter().map(|(range, text)| {
12592                                (range, text.to_string().map(Arc::<str>::from))
12593                            }),
12594                            None,
12595                            cx,
12596                        );
12597                    });
12598                }
12599            }
12600        });
12601        self.change_selections(None, cx, |selections| selections.refresh());
12602    }
12603
12604    pub fn to_pixel_point(
12605        &mut self,
12606        source: multi_buffer::Anchor,
12607        editor_snapshot: &EditorSnapshot,
12608        cx: &mut ViewContext<Self>,
12609    ) -> Option<gpui::Point<Pixels>> {
12610        let source_point = source.to_display_point(editor_snapshot);
12611        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12612    }
12613
12614    pub fn display_to_pixel_point(
12615        &self,
12616        source: DisplayPoint,
12617        editor_snapshot: &EditorSnapshot,
12618        cx: &WindowContext,
12619    ) -> Option<gpui::Point<Pixels>> {
12620        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12621        let text_layout_details = self.text_layout_details(cx);
12622        let scroll_top = text_layout_details
12623            .scroll_anchor
12624            .scroll_position(editor_snapshot)
12625            .y;
12626
12627        if source.row().as_f32() < scroll_top.floor() {
12628            return None;
12629        }
12630        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12631        let source_y = line_height * (source.row().as_f32() - scroll_top);
12632        Some(gpui::Point::new(source_x, source_y))
12633    }
12634
12635    pub fn has_active_completions_menu(&self) -> bool {
12636        self.context_menu.read().as_ref().map_or(false, |menu| {
12637            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12638        })
12639    }
12640
12641    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12642        self.addons
12643            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12644    }
12645
12646    pub fn unregister_addon<T: Addon>(&mut self) {
12647        self.addons.remove(&std::any::TypeId::of::<T>());
12648    }
12649
12650    pub fn addon<T: Addon>(&self) -> Option<&T> {
12651        let type_id = std::any::TypeId::of::<T>();
12652        self.addons
12653            .get(&type_id)
12654            .and_then(|item| item.to_any().downcast_ref::<T>())
12655    }
12656
12657    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12658        let text_layout_details = self.text_layout_details(cx);
12659        let style = &text_layout_details.editor_style;
12660        let font_id = cx.text_system().resolve_font(&style.text.font());
12661        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12662        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12663
12664        let em_width = cx
12665            .text_system()
12666            .typographic_bounds(font_id, font_size, 'm')
12667            .unwrap()
12668            .size
12669            .width;
12670
12671        gpui::Point::new(em_width, line_height)
12672    }
12673}
12674
12675fn get_unstaged_changes_for_buffers(
12676    project: &Model<Project>,
12677    buffers: impl IntoIterator<Item = Model<Buffer>>,
12678    cx: &mut ViewContext<Editor>,
12679) {
12680    let mut tasks = Vec::new();
12681    project.update(cx, |project, cx| {
12682        for buffer in buffers {
12683            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12684        }
12685    });
12686    cx.spawn(|this, mut cx| async move {
12687        let change_sets = futures::future::join_all(tasks).await;
12688        this.update(&mut cx, |this, cx| {
12689            for change_set in change_sets {
12690                if let Some(change_set) = change_set.log_err() {
12691                    this.diff_map.add_change_set(change_set, cx);
12692                }
12693            }
12694        })
12695        .ok();
12696    })
12697    .detach();
12698}
12699
12700fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12701    let tab_size = tab_size.get() as usize;
12702    let mut width = offset;
12703
12704    for ch in text.chars() {
12705        width += if ch == '\t' {
12706            tab_size - (width % tab_size)
12707        } else {
12708            1
12709        };
12710    }
12711
12712    width - offset
12713}
12714
12715#[cfg(test)]
12716mod tests {
12717    use super::*;
12718
12719    #[test]
12720    fn test_string_size_with_expanded_tabs() {
12721        let nz = |val| NonZeroU32::new(val).unwrap();
12722        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12723        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12724        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12725        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12726        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12727        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12728        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12729        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12730    }
12731}
12732
12733/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
12734struct WordBreakingTokenizer<'a> {
12735    input: &'a str,
12736}
12737
12738impl<'a> WordBreakingTokenizer<'a> {
12739    fn new(input: &'a str) -> Self {
12740        Self { input }
12741    }
12742}
12743
12744fn is_char_ideographic(ch: char) -> bool {
12745    use unicode_script::Script::*;
12746    use unicode_script::UnicodeScript;
12747    matches!(ch.script(), Han | Tangut | Yi)
12748}
12749
12750fn is_grapheme_ideographic(text: &str) -> bool {
12751    text.chars().any(is_char_ideographic)
12752}
12753
12754fn is_grapheme_whitespace(text: &str) -> bool {
12755    text.chars().any(|x| x.is_whitespace())
12756}
12757
12758fn should_stay_with_preceding_ideograph(text: &str) -> bool {
12759    text.chars().next().map_or(false, |ch| {
12760        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
12761    })
12762}
12763
12764#[derive(PartialEq, Eq, Debug, Clone, Copy)]
12765struct WordBreakToken<'a> {
12766    token: &'a str,
12767    grapheme_len: usize,
12768    is_whitespace: bool,
12769}
12770
12771impl<'a> Iterator for WordBreakingTokenizer<'a> {
12772    /// Yields a span, the count of graphemes in the token, and whether it was
12773    /// whitespace. Note that it also breaks at word boundaries.
12774    type Item = WordBreakToken<'a>;
12775
12776    fn next(&mut self) -> Option<Self::Item> {
12777        use unicode_segmentation::UnicodeSegmentation;
12778        if self.input.is_empty() {
12779            return None;
12780        }
12781
12782        let mut iter = self.input.graphemes(true).peekable();
12783        let mut offset = 0;
12784        let mut graphemes = 0;
12785        if let Some(first_grapheme) = iter.next() {
12786            let is_whitespace = is_grapheme_whitespace(first_grapheme);
12787            offset += first_grapheme.len();
12788            graphemes += 1;
12789            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
12790                if let Some(grapheme) = iter.peek().copied() {
12791                    if should_stay_with_preceding_ideograph(grapheme) {
12792                        offset += grapheme.len();
12793                        graphemes += 1;
12794                    }
12795                }
12796            } else {
12797                let mut words = self.input[offset..].split_word_bound_indices().peekable();
12798                let mut next_word_bound = words.peek().copied();
12799                if next_word_bound.map_or(false, |(i, _)| i == 0) {
12800                    next_word_bound = words.next();
12801                }
12802                while let Some(grapheme) = iter.peek().copied() {
12803                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
12804                        break;
12805                    };
12806                    if is_grapheme_whitespace(grapheme) != is_whitespace {
12807                        break;
12808                    };
12809                    offset += grapheme.len();
12810                    graphemes += 1;
12811                    iter.next();
12812                }
12813            }
12814            let token = &self.input[..offset];
12815            self.input = &self.input[offset..];
12816            if is_whitespace {
12817                Some(WordBreakToken {
12818                    token: " ",
12819                    grapheme_len: 1,
12820                    is_whitespace: true,
12821                })
12822            } else {
12823                Some(WordBreakToken {
12824                    token,
12825                    grapheme_len: graphemes,
12826                    is_whitespace: false,
12827                })
12828            }
12829        } else {
12830            None
12831        }
12832    }
12833}
12834
12835#[test]
12836fn test_word_breaking_tokenizer() {
12837    let tests: &[(&str, &[(&str, usize, bool)])] = &[
12838        ("", &[]),
12839        ("  ", &[(" ", 1, true)]),
12840        ("Ʒ", &[("Ʒ", 1, false)]),
12841        ("Ǽ", &[("Ǽ", 1, false)]),
12842        ("", &[("", 1, false)]),
12843        ("⋑⋑", &[("⋑⋑", 2, false)]),
12844        (
12845            "原理,进而",
12846            &[
12847                ("", 1, false),
12848                ("理,", 2, false),
12849                ("", 1, false),
12850                ("", 1, false),
12851            ],
12852        ),
12853        (
12854            "hello world",
12855            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
12856        ),
12857        (
12858            "hello, world",
12859            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
12860        ),
12861        (
12862            "  hello world",
12863            &[
12864                (" ", 1, true),
12865                ("hello", 5, false),
12866                (" ", 1, true),
12867                ("world", 5, false),
12868            ],
12869        ),
12870        (
12871            "这是什么 \n 钢笔",
12872            &[
12873                ("", 1, false),
12874                ("", 1, false),
12875                ("", 1, false),
12876                ("", 1, false),
12877                (" ", 1, true),
12878                ("", 1, false),
12879                ("", 1, false),
12880            ],
12881        ),
12882        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
12883    ];
12884
12885    for (input, result) in tests {
12886        assert_eq!(
12887            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
12888            result
12889                .iter()
12890                .copied()
12891                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
12892                    token,
12893                    grapheme_len,
12894                    is_whitespace,
12895                })
12896                .collect::<Vec<_>>()
12897        );
12898    }
12899}
12900
12901fn wrap_with_prefix(
12902    line_prefix: String,
12903    unwrapped_text: String,
12904    wrap_column: usize,
12905    tab_size: NonZeroU32,
12906) -> String {
12907    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
12908    let mut wrapped_text = String::new();
12909    let mut current_line = line_prefix.clone();
12910
12911    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
12912    let mut current_line_len = line_prefix_len;
12913    for WordBreakToken {
12914        token,
12915        grapheme_len,
12916        is_whitespace,
12917    } in tokenizer
12918    {
12919        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
12920            wrapped_text.push_str(current_line.trim_end());
12921            wrapped_text.push('\n');
12922            current_line.truncate(line_prefix.len());
12923            current_line_len = line_prefix_len;
12924            if !is_whitespace {
12925                current_line.push_str(token);
12926                current_line_len += grapheme_len;
12927            }
12928        } else if !is_whitespace {
12929            current_line.push_str(token);
12930            current_line_len += grapheme_len;
12931        } else if current_line_len != line_prefix_len {
12932            current_line.push(' ');
12933            current_line_len += 1;
12934        }
12935    }
12936
12937    if !current_line.is_empty() {
12938        wrapped_text.push_str(&current_line);
12939    }
12940    wrapped_text
12941}
12942
12943#[test]
12944fn test_wrap_with_prefix() {
12945    assert_eq!(
12946        wrap_with_prefix(
12947            "# ".to_string(),
12948            "abcdefg".to_string(),
12949            4,
12950            NonZeroU32::new(4).unwrap()
12951        ),
12952        "# abcdefg"
12953    );
12954    assert_eq!(
12955        wrap_with_prefix(
12956            "".to_string(),
12957            "\thello world".to_string(),
12958            8,
12959            NonZeroU32::new(4).unwrap()
12960        ),
12961        "hello\nworld"
12962    );
12963    assert_eq!(
12964        wrap_with_prefix(
12965            "// ".to_string(),
12966            "xx \nyy zz aa bb cc".to_string(),
12967            12,
12968            NonZeroU32::new(4).unwrap()
12969        ),
12970        "// xx yy zz\n// aa bb cc"
12971    );
12972    assert_eq!(
12973        wrap_with_prefix(
12974            String::new(),
12975            "这是什么 \n 钢笔".to_string(),
12976            3,
12977            NonZeroU32::new(4).unwrap()
12978        ),
12979        "这是什\n么 钢\n"
12980    );
12981}
12982
12983fn hunks_for_selections(
12984    snapshot: &EditorSnapshot,
12985    selections: &[Selection<Point>],
12986) -> Vec<MultiBufferDiffHunk> {
12987    hunks_for_ranges(
12988        selections.iter().map(|selection| selection.range()),
12989        snapshot,
12990    )
12991}
12992
12993pub fn hunks_for_ranges(
12994    ranges: impl Iterator<Item = Range<Point>>,
12995    snapshot: &EditorSnapshot,
12996) -> Vec<MultiBufferDiffHunk> {
12997    let mut hunks = Vec::new();
12998    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12999        HashMap::default();
13000    for query_range in ranges {
13001        let query_rows =
13002            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13003        for hunk in snapshot.diff_map.diff_hunks_in_range(
13004            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13005            &snapshot.buffer_snapshot,
13006        ) {
13007            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13008            // when the caret is just above or just below the deleted hunk.
13009            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13010            let related_to_selection = if allow_adjacent {
13011                hunk.row_range.overlaps(&query_rows)
13012                    || hunk.row_range.start == query_rows.end
13013                    || hunk.row_range.end == query_rows.start
13014            } else {
13015                hunk.row_range.overlaps(&query_rows)
13016            };
13017            if related_to_selection {
13018                if !processed_buffer_rows
13019                    .entry(hunk.buffer_id)
13020                    .or_default()
13021                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13022                {
13023                    continue;
13024                }
13025                hunks.push(hunk);
13026            }
13027        }
13028    }
13029
13030    hunks
13031}
13032
13033pub trait CollaborationHub {
13034    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13035    fn user_participant_indices<'a>(
13036        &self,
13037        cx: &'a AppContext,
13038    ) -> &'a HashMap<u64, ParticipantIndex>;
13039    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13040}
13041
13042impl CollaborationHub for Model<Project> {
13043    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13044        self.read(cx).collaborators()
13045    }
13046
13047    fn user_participant_indices<'a>(
13048        &self,
13049        cx: &'a AppContext,
13050    ) -> &'a HashMap<u64, ParticipantIndex> {
13051        self.read(cx).user_store().read(cx).participant_indices()
13052    }
13053
13054    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13055        let this = self.read(cx);
13056        let user_ids = this.collaborators().values().map(|c| c.user_id);
13057        this.user_store().read_with(cx, |user_store, cx| {
13058            user_store.participant_names(user_ids, cx)
13059        })
13060    }
13061}
13062
13063pub trait SemanticsProvider {
13064    fn hover(
13065        &self,
13066        buffer: &Model<Buffer>,
13067        position: text::Anchor,
13068        cx: &mut AppContext,
13069    ) -> Option<Task<Vec<project::Hover>>>;
13070
13071    fn inlay_hints(
13072        &self,
13073        buffer_handle: Model<Buffer>,
13074        range: Range<text::Anchor>,
13075        cx: &mut AppContext,
13076    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13077
13078    fn resolve_inlay_hint(
13079        &self,
13080        hint: InlayHint,
13081        buffer_handle: Model<Buffer>,
13082        server_id: LanguageServerId,
13083        cx: &mut AppContext,
13084    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13085
13086    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13087
13088    fn document_highlights(
13089        &self,
13090        buffer: &Model<Buffer>,
13091        position: text::Anchor,
13092        cx: &mut AppContext,
13093    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13094
13095    fn definitions(
13096        &self,
13097        buffer: &Model<Buffer>,
13098        position: text::Anchor,
13099        kind: GotoDefinitionKind,
13100        cx: &mut AppContext,
13101    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13102
13103    fn range_for_rename(
13104        &self,
13105        buffer: &Model<Buffer>,
13106        position: text::Anchor,
13107        cx: &mut AppContext,
13108    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13109
13110    fn perform_rename(
13111        &self,
13112        buffer: &Model<Buffer>,
13113        position: text::Anchor,
13114        new_name: String,
13115        cx: &mut AppContext,
13116    ) -> Option<Task<Result<ProjectTransaction>>>;
13117}
13118
13119pub trait CompletionProvider {
13120    fn completions(
13121        &self,
13122        buffer: &Model<Buffer>,
13123        buffer_position: text::Anchor,
13124        trigger: CompletionContext,
13125        cx: &mut ViewContext<Editor>,
13126    ) -> Task<Result<Vec<Completion>>>;
13127
13128    fn resolve_completions(
13129        &self,
13130        buffer: Model<Buffer>,
13131        completion_indices: Vec<usize>,
13132        completions: Arc<RwLock<Box<[Completion]>>>,
13133        cx: &mut ViewContext<Editor>,
13134    ) -> Task<Result<bool>>;
13135
13136    fn apply_additional_edits_for_completion(
13137        &self,
13138        buffer: Model<Buffer>,
13139        completion: Completion,
13140        push_to_history: bool,
13141        cx: &mut ViewContext<Editor>,
13142    ) -> Task<Result<Option<language::Transaction>>>;
13143
13144    fn is_completion_trigger(
13145        &self,
13146        buffer: &Model<Buffer>,
13147        position: language::Anchor,
13148        text: &str,
13149        trigger_in_words: bool,
13150        cx: &mut ViewContext<Editor>,
13151    ) -> bool;
13152
13153    fn sort_completions(&self) -> bool {
13154        true
13155    }
13156}
13157
13158pub trait CodeActionProvider {
13159    fn code_actions(
13160        &self,
13161        buffer: &Model<Buffer>,
13162        range: Range<text::Anchor>,
13163        cx: &mut WindowContext,
13164    ) -> Task<Result<Vec<CodeAction>>>;
13165
13166    fn apply_code_action(
13167        &self,
13168        buffer_handle: Model<Buffer>,
13169        action: CodeAction,
13170        excerpt_id: ExcerptId,
13171        push_to_history: bool,
13172        cx: &mut WindowContext,
13173    ) -> Task<Result<ProjectTransaction>>;
13174}
13175
13176impl CodeActionProvider for Model<Project> {
13177    fn code_actions(
13178        &self,
13179        buffer: &Model<Buffer>,
13180        range: Range<text::Anchor>,
13181        cx: &mut WindowContext,
13182    ) -> Task<Result<Vec<CodeAction>>> {
13183        self.update(cx, |project, cx| {
13184            project.code_actions(buffer, range, None, cx)
13185        })
13186    }
13187
13188    fn apply_code_action(
13189        &self,
13190        buffer_handle: Model<Buffer>,
13191        action: CodeAction,
13192        _excerpt_id: ExcerptId,
13193        push_to_history: bool,
13194        cx: &mut WindowContext,
13195    ) -> Task<Result<ProjectTransaction>> {
13196        self.update(cx, |project, cx| {
13197            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13198        })
13199    }
13200}
13201
13202fn snippet_completions(
13203    project: &Project,
13204    buffer: &Model<Buffer>,
13205    buffer_position: text::Anchor,
13206    cx: &mut AppContext,
13207) -> Task<Result<Vec<Completion>>> {
13208    let language = buffer.read(cx).language_at(buffer_position);
13209    let language_name = language.as_ref().map(|language| language.lsp_id());
13210    let snippet_store = project.snippets().read(cx);
13211    let snippets = snippet_store.snippets_for(language_name, cx);
13212
13213    if snippets.is_empty() {
13214        return Task::ready(Ok(vec![]));
13215    }
13216    let snapshot = buffer.read(cx).text_snapshot();
13217    let chars: String = snapshot
13218        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13219        .collect();
13220
13221    let scope = language.map(|language| language.default_scope());
13222    let executor = cx.background_executor().clone();
13223
13224    cx.background_executor().spawn(async move {
13225        let classifier = CharClassifier::new(scope).for_completion(true);
13226        let mut last_word = chars
13227            .chars()
13228            .take_while(|c| classifier.is_word(*c))
13229            .collect::<String>();
13230        last_word = last_word.chars().rev().collect();
13231
13232        if last_word.is_empty() {
13233            return Ok(vec![]);
13234        }
13235
13236        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13237        let to_lsp = |point: &text::Anchor| {
13238            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13239            point_to_lsp(end)
13240        };
13241        let lsp_end = to_lsp(&buffer_position);
13242
13243        let candidates = snippets
13244            .iter()
13245            .enumerate()
13246            .flat_map(|(ix, snippet)| {
13247                snippet
13248                    .prefix
13249                    .iter()
13250                    .map(move |prefix| StringMatchCandidate::new(ix, prefix.clone()))
13251            })
13252            .collect::<Vec<StringMatchCandidate>>();
13253
13254        let mut matches = fuzzy::match_strings(
13255            &candidates,
13256            &last_word,
13257            last_word.chars().any(|c| c.is_uppercase()),
13258            100,
13259            &Default::default(),
13260            executor,
13261        )
13262        .await;
13263
13264        // Remove all candidates where the query's start does not match the start of any word in the candidate
13265        if let Some(query_start) = last_word.chars().next() {
13266            matches.retain(|string_match| {
13267                split_words(&string_match.string).any(|word| {
13268                    // Check that the first codepoint of the word as lowercase matches the first
13269                    // codepoint of the query as lowercase
13270                    word.chars()
13271                        .flat_map(|codepoint| codepoint.to_lowercase())
13272                        .zip(query_start.to_lowercase())
13273                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13274                })
13275            });
13276        }
13277
13278        let matched_strings = matches
13279            .into_iter()
13280            .map(|m| m.string)
13281            .collect::<HashSet<_>>();
13282
13283        let result: Vec<Completion> = snippets
13284            .into_iter()
13285            .filter_map(|snippet| {
13286                let matching_prefix = snippet
13287                    .prefix
13288                    .iter()
13289                    .find(|prefix| matched_strings.contains(*prefix))?;
13290                let start = as_offset - last_word.len();
13291                let start = snapshot.anchor_before(start);
13292                let range = start..buffer_position;
13293                let lsp_start = to_lsp(&start);
13294                let lsp_range = lsp::Range {
13295                    start: lsp_start,
13296                    end: lsp_end,
13297                };
13298                Some(Completion {
13299                    old_range: range,
13300                    new_text: snippet.body.clone(),
13301                    label: CodeLabel {
13302                        text: matching_prefix.clone(),
13303                        runs: vec![],
13304                        filter_range: 0..matching_prefix.len(),
13305                    },
13306                    server_id: LanguageServerId(usize::MAX),
13307                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13308                    lsp_completion: lsp::CompletionItem {
13309                        label: snippet.prefix.first().unwrap().clone(),
13310                        kind: Some(CompletionItemKind::SNIPPET),
13311                        label_details: snippet.description.as_ref().map(|description| {
13312                            lsp::CompletionItemLabelDetails {
13313                                detail: Some(description.clone()),
13314                                description: None,
13315                            }
13316                        }),
13317                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13318                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13319                            lsp::InsertReplaceEdit {
13320                                new_text: snippet.body.clone(),
13321                                insert: lsp_range,
13322                                replace: lsp_range,
13323                            },
13324                        )),
13325                        filter_text: Some(snippet.body.clone()),
13326                        sort_text: Some(char::MAX.to_string()),
13327                        ..Default::default()
13328                    },
13329                    confirm: None,
13330                })
13331            })
13332            .collect();
13333
13334        Ok(result)
13335    })
13336}
13337
13338impl CompletionProvider for Model<Project> {
13339    fn completions(
13340        &self,
13341        buffer: &Model<Buffer>,
13342        buffer_position: text::Anchor,
13343        options: CompletionContext,
13344        cx: &mut ViewContext<Editor>,
13345    ) -> Task<Result<Vec<Completion>>> {
13346        self.update(cx, |project, cx| {
13347            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13348            let project_completions = project.completions(buffer, buffer_position, options, cx);
13349            cx.background_executor().spawn(async move {
13350                let mut completions = project_completions.await?;
13351                let snippets_completions = snippets.await?;
13352                completions.extend(snippets_completions);
13353                Ok(completions)
13354            })
13355        })
13356    }
13357
13358    fn resolve_completions(
13359        &self,
13360        buffer: Model<Buffer>,
13361        completion_indices: Vec<usize>,
13362        completions: Arc<RwLock<Box<[Completion]>>>,
13363        cx: &mut ViewContext<Editor>,
13364    ) -> Task<Result<bool>> {
13365        self.update(cx, |project, cx| {
13366            project.resolve_completions(buffer, completion_indices, completions, cx)
13367        })
13368    }
13369
13370    fn apply_additional_edits_for_completion(
13371        &self,
13372        buffer: Model<Buffer>,
13373        completion: Completion,
13374        push_to_history: bool,
13375        cx: &mut ViewContext<Editor>,
13376    ) -> Task<Result<Option<language::Transaction>>> {
13377        self.update(cx, |project, cx| {
13378            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13379        })
13380    }
13381
13382    fn is_completion_trigger(
13383        &self,
13384        buffer: &Model<Buffer>,
13385        position: language::Anchor,
13386        text: &str,
13387        trigger_in_words: bool,
13388        cx: &mut ViewContext<Editor>,
13389    ) -> bool {
13390        let mut chars = text.chars();
13391        let char = if let Some(char) = chars.next() {
13392            char
13393        } else {
13394            return false;
13395        };
13396        if chars.next().is_some() {
13397            return false;
13398        }
13399
13400        let buffer = buffer.read(cx);
13401        let snapshot = buffer.snapshot();
13402        if !snapshot.settings_at(position, cx).show_completions_on_input {
13403            return false;
13404        }
13405        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13406        if trigger_in_words && classifier.is_word(char) {
13407            return true;
13408        }
13409
13410        buffer.completion_triggers().contains(text)
13411    }
13412}
13413
13414impl SemanticsProvider for Model<Project> {
13415    fn hover(
13416        &self,
13417        buffer: &Model<Buffer>,
13418        position: text::Anchor,
13419        cx: &mut AppContext,
13420    ) -> Option<Task<Vec<project::Hover>>> {
13421        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13422    }
13423
13424    fn document_highlights(
13425        &self,
13426        buffer: &Model<Buffer>,
13427        position: text::Anchor,
13428        cx: &mut AppContext,
13429    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13430        Some(self.update(cx, |project, cx| {
13431            project.document_highlights(buffer, position, cx)
13432        }))
13433    }
13434
13435    fn definitions(
13436        &self,
13437        buffer: &Model<Buffer>,
13438        position: text::Anchor,
13439        kind: GotoDefinitionKind,
13440        cx: &mut AppContext,
13441    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13442        Some(self.update(cx, |project, cx| match kind {
13443            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13444            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13445            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13446            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13447        }))
13448    }
13449
13450    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13451        // TODO: make this work for remote projects
13452        self.read(cx)
13453            .language_servers_for_local_buffer(buffer.read(cx), cx)
13454            .any(
13455                |(_, server)| match server.capabilities().inlay_hint_provider {
13456                    Some(lsp::OneOf::Left(enabled)) => enabled,
13457                    Some(lsp::OneOf::Right(_)) => true,
13458                    None => false,
13459                },
13460            )
13461    }
13462
13463    fn inlay_hints(
13464        &self,
13465        buffer_handle: Model<Buffer>,
13466        range: Range<text::Anchor>,
13467        cx: &mut AppContext,
13468    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13469        Some(self.update(cx, |project, cx| {
13470            project.inlay_hints(buffer_handle, range, cx)
13471        }))
13472    }
13473
13474    fn resolve_inlay_hint(
13475        &self,
13476        hint: InlayHint,
13477        buffer_handle: Model<Buffer>,
13478        server_id: LanguageServerId,
13479        cx: &mut AppContext,
13480    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13481        Some(self.update(cx, |project, cx| {
13482            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13483        }))
13484    }
13485
13486    fn range_for_rename(
13487        &self,
13488        buffer: &Model<Buffer>,
13489        position: text::Anchor,
13490        cx: &mut AppContext,
13491    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13492        Some(self.update(cx, |project, cx| {
13493            project.prepare_rename(buffer.clone(), position, cx)
13494        }))
13495    }
13496
13497    fn perform_rename(
13498        &self,
13499        buffer: &Model<Buffer>,
13500        position: text::Anchor,
13501        new_name: String,
13502        cx: &mut AppContext,
13503    ) -> Option<Task<Result<ProjectTransaction>>> {
13504        Some(self.update(cx, |project, cx| {
13505            project.perform_rename(buffer.clone(), position, new_name, cx)
13506        }))
13507    }
13508}
13509
13510fn inlay_hint_settings(
13511    location: Anchor,
13512    snapshot: &MultiBufferSnapshot,
13513    cx: &mut ViewContext<'_, Editor>,
13514) -> InlayHintSettings {
13515    let file = snapshot.file_at(location);
13516    let language = snapshot.language_at(location).map(|l| l.name());
13517    language_settings(language, file, cx).inlay_hints
13518}
13519
13520fn consume_contiguous_rows(
13521    contiguous_row_selections: &mut Vec<Selection<Point>>,
13522    selection: &Selection<Point>,
13523    display_map: &DisplaySnapshot,
13524    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13525) -> (MultiBufferRow, MultiBufferRow) {
13526    contiguous_row_selections.push(selection.clone());
13527    let start_row = MultiBufferRow(selection.start.row);
13528    let mut end_row = ending_row(selection, display_map);
13529
13530    while let Some(next_selection) = selections.peek() {
13531        if next_selection.start.row <= end_row.0 {
13532            end_row = ending_row(next_selection, display_map);
13533            contiguous_row_selections.push(selections.next().unwrap().clone());
13534        } else {
13535            break;
13536        }
13537    }
13538    (start_row, end_row)
13539}
13540
13541fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13542    if next_selection.end.column > 0 || next_selection.is_empty() {
13543        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13544    } else {
13545        MultiBufferRow(next_selection.end.row)
13546    }
13547}
13548
13549impl EditorSnapshot {
13550    pub fn remote_selections_in_range<'a>(
13551        &'a self,
13552        range: &'a Range<Anchor>,
13553        collaboration_hub: &dyn CollaborationHub,
13554        cx: &'a AppContext,
13555    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13556        let participant_names = collaboration_hub.user_names(cx);
13557        let participant_indices = collaboration_hub.user_participant_indices(cx);
13558        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13559        let collaborators_by_replica_id = collaborators_by_peer_id
13560            .iter()
13561            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13562            .collect::<HashMap<_, _>>();
13563        self.buffer_snapshot
13564            .selections_in_range(range, false)
13565            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13566                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13567                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13568                let user_name = participant_names.get(&collaborator.user_id).cloned();
13569                Some(RemoteSelection {
13570                    replica_id,
13571                    selection,
13572                    cursor_shape,
13573                    line_mode,
13574                    participant_index,
13575                    peer_id: collaborator.peer_id,
13576                    user_name,
13577                })
13578            })
13579    }
13580
13581    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13582        self.display_snapshot.buffer_snapshot.language_at(position)
13583    }
13584
13585    pub fn is_focused(&self) -> bool {
13586        self.is_focused
13587    }
13588
13589    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13590        self.placeholder_text.as_ref()
13591    }
13592
13593    pub fn scroll_position(&self) -> gpui::Point<f32> {
13594        self.scroll_anchor.scroll_position(&self.display_snapshot)
13595    }
13596
13597    fn gutter_dimensions(
13598        &self,
13599        font_id: FontId,
13600        font_size: Pixels,
13601        em_width: Pixels,
13602        em_advance: Pixels,
13603        max_line_number_width: Pixels,
13604        cx: &AppContext,
13605    ) -> GutterDimensions {
13606        if !self.show_gutter {
13607            return GutterDimensions::default();
13608        }
13609        let descent = cx.text_system().descent(font_id, font_size);
13610
13611        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13612            matches!(
13613                ProjectSettings::get_global(cx).git.git_gutter,
13614                Some(GitGutterSetting::TrackedFiles)
13615            )
13616        });
13617        let gutter_settings = EditorSettings::get_global(cx).gutter;
13618        let show_line_numbers = self
13619            .show_line_numbers
13620            .unwrap_or(gutter_settings.line_numbers);
13621        let line_gutter_width = if show_line_numbers {
13622            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13623            let min_width_for_number_on_gutter = em_advance * 4.0;
13624            max_line_number_width.max(min_width_for_number_on_gutter)
13625        } else {
13626            0.0.into()
13627        };
13628
13629        let show_code_actions = self
13630            .show_code_actions
13631            .unwrap_or(gutter_settings.code_actions);
13632
13633        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13634
13635        let git_blame_entries_width =
13636            self.git_blame_gutter_max_author_length
13637                .map(|max_author_length| {
13638                    // Length of the author name, but also space for the commit hash,
13639                    // the spacing and the timestamp.
13640                    let max_char_count = max_author_length
13641                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13642                        + 7 // length of commit sha
13643                        + 14 // length of max relative timestamp ("60 minutes ago")
13644                        + 4; // gaps and margins
13645
13646                    em_advance * max_char_count
13647                });
13648
13649        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13650        left_padding += if show_code_actions || show_runnables {
13651            em_width * 3.0
13652        } else if show_git_gutter && show_line_numbers {
13653            em_width * 2.0
13654        } else if show_git_gutter || show_line_numbers {
13655            em_width
13656        } else {
13657            px(0.)
13658        };
13659
13660        let right_padding = if gutter_settings.folds && show_line_numbers {
13661            em_width * 4.0
13662        } else if gutter_settings.folds {
13663            em_width * 3.0
13664        } else if show_line_numbers {
13665            em_width
13666        } else {
13667            px(0.)
13668        };
13669
13670        GutterDimensions {
13671            left_padding,
13672            right_padding,
13673            width: line_gutter_width + left_padding + right_padding,
13674            margin: -descent,
13675            git_blame_entries_width,
13676        }
13677    }
13678
13679    pub fn render_crease_toggle(
13680        &self,
13681        buffer_row: MultiBufferRow,
13682        row_contains_cursor: bool,
13683        editor: View<Editor>,
13684        cx: &mut WindowContext,
13685    ) -> Option<AnyElement> {
13686        let folded = self.is_line_folded(buffer_row);
13687        let mut is_foldable = false;
13688
13689        if let Some(crease) = self
13690            .crease_snapshot
13691            .query_row(buffer_row, &self.buffer_snapshot)
13692        {
13693            is_foldable = true;
13694            match crease {
13695                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13696                    if let Some(render_toggle) = render_toggle {
13697                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13698                            if folded {
13699                                editor.update(cx, |editor, cx| {
13700                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13701                                });
13702                            } else {
13703                                editor.update(cx, |editor, cx| {
13704                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13705                                });
13706                            }
13707                        });
13708                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13709                    }
13710                }
13711            }
13712        }
13713
13714        is_foldable |= self.starts_indent(buffer_row);
13715
13716        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13717            Some(
13718                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13719                    .selected(folded)
13720                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13721                        if folded {
13722                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13723                        } else {
13724                            this.fold_at(&FoldAt { buffer_row }, cx);
13725                        }
13726                    }))
13727                    .into_any_element(),
13728            )
13729        } else {
13730            None
13731        }
13732    }
13733
13734    pub fn render_crease_trailer(
13735        &self,
13736        buffer_row: MultiBufferRow,
13737        cx: &mut WindowContext,
13738    ) -> Option<AnyElement> {
13739        let folded = self.is_line_folded(buffer_row);
13740        if let Crease::Inline { render_trailer, .. } = self
13741            .crease_snapshot
13742            .query_row(buffer_row, &self.buffer_snapshot)?
13743        {
13744            let render_trailer = render_trailer.as_ref()?;
13745            Some(render_trailer(buffer_row, folded, cx))
13746        } else {
13747            None
13748        }
13749    }
13750}
13751
13752impl Deref for EditorSnapshot {
13753    type Target = DisplaySnapshot;
13754
13755    fn deref(&self) -> &Self::Target {
13756        &self.display_snapshot
13757    }
13758}
13759
13760#[derive(Clone, Debug, PartialEq, Eq)]
13761pub enum EditorEvent {
13762    InputIgnored {
13763        text: Arc<str>,
13764    },
13765    InputHandled {
13766        utf16_range_to_replace: Option<Range<isize>>,
13767        text: Arc<str>,
13768    },
13769    ExcerptsAdded {
13770        buffer: Model<Buffer>,
13771        predecessor: ExcerptId,
13772        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13773    },
13774    ExcerptsRemoved {
13775        ids: Vec<ExcerptId>,
13776    },
13777    ExcerptsEdited {
13778        ids: Vec<ExcerptId>,
13779    },
13780    ExcerptsExpanded {
13781        ids: Vec<ExcerptId>,
13782    },
13783    BufferEdited,
13784    Edited {
13785        transaction_id: clock::Lamport,
13786    },
13787    Reparsed(BufferId),
13788    Focused,
13789    FocusedIn,
13790    Blurred,
13791    DirtyChanged,
13792    Saved,
13793    TitleChanged,
13794    DiffBaseChanged,
13795    SelectionsChanged {
13796        local: bool,
13797    },
13798    ScrollPositionChanged {
13799        local: bool,
13800        autoscroll: bool,
13801    },
13802    Closed,
13803    TransactionUndone {
13804        transaction_id: clock::Lamport,
13805    },
13806    TransactionBegun {
13807        transaction_id: clock::Lamport,
13808    },
13809    Reloaded,
13810    CursorShapeChanged,
13811}
13812
13813impl EventEmitter<EditorEvent> for Editor {}
13814
13815impl FocusableView for Editor {
13816    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13817        self.focus_handle.clone()
13818    }
13819}
13820
13821impl Render for Editor {
13822    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13823        let settings = ThemeSettings::get_global(cx);
13824
13825        let mut text_style = match self.mode {
13826            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13827                color: cx.theme().colors().editor_foreground,
13828                font_family: settings.ui_font.family.clone(),
13829                font_features: settings.ui_font.features.clone(),
13830                font_fallbacks: settings.ui_font.fallbacks.clone(),
13831                font_size: rems(0.875).into(),
13832                font_weight: settings.ui_font.weight,
13833                line_height: relative(settings.buffer_line_height.value()),
13834                ..Default::default()
13835            },
13836            EditorMode::Full => TextStyle {
13837                color: cx.theme().colors().editor_foreground,
13838                font_family: settings.buffer_font.family.clone(),
13839                font_features: settings.buffer_font.features.clone(),
13840                font_fallbacks: settings.buffer_font.fallbacks.clone(),
13841                font_size: settings.buffer_font_size(cx).into(),
13842                font_weight: settings.buffer_font.weight,
13843                line_height: relative(settings.buffer_line_height.value()),
13844                ..Default::default()
13845            },
13846        };
13847        if let Some(text_style_refinement) = &self.text_style_refinement {
13848            text_style.refine(text_style_refinement)
13849        }
13850
13851        let background = match self.mode {
13852            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13853            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13854            EditorMode::Full => cx.theme().colors().editor_background,
13855        };
13856
13857        EditorElement::new(
13858            cx.view(),
13859            EditorStyle {
13860                background,
13861                local_player: cx.theme().players().local(),
13862                text: text_style,
13863                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13864                syntax: cx.theme().syntax().clone(),
13865                status: cx.theme().status().clone(),
13866                inlay_hints_style: make_inlay_hints_style(cx),
13867                suggestions_style: HighlightStyle {
13868                    color: Some(cx.theme().status().predictive),
13869                    ..HighlightStyle::default()
13870                },
13871                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13872            },
13873        )
13874    }
13875}
13876
13877impl ViewInputHandler for Editor {
13878    fn text_for_range(
13879        &mut self,
13880        range_utf16: Range<usize>,
13881        adjusted_range: &mut Option<Range<usize>>,
13882        cx: &mut ViewContext<Self>,
13883    ) -> Option<String> {
13884        let snapshot = self.buffer.read(cx).read(cx);
13885        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
13886        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
13887        if (start.0..end.0) != range_utf16 {
13888            adjusted_range.replace(start.0..end.0);
13889        }
13890        Some(snapshot.text_for_range(start..end).collect())
13891    }
13892
13893    fn selected_text_range(
13894        &mut self,
13895        ignore_disabled_input: bool,
13896        cx: &mut ViewContext<Self>,
13897    ) -> Option<UTF16Selection> {
13898        // Prevent the IME menu from appearing when holding down an alphabetic key
13899        // while input is disabled.
13900        if !ignore_disabled_input && !self.input_enabled {
13901            return None;
13902        }
13903
13904        let selection = self.selections.newest::<OffsetUtf16>(cx);
13905        let range = selection.range();
13906
13907        Some(UTF16Selection {
13908            range: range.start.0..range.end.0,
13909            reversed: selection.reversed,
13910        })
13911    }
13912
13913    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13914        let snapshot = self.buffer.read(cx).read(cx);
13915        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13916        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13917    }
13918
13919    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13920        self.clear_highlights::<InputComposition>(cx);
13921        self.ime_transaction.take();
13922    }
13923
13924    fn replace_text_in_range(
13925        &mut self,
13926        range_utf16: Option<Range<usize>>,
13927        text: &str,
13928        cx: &mut ViewContext<Self>,
13929    ) {
13930        if !self.input_enabled {
13931            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13932            return;
13933        }
13934
13935        self.transact(cx, |this, cx| {
13936            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13937                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13938                Some(this.selection_replacement_ranges(range_utf16, cx))
13939            } else {
13940                this.marked_text_ranges(cx)
13941            };
13942
13943            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13944                let newest_selection_id = this.selections.newest_anchor().id;
13945                this.selections
13946                    .all::<OffsetUtf16>(cx)
13947                    .iter()
13948                    .zip(ranges_to_replace.iter())
13949                    .find_map(|(selection, range)| {
13950                        if selection.id == newest_selection_id {
13951                            Some(
13952                                (range.start.0 as isize - selection.head().0 as isize)
13953                                    ..(range.end.0 as isize - selection.head().0 as isize),
13954                            )
13955                        } else {
13956                            None
13957                        }
13958                    })
13959            });
13960
13961            cx.emit(EditorEvent::InputHandled {
13962                utf16_range_to_replace: range_to_replace,
13963                text: text.into(),
13964            });
13965
13966            if let Some(new_selected_ranges) = new_selected_ranges {
13967                this.change_selections(None, cx, |selections| {
13968                    selections.select_ranges(new_selected_ranges)
13969                });
13970                this.backspace(&Default::default(), cx);
13971            }
13972
13973            this.handle_input(text, cx);
13974        });
13975
13976        if let Some(transaction) = self.ime_transaction {
13977            self.buffer.update(cx, |buffer, cx| {
13978                buffer.group_until_transaction(transaction, cx);
13979            });
13980        }
13981
13982        self.unmark_text(cx);
13983    }
13984
13985    fn replace_and_mark_text_in_range(
13986        &mut self,
13987        range_utf16: Option<Range<usize>>,
13988        text: &str,
13989        new_selected_range_utf16: Option<Range<usize>>,
13990        cx: &mut ViewContext<Self>,
13991    ) {
13992        if !self.input_enabled {
13993            return;
13994        }
13995
13996        let transaction = self.transact(cx, |this, cx| {
13997            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13998                let snapshot = this.buffer.read(cx).read(cx);
13999                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14000                    for marked_range in &mut marked_ranges {
14001                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14002                        marked_range.start.0 += relative_range_utf16.start;
14003                        marked_range.start =
14004                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14005                        marked_range.end =
14006                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14007                    }
14008                }
14009                Some(marked_ranges)
14010            } else if let Some(range_utf16) = range_utf16 {
14011                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14012                Some(this.selection_replacement_ranges(range_utf16, cx))
14013            } else {
14014                None
14015            };
14016
14017            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14018                let newest_selection_id = this.selections.newest_anchor().id;
14019                this.selections
14020                    .all::<OffsetUtf16>(cx)
14021                    .iter()
14022                    .zip(ranges_to_replace.iter())
14023                    .find_map(|(selection, range)| {
14024                        if selection.id == newest_selection_id {
14025                            Some(
14026                                (range.start.0 as isize - selection.head().0 as isize)
14027                                    ..(range.end.0 as isize - selection.head().0 as isize),
14028                            )
14029                        } else {
14030                            None
14031                        }
14032                    })
14033            });
14034
14035            cx.emit(EditorEvent::InputHandled {
14036                utf16_range_to_replace: range_to_replace,
14037                text: text.into(),
14038            });
14039
14040            if let Some(ranges) = ranges_to_replace {
14041                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14042            }
14043
14044            let marked_ranges = {
14045                let snapshot = this.buffer.read(cx).read(cx);
14046                this.selections
14047                    .disjoint_anchors()
14048                    .iter()
14049                    .map(|selection| {
14050                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14051                    })
14052                    .collect::<Vec<_>>()
14053            };
14054
14055            if text.is_empty() {
14056                this.unmark_text(cx);
14057            } else {
14058                this.highlight_text::<InputComposition>(
14059                    marked_ranges.clone(),
14060                    HighlightStyle {
14061                        underline: Some(UnderlineStyle {
14062                            thickness: px(1.),
14063                            color: None,
14064                            wavy: false,
14065                        }),
14066                        ..Default::default()
14067                    },
14068                    cx,
14069                );
14070            }
14071
14072            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14073            let use_autoclose = this.use_autoclose;
14074            let use_auto_surround = this.use_auto_surround;
14075            this.set_use_autoclose(false);
14076            this.set_use_auto_surround(false);
14077            this.handle_input(text, cx);
14078            this.set_use_autoclose(use_autoclose);
14079            this.set_use_auto_surround(use_auto_surround);
14080
14081            if let Some(new_selected_range) = new_selected_range_utf16 {
14082                let snapshot = this.buffer.read(cx).read(cx);
14083                let new_selected_ranges = marked_ranges
14084                    .into_iter()
14085                    .map(|marked_range| {
14086                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14087                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14088                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14089                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14090                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14091                    })
14092                    .collect::<Vec<_>>();
14093
14094                drop(snapshot);
14095                this.change_selections(None, cx, |selections| {
14096                    selections.select_ranges(new_selected_ranges)
14097                });
14098            }
14099        });
14100
14101        self.ime_transaction = self.ime_transaction.or(transaction);
14102        if let Some(transaction) = self.ime_transaction {
14103            self.buffer.update(cx, |buffer, cx| {
14104                buffer.group_until_transaction(transaction, cx);
14105            });
14106        }
14107
14108        if self.text_highlights::<InputComposition>(cx).is_none() {
14109            self.ime_transaction.take();
14110        }
14111    }
14112
14113    fn bounds_for_range(
14114        &mut self,
14115        range_utf16: Range<usize>,
14116        element_bounds: gpui::Bounds<Pixels>,
14117        cx: &mut ViewContext<Self>,
14118    ) -> Option<gpui::Bounds<Pixels>> {
14119        let text_layout_details = self.text_layout_details(cx);
14120        let gpui::Point {
14121            x: em_width,
14122            y: line_height,
14123        } = self.character_size(cx);
14124
14125        let snapshot = self.snapshot(cx);
14126        let scroll_position = snapshot.scroll_position();
14127        let scroll_left = scroll_position.x * em_width;
14128
14129        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14130        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14131            + self.gutter_dimensions.width
14132            + self.gutter_dimensions.margin;
14133        let y = line_height * (start.row().as_f32() - scroll_position.y);
14134
14135        Some(Bounds {
14136            origin: element_bounds.origin + point(x, y),
14137            size: size(em_width, line_height),
14138        })
14139    }
14140}
14141
14142trait SelectionExt {
14143    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14144    fn spanned_rows(
14145        &self,
14146        include_end_if_at_line_start: bool,
14147        map: &DisplaySnapshot,
14148    ) -> Range<MultiBufferRow>;
14149}
14150
14151impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14152    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14153        let start = self
14154            .start
14155            .to_point(&map.buffer_snapshot)
14156            .to_display_point(map);
14157        let end = self
14158            .end
14159            .to_point(&map.buffer_snapshot)
14160            .to_display_point(map);
14161        if self.reversed {
14162            end..start
14163        } else {
14164            start..end
14165        }
14166    }
14167
14168    fn spanned_rows(
14169        &self,
14170        include_end_if_at_line_start: bool,
14171        map: &DisplaySnapshot,
14172    ) -> Range<MultiBufferRow> {
14173        let start = self.start.to_point(&map.buffer_snapshot);
14174        let mut end = self.end.to_point(&map.buffer_snapshot);
14175        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14176            end.row -= 1;
14177        }
14178
14179        let buffer_start = map.prev_line_boundary(start).0;
14180        let buffer_end = map.next_line_boundary(end).0;
14181        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14182    }
14183}
14184
14185impl<T: InvalidationRegion> InvalidationStack<T> {
14186    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14187    where
14188        S: Clone + ToOffset,
14189    {
14190        while let Some(region) = self.last() {
14191            let all_selections_inside_invalidation_ranges =
14192                if selections.len() == region.ranges().len() {
14193                    selections
14194                        .iter()
14195                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14196                        .all(|(selection, invalidation_range)| {
14197                            let head = selection.head().to_offset(buffer);
14198                            invalidation_range.start <= head && invalidation_range.end >= head
14199                        })
14200                } else {
14201                    false
14202                };
14203
14204            if all_selections_inside_invalidation_ranges {
14205                break;
14206            } else {
14207                self.pop();
14208            }
14209        }
14210    }
14211}
14212
14213impl<T> Default for InvalidationStack<T> {
14214    fn default() -> Self {
14215        Self(Default::default())
14216    }
14217}
14218
14219impl<T> Deref for InvalidationStack<T> {
14220    type Target = Vec<T>;
14221
14222    fn deref(&self) -> &Self::Target {
14223        &self.0
14224    }
14225}
14226
14227impl<T> DerefMut for InvalidationStack<T> {
14228    fn deref_mut(&mut self) -> &mut Self::Target {
14229        &mut self.0
14230    }
14231}
14232
14233impl InvalidationRegion for SnippetState {
14234    fn ranges(&self) -> &[Range<Anchor>] {
14235        &self.ranges[self.active_index]
14236    }
14237}
14238
14239pub fn diagnostic_block_renderer(
14240    diagnostic: Diagnostic,
14241    max_message_rows: Option<u8>,
14242    allow_closing: bool,
14243    _is_valid: bool,
14244) -> RenderBlock {
14245    let (text_without_backticks, code_ranges) =
14246        highlight_diagnostic_message(&diagnostic, max_message_rows);
14247
14248    Arc::new(move |cx: &mut BlockContext| {
14249        let group_id: SharedString = cx.block_id.to_string().into();
14250
14251        let mut text_style = cx.text_style().clone();
14252        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14253        let theme_settings = ThemeSettings::get_global(cx);
14254        text_style.font_family = theme_settings.buffer_font.family.clone();
14255        text_style.font_style = theme_settings.buffer_font.style;
14256        text_style.font_features = theme_settings.buffer_font.features.clone();
14257        text_style.font_weight = theme_settings.buffer_font.weight;
14258
14259        let multi_line_diagnostic = diagnostic.message.contains('\n');
14260
14261        let buttons = |diagnostic: &Diagnostic| {
14262            if multi_line_diagnostic {
14263                v_flex()
14264            } else {
14265                h_flex()
14266            }
14267            .when(allow_closing, |div| {
14268                div.children(diagnostic.is_primary.then(|| {
14269                    IconButton::new("close-block", IconName::XCircle)
14270                        .icon_color(Color::Muted)
14271                        .size(ButtonSize::Compact)
14272                        .style(ButtonStyle::Transparent)
14273                        .visible_on_hover(group_id.clone())
14274                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14275                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14276                }))
14277            })
14278            .child(
14279                IconButton::new("copy-block", IconName::Copy)
14280                    .icon_color(Color::Muted)
14281                    .size(ButtonSize::Compact)
14282                    .style(ButtonStyle::Transparent)
14283                    .visible_on_hover(group_id.clone())
14284                    .on_click({
14285                        let message = diagnostic.message.clone();
14286                        move |_click, cx| {
14287                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14288                        }
14289                    })
14290                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14291            )
14292        };
14293
14294        let icon_size = buttons(&diagnostic)
14295            .into_any_element()
14296            .layout_as_root(AvailableSpace::min_size(), cx);
14297
14298        h_flex()
14299            .id(cx.block_id)
14300            .group(group_id.clone())
14301            .relative()
14302            .size_full()
14303            .block_mouse_down()
14304            .pl(cx.gutter_dimensions.width)
14305            .w(cx.max_width - cx.gutter_dimensions.full_width())
14306            .child(
14307                div()
14308                    .flex()
14309                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14310                    .flex_shrink(),
14311            )
14312            .child(buttons(&diagnostic))
14313            .child(div().flex().flex_shrink_0().child(
14314                StyledText::new(text_without_backticks.clone()).with_highlights(
14315                    &text_style,
14316                    code_ranges.iter().map(|range| {
14317                        (
14318                            range.clone(),
14319                            HighlightStyle {
14320                                font_weight: Some(FontWeight::BOLD),
14321                                ..Default::default()
14322                            },
14323                        )
14324                    }),
14325                ),
14326            ))
14327            .into_any_element()
14328    })
14329}
14330
14331pub fn highlight_diagnostic_message(
14332    diagnostic: &Diagnostic,
14333    mut max_message_rows: Option<u8>,
14334) -> (SharedString, Vec<Range<usize>>) {
14335    let mut text_without_backticks = String::new();
14336    let mut code_ranges = Vec::new();
14337
14338    if let Some(source) = &diagnostic.source {
14339        text_without_backticks.push_str(source);
14340        code_ranges.push(0..source.len());
14341        text_without_backticks.push_str(": ");
14342    }
14343
14344    let mut prev_offset = 0;
14345    let mut in_code_block = false;
14346    let has_row_limit = max_message_rows.is_some();
14347    let mut newline_indices = diagnostic
14348        .message
14349        .match_indices('\n')
14350        .filter(|_| has_row_limit)
14351        .map(|(ix, _)| ix)
14352        .fuse()
14353        .peekable();
14354
14355    for (quote_ix, _) in diagnostic
14356        .message
14357        .match_indices('`')
14358        .chain([(diagnostic.message.len(), "")])
14359    {
14360        let mut first_newline_ix = None;
14361        let mut last_newline_ix = None;
14362        while let Some(newline_ix) = newline_indices.peek() {
14363            if *newline_ix < quote_ix {
14364                if first_newline_ix.is_none() {
14365                    first_newline_ix = Some(*newline_ix);
14366                }
14367                last_newline_ix = Some(*newline_ix);
14368
14369                if let Some(rows_left) = &mut max_message_rows {
14370                    if *rows_left == 0 {
14371                        break;
14372                    } else {
14373                        *rows_left -= 1;
14374                    }
14375                }
14376                let _ = newline_indices.next();
14377            } else {
14378                break;
14379            }
14380        }
14381        let prev_len = text_without_backticks.len();
14382        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14383        text_without_backticks.push_str(new_text);
14384        if in_code_block {
14385            code_ranges.push(prev_len..text_without_backticks.len());
14386        }
14387        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14388        in_code_block = !in_code_block;
14389        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14390            text_without_backticks.push_str("...");
14391            break;
14392        }
14393    }
14394
14395    (text_without_backticks.into(), code_ranges)
14396}
14397
14398fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14399    match severity {
14400        DiagnosticSeverity::ERROR => colors.error,
14401        DiagnosticSeverity::WARNING => colors.warning,
14402        DiagnosticSeverity::INFORMATION => colors.info,
14403        DiagnosticSeverity::HINT => colors.info,
14404        _ => colors.ignored,
14405    }
14406}
14407
14408pub fn styled_runs_for_code_label<'a>(
14409    label: &'a CodeLabel,
14410    syntax_theme: &'a theme::SyntaxTheme,
14411) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14412    let fade_out = HighlightStyle {
14413        fade_out: Some(0.35),
14414        ..Default::default()
14415    };
14416
14417    let mut prev_end = label.filter_range.end;
14418    label
14419        .runs
14420        .iter()
14421        .enumerate()
14422        .flat_map(move |(ix, (range, highlight_id))| {
14423            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14424                style
14425            } else {
14426                return Default::default();
14427            };
14428            let mut muted_style = style;
14429            muted_style.highlight(fade_out);
14430
14431            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14432            if range.start >= label.filter_range.end {
14433                if range.start > prev_end {
14434                    runs.push((prev_end..range.start, fade_out));
14435                }
14436                runs.push((range.clone(), muted_style));
14437            } else if range.end <= label.filter_range.end {
14438                runs.push((range.clone(), style));
14439            } else {
14440                runs.push((range.start..label.filter_range.end, style));
14441                runs.push((label.filter_range.end..range.end, muted_style));
14442            }
14443            prev_end = cmp::max(prev_end, range.end);
14444
14445            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14446                runs.push((prev_end..label.text.len(), fade_out));
14447            }
14448
14449            runs
14450        })
14451}
14452
14453pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14454    let mut prev_index = 0;
14455    let mut prev_codepoint: Option<char> = None;
14456    text.char_indices()
14457        .chain([(text.len(), '\0')])
14458        .filter_map(move |(index, codepoint)| {
14459            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14460            let is_boundary = index == text.len()
14461                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14462                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14463            if is_boundary {
14464                let chunk = &text[prev_index..index];
14465                prev_index = index;
14466                Some(chunk)
14467            } else {
14468                None
14469            }
14470        })
14471}
14472
14473pub trait RangeToAnchorExt: Sized {
14474    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14475
14476    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14477        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14478        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14479    }
14480}
14481
14482impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14483    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14484        let start_offset = self.start.to_offset(snapshot);
14485        let end_offset = self.end.to_offset(snapshot);
14486        if start_offset == end_offset {
14487            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14488        } else {
14489            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14490        }
14491    }
14492}
14493
14494pub trait RowExt {
14495    fn as_f32(&self) -> f32;
14496
14497    fn next_row(&self) -> Self;
14498
14499    fn previous_row(&self) -> Self;
14500
14501    fn minus(&self, other: Self) -> u32;
14502}
14503
14504impl RowExt for DisplayRow {
14505    fn as_f32(&self) -> f32 {
14506        self.0 as f32
14507    }
14508
14509    fn next_row(&self) -> Self {
14510        Self(self.0 + 1)
14511    }
14512
14513    fn previous_row(&self) -> Self {
14514        Self(self.0.saturating_sub(1))
14515    }
14516
14517    fn minus(&self, other: Self) -> u32 {
14518        self.0 - other.0
14519    }
14520}
14521
14522impl RowExt for MultiBufferRow {
14523    fn as_f32(&self) -> f32 {
14524        self.0 as f32
14525    }
14526
14527    fn next_row(&self) -> Self {
14528        Self(self.0 + 1)
14529    }
14530
14531    fn previous_row(&self) -> Self {
14532        Self(self.0.saturating_sub(1))
14533    }
14534
14535    fn minus(&self, other: Self) -> u32 {
14536        self.0 - other.0
14537    }
14538}
14539
14540trait RowRangeExt {
14541    type Row;
14542
14543    fn len(&self) -> usize;
14544
14545    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14546}
14547
14548impl RowRangeExt for Range<MultiBufferRow> {
14549    type Row = MultiBufferRow;
14550
14551    fn len(&self) -> usize {
14552        (self.end.0 - self.start.0) as usize
14553    }
14554
14555    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14556        (self.start.0..self.end.0).map(MultiBufferRow)
14557    }
14558}
14559
14560impl RowRangeExt for Range<DisplayRow> {
14561    type Row = DisplayRow;
14562
14563    fn len(&self) -> usize {
14564        (self.end.0 - self.start.0) as usize
14565    }
14566
14567    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14568        (self.start.0..self.end.0).map(DisplayRow)
14569    }
14570}
14571
14572fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14573    if hunk.diff_base_byte_range.is_empty() {
14574        DiffHunkStatus::Added
14575    } else if hunk.row_range.is_empty() {
14576        DiffHunkStatus::Removed
14577    } else {
14578        DiffHunkStatus::Modified
14579    }
14580}
14581
14582/// If select range has more than one line, we
14583/// just point the cursor to range.start.
14584fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14585    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14586        range
14587    } else {
14588        range.start..range.start
14589    }
14590}
14591
14592pub struct KillRing(ClipboardItem);
14593impl Global for KillRing {}
14594
14595const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);