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    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   87    WeakView, WindowContext,
   88};
   89use highlight_matching_bracket::refresh_matching_bracket_highlights;
   90use hover_popover::{hide_hover, HoverState};
   91pub(crate) use hunk_diff::HoveredHunk;
   92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
  103    Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    buffer_store::BufferChangeSet,
  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, find_url_from_range};
  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    InlineCompletion(usize),
  263    Hint(usize),
  264}
  265
  266impl InlayId {
  267    fn id(&self) -> usize {
  268        match self {
  269            Self::InlineCompletion(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 inline_completion_styles: InlineCompletionStyles,
  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            inline_completion_styles: InlineCompletionStyles {
  426                insertion: HighlightStyle::default(),
  427                whitespace: HighlightStyle::default(),
  428            },
  429            unnecessary_code_fade: Default::default(),
  430        }
  431    }
  432}
  433
  434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  435    let show_background = language_settings::language_settings(None, None, cx)
  436        .inlay_hints
  437        .show_background;
  438
  439    HighlightStyle {
  440        color: Some(cx.theme().status().hint),
  441        background_color: show_background.then(|| cx.theme().status().hint_background),
  442        ..HighlightStyle::default()
  443    }
  444}
  445
  446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  447    InlineCompletionStyles {
  448        insertion: HighlightStyle {
  449            color: Some(cx.theme().status().predictive),
  450            ..HighlightStyle::default()
  451        },
  452        whitespace: HighlightStyle {
  453            background_color: Some(cx.theme().status().created_background),
  454            ..HighlightStyle::default()
  455        },
  456    }
  457}
  458
  459type CompletionId = usize;
  460
  461#[derive(Debug, Clone)]
  462struct InlineCompletionMenuHint {
  463    provider_name: &'static str,
  464    text: InlineCompletionText,
  465}
  466
  467#[derive(Clone, Debug)]
  468enum InlineCompletionText {
  469    Move(SharedString),
  470    Edit {
  471        text: SharedString,
  472        highlights: Vec<(Range<usize>, HighlightStyle)>,
  473    },
  474}
  475
  476enum InlineCompletion {
  477    Edit(Vec<(Range<Anchor>, String)>),
  478    Move(Anchor),
  479}
  480
  481struct InlineCompletionState {
  482    inlay_ids: Vec<InlayId>,
  483    completion: InlineCompletion,
  484    invalidation_range: Range<Anchor>,
  485}
  486
  487enum InlineCompletionHighlight {}
  488
  489#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  490struct EditorActionId(usize);
  491
  492impl EditorActionId {
  493    pub fn post_inc(&mut self) -> Self {
  494        let answer = self.0;
  495
  496        *self = Self(answer + 1);
  497
  498        Self(answer)
  499    }
  500}
  501
  502// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  503// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  504
  505type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  506type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  507
  508#[derive(Default)]
  509struct ScrollbarMarkerState {
  510    scrollbar_size: Size<Pixels>,
  511    dirty: bool,
  512    markers: Arc<[PaintQuad]>,
  513    pending_refresh: Option<Task<Result<()>>>,
  514}
  515
  516impl ScrollbarMarkerState {
  517    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  518        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  519    }
  520}
  521
  522#[derive(Clone, Debug)]
  523struct RunnableTasks {
  524    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  525    offset: MultiBufferOffset,
  526    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  527    column: u32,
  528    // Values of all named captures, including those starting with '_'
  529    extra_variables: HashMap<String, String>,
  530    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  531    context_range: Range<BufferOffset>,
  532}
  533
  534impl RunnableTasks {
  535    fn resolve<'a>(
  536        &'a self,
  537        cx: &'a task::TaskContext,
  538    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  539        self.templates.iter().filter_map(|(kind, template)| {
  540            template
  541                .resolve_task(&kind.to_id_base(), cx)
  542                .map(|task| (kind.clone(), task))
  543        })
  544    }
  545}
  546
  547#[derive(Clone)]
  548struct ResolvedTasks {
  549    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  550    position: Anchor,
  551}
  552#[derive(Copy, Clone, Debug)]
  553struct MultiBufferOffset(usize);
  554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  555struct BufferOffset(usize);
  556
  557// Addons allow storing per-editor state in other crates (e.g. Vim)
  558pub trait Addon: 'static {
  559    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  560
  561    fn to_any(&self) -> &dyn std::any::Any;
  562}
  563
  564#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  565pub enum IsVimMode {
  566    Yes,
  567    No,
  568}
  569
  570/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  571///
  572/// See the [module level documentation](self) for more information.
  573pub struct Editor {
  574    focus_handle: FocusHandle,
  575    last_focused_descendant: Option<WeakFocusHandle>,
  576    /// The text buffer being edited
  577    buffer: Model<MultiBuffer>,
  578    /// Map of how text in the buffer should be displayed.
  579    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  580    pub display_map: Model<DisplayMap>,
  581    pub selections: SelectionsCollection,
  582    pub scroll_manager: ScrollManager,
  583    /// When inline assist editors are linked, they all render cursors because
  584    /// typing enters text into each of them, even the ones that aren't focused.
  585    pub(crate) show_cursor_when_unfocused: bool,
  586    columnar_selection_tail: Option<Anchor>,
  587    add_selections_state: Option<AddSelectionsState>,
  588    select_next_state: Option<SelectNextState>,
  589    select_prev_state: Option<SelectNextState>,
  590    selection_history: SelectionHistory,
  591    autoclose_regions: Vec<AutocloseRegion>,
  592    snippet_stack: InvalidationStack<SnippetState>,
  593    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  594    ime_transaction: Option<TransactionId>,
  595    active_diagnostics: Option<ActiveDiagnosticGroup>,
  596    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  597
  598    project: Option<Model<Project>>,
  599    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  600    completion_provider: Option<Box<dyn CompletionProvider>>,
  601    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  602    blink_manager: Model<BlinkManager>,
  603    show_cursor_names: bool,
  604    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  605    pub show_local_selections: bool,
  606    mode: EditorMode,
  607    show_breadcrumbs: bool,
  608    show_gutter: bool,
  609    show_scrollbars: bool,
  610    show_line_numbers: Option<bool>,
  611    use_relative_line_numbers: Option<bool>,
  612    show_git_diff_gutter: Option<bool>,
  613    show_code_actions: Option<bool>,
  614    show_runnables: Option<bool>,
  615    show_wrap_guides: Option<bool>,
  616    show_indent_guides: Option<bool>,
  617    placeholder_text: Option<Arc<str>>,
  618    highlight_order: usize,
  619    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  620    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  621    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  622    scrollbar_marker_state: ScrollbarMarkerState,
  623    active_indent_guides_state: ActiveIndentGuidesState,
  624    nav_history: Option<ItemNavHistory>,
  625    context_menu: RefCell<Option<CodeContextMenu>>,
  626    mouse_context_menu: Option<MouseContextMenu>,
  627    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  628    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  629    signature_help_state: SignatureHelpState,
  630    auto_signature_help: Option<bool>,
  631    find_all_references_task_sources: Vec<Anchor>,
  632    next_completion_id: CompletionId,
  633    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  634    code_actions_task: Option<Task<Result<()>>>,
  635    document_highlights_task: Option<Task<()>>,
  636    linked_editing_range_task: Option<Task<Option<()>>>,
  637    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  638    pending_rename: Option<RenameState>,
  639    searchable: bool,
  640    cursor_shape: CursorShape,
  641    current_line_highlight: Option<CurrentLineHighlight>,
  642    collapse_matches: bool,
  643    autoindent_mode: Option<AutoindentMode>,
  644    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  645    input_enabled: bool,
  646    use_modal_editing: bool,
  647    read_only: bool,
  648    leader_peer_id: Option<PeerId>,
  649    remote_id: Option<ViewId>,
  650    hover_state: HoverState,
  651    gutter_hovered: bool,
  652    hovered_link_state: Option<HoveredLinkState>,
  653    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  654    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  655    active_inline_completion: Option<InlineCompletionState>,
  656    // enable_inline_completions is a switch that Vim can use to disable
  657    // inline completions based on its mode.
  658    enable_inline_completions: bool,
  659    show_inline_completions_override: Option<bool>,
  660    inlay_hint_cache: InlayHintCache,
  661    diff_map: DiffMap,
  662    next_inlay_id: usize,
  663    _subscriptions: Vec<Subscription>,
  664    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  665    gutter_dimensions: GutterDimensions,
  666    style: Option<EditorStyle>,
  667    text_style_refinement: Option<TextStyleRefinement>,
  668    next_editor_action_id: EditorActionId,
  669    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  670    use_autoclose: bool,
  671    use_auto_surround: bool,
  672    auto_replace_emoji_shortcode: bool,
  673    show_git_blame_gutter: bool,
  674    show_git_blame_inline: bool,
  675    show_git_blame_inline_delay_task: Option<Task<()>>,
  676    git_blame_inline_enabled: bool,
  677    serialize_dirty_buffers: bool,
  678    show_selection_menu: Option<bool>,
  679    blame: Option<Model<GitBlame>>,
  680    blame_subscription: Option<Subscription>,
  681    custom_context_menu: Option<
  682        Box<
  683            dyn 'static
  684                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  685        >,
  686    >,
  687    last_bounds: Option<Bounds<Pixels>>,
  688    expect_bounds_change: Option<Bounds<Pixels>>,
  689    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  690    tasks_update_task: Option<Task<()>>,
  691    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  692    breadcrumb_header: Option<String>,
  693    focused_block: Option<FocusedBlock>,
  694    next_scroll_position: NextScrollCursorCenterTopBottom,
  695    addons: HashMap<TypeId, Box<dyn Addon>>,
  696    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  697    toggle_fold_multiple_buffers: Task<()>,
  698    _scroll_cursor_center_top_bottom_task: Task<()>,
  699}
  700
  701#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  702enum NextScrollCursorCenterTopBottom {
  703    #[default]
  704    Center,
  705    Top,
  706    Bottom,
  707}
  708
  709impl NextScrollCursorCenterTopBottom {
  710    fn next(&self) -> Self {
  711        match self {
  712            Self::Center => Self::Top,
  713            Self::Top => Self::Bottom,
  714            Self::Bottom => Self::Center,
  715        }
  716    }
  717}
  718
  719#[derive(Clone)]
  720pub struct EditorSnapshot {
  721    pub mode: EditorMode,
  722    show_gutter: bool,
  723    show_line_numbers: Option<bool>,
  724    show_git_diff_gutter: Option<bool>,
  725    show_code_actions: Option<bool>,
  726    show_runnables: Option<bool>,
  727    git_blame_gutter_max_author_length: Option<usize>,
  728    pub display_snapshot: DisplaySnapshot,
  729    pub placeholder_text: Option<Arc<str>>,
  730    diff_map: DiffMapSnapshot,
  731    is_focused: bool,
  732    scroll_anchor: ScrollAnchor,
  733    ongoing_scroll: OngoingScroll,
  734    current_line_highlight: CurrentLineHighlight,
  735    gutter_hovered: bool,
  736}
  737
  738const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  739
  740#[derive(Default, Debug, Clone, Copy)]
  741pub struct GutterDimensions {
  742    pub left_padding: Pixels,
  743    pub right_padding: Pixels,
  744    pub width: Pixels,
  745    pub margin: Pixels,
  746    pub git_blame_entries_width: Option<Pixels>,
  747}
  748
  749impl GutterDimensions {
  750    /// The full width of the space taken up by the gutter.
  751    pub fn full_width(&self) -> Pixels {
  752        self.margin + self.width
  753    }
  754
  755    /// The width of the space reserved for the fold indicators,
  756    /// use alongside 'justify_end' and `gutter_width` to
  757    /// right align content with the line numbers
  758    pub fn fold_area_width(&self) -> Pixels {
  759        self.margin + self.right_padding
  760    }
  761}
  762
  763#[derive(Debug)]
  764pub struct RemoteSelection {
  765    pub replica_id: ReplicaId,
  766    pub selection: Selection<Anchor>,
  767    pub cursor_shape: CursorShape,
  768    pub peer_id: PeerId,
  769    pub line_mode: bool,
  770    pub participant_index: Option<ParticipantIndex>,
  771    pub user_name: Option<SharedString>,
  772}
  773
  774#[derive(Clone, Debug)]
  775struct SelectionHistoryEntry {
  776    selections: Arc<[Selection<Anchor>]>,
  777    select_next_state: Option<SelectNextState>,
  778    select_prev_state: Option<SelectNextState>,
  779    add_selections_state: Option<AddSelectionsState>,
  780}
  781
  782enum SelectionHistoryMode {
  783    Normal,
  784    Undoing,
  785    Redoing,
  786}
  787
  788#[derive(Clone, PartialEq, Eq, Hash)]
  789struct HoveredCursor {
  790    replica_id: u16,
  791    selection_id: usize,
  792}
  793
  794impl Default for SelectionHistoryMode {
  795    fn default() -> Self {
  796        Self::Normal
  797    }
  798}
  799
  800#[derive(Default)]
  801struct SelectionHistory {
  802    #[allow(clippy::type_complexity)]
  803    selections_by_transaction:
  804        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  805    mode: SelectionHistoryMode,
  806    undo_stack: VecDeque<SelectionHistoryEntry>,
  807    redo_stack: VecDeque<SelectionHistoryEntry>,
  808}
  809
  810impl SelectionHistory {
  811    fn insert_transaction(
  812        &mut self,
  813        transaction_id: TransactionId,
  814        selections: Arc<[Selection<Anchor>]>,
  815    ) {
  816        self.selections_by_transaction
  817            .insert(transaction_id, (selections, None));
  818    }
  819
  820    #[allow(clippy::type_complexity)]
  821    fn transaction(
  822        &self,
  823        transaction_id: TransactionId,
  824    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  825        self.selections_by_transaction.get(&transaction_id)
  826    }
  827
  828    #[allow(clippy::type_complexity)]
  829    fn transaction_mut(
  830        &mut self,
  831        transaction_id: TransactionId,
  832    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  833        self.selections_by_transaction.get_mut(&transaction_id)
  834    }
  835
  836    fn push(&mut self, entry: SelectionHistoryEntry) {
  837        if !entry.selections.is_empty() {
  838            match self.mode {
  839                SelectionHistoryMode::Normal => {
  840                    self.push_undo(entry);
  841                    self.redo_stack.clear();
  842                }
  843                SelectionHistoryMode::Undoing => self.push_redo(entry),
  844                SelectionHistoryMode::Redoing => self.push_undo(entry),
  845            }
  846        }
  847    }
  848
  849    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  850        if self
  851            .undo_stack
  852            .back()
  853            .map_or(true, |e| e.selections != entry.selections)
  854        {
  855            self.undo_stack.push_back(entry);
  856            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  857                self.undo_stack.pop_front();
  858            }
  859        }
  860    }
  861
  862    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  863        if self
  864            .redo_stack
  865            .back()
  866            .map_or(true, |e| e.selections != entry.selections)
  867        {
  868            self.redo_stack.push_back(entry);
  869            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  870                self.redo_stack.pop_front();
  871            }
  872        }
  873    }
  874}
  875
  876struct RowHighlight {
  877    index: usize,
  878    range: Range<Anchor>,
  879    color: Hsla,
  880    should_autoscroll: bool,
  881}
  882
  883#[derive(Clone, Debug)]
  884struct AddSelectionsState {
  885    above: bool,
  886    stack: Vec<usize>,
  887}
  888
  889#[derive(Clone)]
  890struct SelectNextState {
  891    query: AhoCorasick,
  892    wordwise: bool,
  893    done: bool,
  894}
  895
  896impl std::fmt::Debug for SelectNextState {
  897    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  898        f.debug_struct(std::any::type_name::<Self>())
  899            .field("wordwise", &self.wordwise)
  900            .field("done", &self.done)
  901            .finish()
  902    }
  903}
  904
  905#[derive(Debug)]
  906struct AutocloseRegion {
  907    selection_id: usize,
  908    range: Range<Anchor>,
  909    pair: BracketPair,
  910}
  911
  912#[derive(Debug)]
  913struct SnippetState {
  914    ranges: Vec<Vec<Range<Anchor>>>,
  915    active_index: usize,
  916    choices: Vec<Option<Vec<String>>>,
  917}
  918
  919#[doc(hidden)]
  920pub struct RenameState {
  921    pub range: Range<Anchor>,
  922    pub old_name: Arc<str>,
  923    pub editor: View<Editor>,
  924    block_id: CustomBlockId,
  925}
  926
  927struct InvalidationStack<T>(Vec<T>);
  928
  929struct RegisteredInlineCompletionProvider {
  930    provider: Arc<dyn InlineCompletionProviderHandle>,
  931    _subscription: Subscription,
  932}
  933
  934#[derive(Debug)]
  935struct ActiveDiagnosticGroup {
  936    primary_range: Range<Anchor>,
  937    primary_message: String,
  938    group_id: usize,
  939    blocks: HashMap<CustomBlockId, Diagnostic>,
  940    is_valid: bool,
  941}
  942
  943#[derive(Serialize, Deserialize, Clone, Debug)]
  944pub struct ClipboardSelection {
  945    pub len: usize,
  946    pub is_entire_line: bool,
  947    pub first_line_indent: u32,
  948}
  949
  950#[derive(Debug)]
  951pub(crate) struct NavigationData {
  952    cursor_anchor: Anchor,
  953    cursor_position: Point,
  954    scroll_anchor: ScrollAnchor,
  955    scroll_top_row: u32,
  956}
  957
  958#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  959pub enum GotoDefinitionKind {
  960    Symbol,
  961    Declaration,
  962    Type,
  963    Implementation,
  964}
  965
  966#[derive(Debug, Clone)]
  967enum InlayHintRefreshReason {
  968    Toggle(bool),
  969    SettingsChange(InlayHintSettings),
  970    NewLinesShown,
  971    BufferEdited(HashSet<Arc<Language>>),
  972    RefreshRequested,
  973    ExcerptsRemoved(Vec<ExcerptId>),
  974}
  975
  976impl InlayHintRefreshReason {
  977    fn description(&self) -> &'static str {
  978        match self {
  979            Self::Toggle(_) => "toggle",
  980            Self::SettingsChange(_) => "settings change",
  981            Self::NewLinesShown => "new lines shown",
  982            Self::BufferEdited(_) => "buffer edited",
  983            Self::RefreshRequested => "refresh requested",
  984            Self::ExcerptsRemoved(_) => "excerpts removed",
  985        }
  986    }
  987}
  988
  989pub(crate) struct FocusedBlock {
  990    id: BlockId,
  991    focus_handle: WeakFocusHandle,
  992}
  993
  994#[derive(Clone)]
  995struct JumpData {
  996    excerpt_id: ExcerptId,
  997    position: Point,
  998    anchor: text::Anchor,
  999    path: Option<project::ProjectPath>,
 1000    line_offset_from_top: u32,
 1001}
 1002
 1003impl Editor {
 1004    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1005        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1006        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1007        Self::new(
 1008            EditorMode::SingleLine { auto_width: false },
 1009            buffer,
 1010            None,
 1011            false,
 1012            cx,
 1013        )
 1014    }
 1015
 1016    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1017        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1018        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1019        Self::new(EditorMode::Full, buffer, None, false, cx)
 1020    }
 1021
 1022    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1023        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1024        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1025        Self::new(
 1026            EditorMode::SingleLine { auto_width: true },
 1027            buffer,
 1028            None,
 1029            false,
 1030            cx,
 1031        )
 1032    }
 1033
 1034    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1035        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1036        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1037        Self::new(
 1038            EditorMode::AutoHeight { max_lines },
 1039            buffer,
 1040            None,
 1041            false,
 1042            cx,
 1043        )
 1044    }
 1045
 1046    pub fn for_buffer(
 1047        buffer: Model<Buffer>,
 1048        project: Option<Model<Project>>,
 1049        cx: &mut ViewContext<Self>,
 1050    ) -> Self {
 1051        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1052        Self::new(EditorMode::Full, buffer, project, false, cx)
 1053    }
 1054
 1055    pub fn for_multibuffer(
 1056        buffer: Model<MultiBuffer>,
 1057        project: Option<Model<Project>>,
 1058        show_excerpt_controls: bool,
 1059        cx: &mut ViewContext<Self>,
 1060    ) -> Self {
 1061        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1062    }
 1063
 1064    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1065        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1066        let mut clone = Self::new(
 1067            self.mode,
 1068            self.buffer.clone(),
 1069            self.project.clone(),
 1070            show_excerpt_controls,
 1071            cx,
 1072        );
 1073        self.display_map.update(cx, |display_map, cx| {
 1074            let snapshot = display_map.snapshot(cx);
 1075            clone.display_map.update(cx, |display_map, cx| {
 1076                display_map.set_state(&snapshot, cx);
 1077            });
 1078        });
 1079        clone.selections.clone_state(&self.selections);
 1080        clone.scroll_manager.clone_state(&self.scroll_manager);
 1081        clone.searchable = self.searchable;
 1082        clone
 1083    }
 1084
 1085    pub fn new(
 1086        mode: EditorMode,
 1087        buffer: Model<MultiBuffer>,
 1088        project: Option<Model<Project>>,
 1089        show_excerpt_controls: bool,
 1090        cx: &mut ViewContext<Self>,
 1091    ) -> Self {
 1092        let style = cx.text_style();
 1093        let font_size = style.font_size.to_pixels(cx.rem_size());
 1094        let editor = cx.view().downgrade();
 1095        let fold_placeholder = FoldPlaceholder {
 1096            constrain_width: true,
 1097            render: Arc::new(move |fold_id, fold_range, cx| {
 1098                let editor = editor.clone();
 1099                div()
 1100                    .id(fold_id)
 1101                    .bg(cx.theme().colors().ghost_element_background)
 1102                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1103                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1104                    .rounded_sm()
 1105                    .size_full()
 1106                    .cursor_pointer()
 1107                    .child("")
 1108                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1109                    .on_click(move |_, cx| {
 1110                        editor
 1111                            .update(cx, |editor, cx| {
 1112                                editor.unfold_ranges(
 1113                                    &[fold_range.start..fold_range.end],
 1114                                    true,
 1115                                    false,
 1116                                    cx,
 1117                                );
 1118                                cx.stop_propagation();
 1119                            })
 1120                            .ok();
 1121                    })
 1122                    .into_any()
 1123            }),
 1124            merge_adjacent: true,
 1125            ..Default::default()
 1126        };
 1127        let display_map = cx.new_model(|cx| {
 1128            DisplayMap::new(
 1129                buffer.clone(),
 1130                style.font(),
 1131                font_size,
 1132                None,
 1133                show_excerpt_controls,
 1134                FILE_HEADER_HEIGHT,
 1135                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1136                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1137                fold_placeholder,
 1138                cx,
 1139            )
 1140        });
 1141
 1142        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1143
 1144        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1145
 1146        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1147            .then(|| language_settings::SoftWrap::None);
 1148
 1149        let mut project_subscriptions = Vec::new();
 1150        if mode == EditorMode::Full {
 1151            if let Some(project) = project.as_ref() {
 1152                if buffer.read(cx).is_singleton() {
 1153                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1154                        cx.emit(EditorEvent::TitleChanged);
 1155                    }));
 1156                }
 1157                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1158                    if let project::Event::RefreshInlayHints = event {
 1159                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1160                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1161                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1162                            let focus_handle = editor.focus_handle(cx);
 1163                            if focus_handle.is_focused(cx) {
 1164                                let snapshot = buffer.read(cx).snapshot();
 1165                                for (range, snippet) in snippet_edits {
 1166                                    let editor_range =
 1167                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1168                                    editor
 1169                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1170                                        .ok();
 1171                                }
 1172                            }
 1173                        }
 1174                    }
 1175                }));
 1176                if let Some(task_inventory) = project
 1177                    .read(cx)
 1178                    .task_store()
 1179                    .read(cx)
 1180                    .task_inventory()
 1181                    .cloned()
 1182                {
 1183                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1184                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1185                    }));
 1186                }
 1187            }
 1188        }
 1189
 1190        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1191
 1192        let inlay_hint_settings =
 1193            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1194        let focus_handle = cx.focus_handle();
 1195        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1196        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1197            .detach();
 1198        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1199            .detach();
 1200        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1201
 1202        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1203            Some(false)
 1204        } else {
 1205            None
 1206        };
 1207
 1208        let mut code_action_providers = Vec::new();
 1209        if let Some(project) = project.clone() {
 1210            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1211            code_action_providers.push(Rc::new(project) as Rc<_>);
 1212        }
 1213
 1214        let mut this = Self {
 1215            focus_handle,
 1216            show_cursor_when_unfocused: false,
 1217            last_focused_descendant: None,
 1218            buffer: buffer.clone(),
 1219            display_map: display_map.clone(),
 1220            selections,
 1221            scroll_manager: ScrollManager::new(cx),
 1222            columnar_selection_tail: None,
 1223            add_selections_state: None,
 1224            select_next_state: None,
 1225            select_prev_state: None,
 1226            selection_history: Default::default(),
 1227            autoclose_regions: Default::default(),
 1228            snippet_stack: Default::default(),
 1229            select_larger_syntax_node_stack: Vec::new(),
 1230            ime_transaction: Default::default(),
 1231            active_diagnostics: None,
 1232            soft_wrap_mode_override,
 1233            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1234            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1235            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1236            project,
 1237            blink_manager: blink_manager.clone(),
 1238            show_local_selections: true,
 1239            show_scrollbars: true,
 1240            mode,
 1241            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1242            show_gutter: mode == EditorMode::Full,
 1243            show_line_numbers: None,
 1244            use_relative_line_numbers: None,
 1245            show_git_diff_gutter: None,
 1246            show_code_actions: None,
 1247            show_runnables: None,
 1248            show_wrap_guides: None,
 1249            show_indent_guides,
 1250            placeholder_text: None,
 1251            highlight_order: 0,
 1252            highlighted_rows: HashMap::default(),
 1253            background_highlights: Default::default(),
 1254            gutter_highlights: TreeMap::default(),
 1255            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1256            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1257            nav_history: None,
 1258            context_menu: RefCell::new(None),
 1259            mouse_context_menu: None,
 1260            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1261            completion_tasks: Default::default(),
 1262            signature_help_state: SignatureHelpState::default(),
 1263            auto_signature_help: None,
 1264            find_all_references_task_sources: Vec::new(),
 1265            next_completion_id: 0,
 1266            next_inlay_id: 0,
 1267            code_action_providers,
 1268            available_code_actions: Default::default(),
 1269            code_actions_task: Default::default(),
 1270            document_highlights_task: Default::default(),
 1271            linked_editing_range_task: Default::default(),
 1272            pending_rename: Default::default(),
 1273            searchable: true,
 1274            cursor_shape: EditorSettings::get_global(cx)
 1275                .cursor_shape
 1276                .unwrap_or_default(),
 1277            current_line_highlight: None,
 1278            autoindent_mode: Some(AutoindentMode::EachLine),
 1279            collapse_matches: false,
 1280            workspace: None,
 1281            input_enabled: true,
 1282            use_modal_editing: mode == EditorMode::Full,
 1283            read_only: false,
 1284            use_autoclose: true,
 1285            use_auto_surround: true,
 1286            auto_replace_emoji_shortcode: false,
 1287            leader_peer_id: None,
 1288            remote_id: None,
 1289            hover_state: Default::default(),
 1290            hovered_link_state: Default::default(),
 1291            inline_completion_provider: None,
 1292            active_inline_completion: None,
 1293            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1294            diff_map: DiffMap::default(),
 1295            gutter_hovered: false,
 1296            pixel_position_of_newest_cursor: None,
 1297            last_bounds: None,
 1298            expect_bounds_change: None,
 1299            gutter_dimensions: GutterDimensions::default(),
 1300            style: None,
 1301            show_cursor_names: false,
 1302            hovered_cursors: Default::default(),
 1303            next_editor_action_id: EditorActionId::default(),
 1304            editor_actions: Rc::default(),
 1305            show_inline_completions_override: None,
 1306            enable_inline_completions: true,
 1307            custom_context_menu: None,
 1308            show_git_blame_gutter: false,
 1309            show_git_blame_inline: false,
 1310            show_selection_menu: None,
 1311            show_git_blame_inline_delay_task: None,
 1312            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1313            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1314                .session
 1315                .restore_unsaved_buffers,
 1316            blame: None,
 1317            blame_subscription: None,
 1318            tasks: Default::default(),
 1319            _subscriptions: vec![
 1320                cx.observe(&buffer, Self::on_buffer_changed),
 1321                cx.subscribe(&buffer, Self::on_buffer_event),
 1322                cx.observe(&display_map, Self::on_display_map_changed),
 1323                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1324                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1325                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1326                cx.observe_window_activation(|editor, cx| {
 1327                    let active = cx.is_window_active();
 1328                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1329                        if active {
 1330                            blink_manager.enable(cx);
 1331                        } else {
 1332                            blink_manager.disable(cx);
 1333                        }
 1334                    });
 1335                }),
 1336            ],
 1337            tasks_update_task: None,
 1338            linked_edit_ranges: Default::default(),
 1339            previous_search_ranges: None,
 1340            breadcrumb_header: None,
 1341            focused_block: None,
 1342            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1343            addons: HashMap::default(),
 1344            registered_buffers: HashMap::default(),
 1345            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1346            toggle_fold_multiple_buffers: Task::ready(()),
 1347            text_style_refinement: None,
 1348        };
 1349        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1350        this._subscriptions.extend(project_subscriptions);
 1351
 1352        this.end_selection(cx);
 1353        this.scroll_manager.show_scrollbar(cx);
 1354
 1355        if mode == EditorMode::Full {
 1356            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1357            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1358
 1359            if this.git_blame_inline_enabled {
 1360                this.git_blame_inline_enabled = true;
 1361                this.start_git_blame_inline(false, cx);
 1362            }
 1363
 1364            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1365                if let Some(project) = this.project.as_ref() {
 1366                    let lsp_store = project.read(cx).lsp_store();
 1367                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1368                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1369                    });
 1370                    this.registered_buffers
 1371                        .insert(buffer.read(cx).remote_id(), handle);
 1372                }
 1373            }
 1374        }
 1375
 1376        this.report_editor_event("Editor Opened", None, cx);
 1377        this
 1378    }
 1379
 1380    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1381        self.mouse_context_menu
 1382            .as_ref()
 1383            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1384    }
 1385
 1386    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1387        let mut key_context = KeyContext::new_with_defaults();
 1388        key_context.add("Editor");
 1389        let mode = match self.mode {
 1390            EditorMode::SingleLine { .. } => "single_line",
 1391            EditorMode::AutoHeight { .. } => "auto_height",
 1392            EditorMode::Full => "full",
 1393        };
 1394
 1395        if EditorSettings::jupyter_enabled(cx) {
 1396            key_context.add("jupyter");
 1397        }
 1398
 1399        key_context.set("mode", mode);
 1400        if self.pending_rename.is_some() {
 1401            key_context.add("renaming");
 1402        }
 1403        match self.context_menu.borrow().as_ref() {
 1404            Some(CodeContextMenu::Completions(_)) => {
 1405                key_context.add("menu");
 1406                key_context.add("showing_completions")
 1407            }
 1408            Some(CodeContextMenu::CodeActions(_)) => {
 1409                key_context.add("menu");
 1410                key_context.add("showing_code_actions")
 1411            }
 1412            None => {}
 1413        }
 1414
 1415        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1416        if !self.focus_handle(cx).contains_focused(cx)
 1417            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1418        {
 1419            for addon in self.addons.values() {
 1420                addon.extend_key_context(&mut key_context, cx)
 1421            }
 1422        }
 1423
 1424        if let Some(extension) = self
 1425            .buffer
 1426            .read(cx)
 1427            .as_singleton()
 1428            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1429        {
 1430            key_context.set("extension", extension.to_string());
 1431        }
 1432
 1433        if self.has_active_inline_completion() {
 1434            key_context.add("copilot_suggestion");
 1435            key_context.add("inline_completion");
 1436        }
 1437
 1438        if !self
 1439            .selections
 1440            .disjoint
 1441            .iter()
 1442            .all(|selection| selection.start == selection.end)
 1443        {
 1444            key_context.add("selection");
 1445        }
 1446
 1447        key_context
 1448    }
 1449
 1450    pub fn new_file(
 1451        workspace: &mut Workspace,
 1452        _: &workspace::NewFile,
 1453        cx: &mut ViewContext<Workspace>,
 1454    ) {
 1455        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1456            "Failed to create buffer",
 1457            cx,
 1458            |e, _| match e.error_code() {
 1459                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1460                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1461                e.error_tag("required").unwrap_or("the latest version")
 1462            )),
 1463                _ => None,
 1464            },
 1465        );
 1466    }
 1467
 1468    pub fn new_in_workspace(
 1469        workspace: &mut Workspace,
 1470        cx: &mut ViewContext<Workspace>,
 1471    ) -> Task<Result<View<Editor>>> {
 1472        let project = workspace.project().clone();
 1473        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1474
 1475        cx.spawn(|workspace, mut cx| async move {
 1476            let buffer = create.await?;
 1477            workspace.update(&mut cx, |workspace, cx| {
 1478                let editor =
 1479                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1480                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1481                editor
 1482            })
 1483        })
 1484    }
 1485
 1486    fn new_file_vertical(
 1487        workspace: &mut Workspace,
 1488        _: &workspace::NewFileSplitVertical,
 1489        cx: &mut ViewContext<Workspace>,
 1490    ) {
 1491        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1492    }
 1493
 1494    fn new_file_horizontal(
 1495        workspace: &mut Workspace,
 1496        _: &workspace::NewFileSplitHorizontal,
 1497        cx: &mut ViewContext<Workspace>,
 1498    ) {
 1499        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1500    }
 1501
 1502    fn new_file_in_direction(
 1503        workspace: &mut Workspace,
 1504        direction: SplitDirection,
 1505        cx: &mut ViewContext<Workspace>,
 1506    ) {
 1507        let project = workspace.project().clone();
 1508        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1509
 1510        cx.spawn(|workspace, mut cx| async move {
 1511            let buffer = create.await?;
 1512            workspace.update(&mut cx, move |workspace, cx| {
 1513                workspace.split_item(
 1514                    direction,
 1515                    Box::new(
 1516                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1517                    ),
 1518                    cx,
 1519                )
 1520            })?;
 1521            anyhow::Ok(())
 1522        })
 1523        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1524            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1525                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1526                e.error_tag("required").unwrap_or("the latest version")
 1527            )),
 1528            _ => None,
 1529        });
 1530    }
 1531
 1532    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1533        self.leader_peer_id
 1534    }
 1535
 1536    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1537        &self.buffer
 1538    }
 1539
 1540    pub fn workspace(&self) -> Option<View<Workspace>> {
 1541        self.workspace.as_ref()?.0.upgrade()
 1542    }
 1543
 1544    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1545        self.buffer().read(cx).title(cx)
 1546    }
 1547
 1548    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1549        let git_blame_gutter_max_author_length = self
 1550            .render_git_blame_gutter(cx)
 1551            .then(|| {
 1552                if let Some(blame) = self.blame.as_ref() {
 1553                    let max_author_length =
 1554                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1555                    Some(max_author_length)
 1556                } else {
 1557                    None
 1558                }
 1559            })
 1560            .flatten();
 1561
 1562        EditorSnapshot {
 1563            mode: self.mode,
 1564            show_gutter: self.show_gutter,
 1565            show_line_numbers: self.show_line_numbers,
 1566            show_git_diff_gutter: self.show_git_diff_gutter,
 1567            show_code_actions: self.show_code_actions,
 1568            show_runnables: self.show_runnables,
 1569            git_blame_gutter_max_author_length,
 1570            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1571            scroll_anchor: self.scroll_manager.anchor(),
 1572            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1573            placeholder_text: self.placeholder_text.clone(),
 1574            diff_map: self.diff_map.snapshot(),
 1575            is_focused: self.focus_handle.is_focused(cx),
 1576            current_line_highlight: self
 1577                .current_line_highlight
 1578                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1579            gutter_hovered: self.gutter_hovered,
 1580        }
 1581    }
 1582
 1583    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1584        self.buffer.read(cx).language_at(point, cx)
 1585    }
 1586
 1587    pub fn file_at<T: ToOffset>(
 1588        &self,
 1589        point: T,
 1590        cx: &AppContext,
 1591    ) -> Option<Arc<dyn language::File>> {
 1592        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1593    }
 1594
 1595    pub fn active_excerpt(
 1596        &self,
 1597        cx: &AppContext,
 1598    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1599        self.buffer
 1600            .read(cx)
 1601            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1602    }
 1603
 1604    pub fn mode(&self) -> EditorMode {
 1605        self.mode
 1606    }
 1607
 1608    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1609        self.collaboration_hub.as_deref()
 1610    }
 1611
 1612    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1613        self.collaboration_hub = Some(hub);
 1614    }
 1615
 1616    pub fn set_custom_context_menu(
 1617        &mut self,
 1618        f: impl 'static
 1619            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1620    ) {
 1621        self.custom_context_menu = Some(Box::new(f))
 1622    }
 1623
 1624    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1625        self.completion_provider = provider;
 1626    }
 1627
 1628    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1629        self.semantics_provider.clone()
 1630    }
 1631
 1632    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1633        self.semantics_provider = provider;
 1634    }
 1635
 1636    pub fn set_inline_completion_provider<T>(
 1637        &mut self,
 1638        provider: Option<Model<T>>,
 1639        cx: &mut ViewContext<Self>,
 1640    ) where
 1641        T: InlineCompletionProvider,
 1642    {
 1643        self.inline_completion_provider =
 1644            provider.map(|provider| RegisteredInlineCompletionProvider {
 1645                _subscription: cx.observe(&provider, |this, _, cx| {
 1646                    if this.focus_handle.is_focused(cx) {
 1647                        this.update_visible_inline_completion(cx);
 1648                    }
 1649                }),
 1650                provider: Arc::new(provider),
 1651            });
 1652        self.refresh_inline_completion(false, false, cx);
 1653    }
 1654
 1655    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1656        self.placeholder_text.as_deref()
 1657    }
 1658
 1659    pub fn set_placeholder_text(
 1660        &mut self,
 1661        placeholder_text: impl Into<Arc<str>>,
 1662        cx: &mut ViewContext<Self>,
 1663    ) {
 1664        let placeholder_text = Some(placeholder_text.into());
 1665        if self.placeholder_text != placeholder_text {
 1666            self.placeholder_text = placeholder_text;
 1667            cx.notify();
 1668        }
 1669    }
 1670
 1671    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1672        self.cursor_shape = cursor_shape;
 1673
 1674        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1675        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1676
 1677        cx.notify();
 1678    }
 1679
 1680    pub fn set_current_line_highlight(
 1681        &mut self,
 1682        current_line_highlight: Option<CurrentLineHighlight>,
 1683    ) {
 1684        self.current_line_highlight = current_line_highlight;
 1685    }
 1686
 1687    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1688        self.collapse_matches = collapse_matches;
 1689    }
 1690
 1691    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1692        let buffers = self.buffer.read(cx).all_buffers();
 1693        let Some(lsp_store) = self.lsp_store(cx) else {
 1694            return;
 1695        };
 1696        lsp_store.update(cx, |lsp_store, cx| {
 1697            for buffer in buffers {
 1698                self.registered_buffers
 1699                    .entry(buffer.read(cx).remote_id())
 1700                    .or_insert_with(|| {
 1701                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1702                    });
 1703            }
 1704        })
 1705    }
 1706
 1707    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1708        if self.collapse_matches {
 1709            return range.start..range.start;
 1710        }
 1711        range.clone()
 1712    }
 1713
 1714    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1715        if self.display_map.read(cx).clip_at_line_ends != clip {
 1716            self.display_map
 1717                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1718        }
 1719    }
 1720
 1721    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1722        self.input_enabled = input_enabled;
 1723    }
 1724
 1725    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1726        self.enable_inline_completions = enabled;
 1727    }
 1728
 1729    pub fn set_autoindent(&mut self, autoindent: bool) {
 1730        if autoindent {
 1731            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1732        } else {
 1733            self.autoindent_mode = None;
 1734        }
 1735    }
 1736
 1737    pub fn read_only(&self, cx: &AppContext) -> bool {
 1738        self.read_only || self.buffer.read(cx).read_only()
 1739    }
 1740
 1741    pub fn set_read_only(&mut self, read_only: bool) {
 1742        self.read_only = read_only;
 1743    }
 1744
 1745    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1746        self.use_autoclose = autoclose;
 1747    }
 1748
 1749    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1750        self.use_auto_surround = auto_surround;
 1751    }
 1752
 1753    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1754        self.auto_replace_emoji_shortcode = auto_replace;
 1755    }
 1756
 1757    pub fn toggle_inline_completions(
 1758        &mut self,
 1759        _: &ToggleInlineCompletions,
 1760        cx: &mut ViewContext<Self>,
 1761    ) {
 1762        if self.show_inline_completions_override.is_some() {
 1763            self.set_show_inline_completions(None, cx);
 1764        } else {
 1765            let cursor = self.selections.newest_anchor().head();
 1766            if let Some((buffer, cursor_buffer_position)) =
 1767                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1768            {
 1769                let show_inline_completions =
 1770                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1771                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1772            }
 1773        }
 1774    }
 1775
 1776    pub fn set_show_inline_completions(
 1777        &mut self,
 1778        show_inline_completions: Option<bool>,
 1779        cx: &mut ViewContext<Self>,
 1780    ) {
 1781        self.show_inline_completions_override = show_inline_completions;
 1782        self.refresh_inline_completion(false, true, cx);
 1783    }
 1784
 1785    fn should_show_inline_completions(
 1786        &self,
 1787        buffer: &Model<Buffer>,
 1788        buffer_position: language::Anchor,
 1789        cx: &AppContext,
 1790    ) -> bool {
 1791        if !self.snippet_stack.is_empty() {
 1792            return false;
 1793        }
 1794
 1795        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1796            return false;
 1797        }
 1798
 1799        if let Some(provider) = self.inline_completion_provider() {
 1800            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1801                show_inline_completions
 1802            } else {
 1803                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1804            }
 1805        } else {
 1806            false
 1807        }
 1808    }
 1809
 1810    fn inline_completions_disabled_in_scope(
 1811        &self,
 1812        buffer: &Model<Buffer>,
 1813        buffer_position: language::Anchor,
 1814        cx: &AppContext,
 1815    ) -> bool {
 1816        let snapshot = buffer.read(cx).snapshot();
 1817        let settings = snapshot.settings_at(buffer_position, cx);
 1818
 1819        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1820            return false;
 1821        };
 1822
 1823        scope.override_name().map_or(false, |scope_name| {
 1824            settings
 1825                .inline_completions_disabled_in
 1826                .iter()
 1827                .any(|s| s == scope_name)
 1828        })
 1829    }
 1830
 1831    pub fn set_use_modal_editing(&mut self, to: bool) {
 1832        self.use_modal_editing = to;
 1833    }
 1834
 1835    pub fn use_modal_editing(&self) -> bool {
 1836        self.use_modal_editing
 1837    }
 1838
 1839    fn selections_did_change(
 1840        &mut self,
 1841        local: bool,
 1842        old_cursor_position: &Anchor,
 1843        show_completions: bool,
 1844        cx: &mut ViewContext<Self>,
 1845    ) {
 1846        cx.invalidate_character_coordinates();
 1847
 1848        // Copy selections to primary selection buffer
 1849        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1850        if local {
 1851            let selections = self.selections.all::<usize>(cx);
 1852            let buffer_handle = self.buffer.read(cx).read(cx);
 1853
 1854            let mut text = String::new();
 1855            for (index, selection) in selections.iter().enumerate() {
 1856                let text_for_selection = buffer_handle
 1857                    .text_for_range(selection.start..selection.end)
 1858                    .collect::<String>();
 1859
 1860                text.push_str(&text_for_selection);
 1861                if index != selections.len() - 1 {
 1862                    text.push('\n');
 1863                }
 1864            }
 1865
 1866            if !text.is_empty() {
 1867                cx.write_to_primary(ClipboardItem::new_string(text));
 1868            }
 1869        }
 1870
 1871        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1872            self.buffer.update(cx, |buffer, cx| {
 1873                buffer.set_active_selections(
 1874                    &self.selections.disjoint_anchors(),
 1875                    self.selections.line_mode,
 1876                    self.cursor_shape,
 1877                    cx,
 1878                )
 1879            });
 1880        }
 1881        let display_map = self
 1882            .display_map
 1883            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1884        let buffer = &display_map.buffer_snapshot;
 1885        self.add_selections_state = None;
 1886        self.select_next_state = None;
 1887        self.select_prev_state = None;
 1888        self.select_larger_syntax_node_stack.clear();
 1889        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1890        self.snippet_stack
 1891            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1892        self.take_rename(false, cx);
 1893
 1894        let new_cursor_position = self.selections.newest_anchor().head();
 1895
 1896        self.push_to_nav_history(
 1897            *old_cursor_position,
 1898            Some(new_cursor_position.to_point(buffer)),
 1899            cx,
 1900        );
 1901
 1902        if local {
 1903            let new_cursor_position = self.selections.newest_anchor().head();
 1904            let mut context_menu = self.context_menu.borrow_mut();
 1905            let completion_menu = match context_menu.as_ref() {
 1906                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1907                _ => {
 1908                    *context_menu = None;
 1909                    None
 1910                }
 1911            };
 1912
 1913            if let Some(completion_menu) = completion_menu {
 1914                let cursor_position = new_cursor_position.to_offset(buffer);
 1915                let (word_range, kind) =
 1916                    buffer.surrounding_word(completion_menu.initial_position, true);
 1917                if kind == Some(CharKind::Word)
 1918                    && word_range.to_inclusive().contains(&cursor_position)
 1919                {
 1920                    let mut completion_menu = completion_menu.clone();
 1921                    drop(context_menu);
 1922
 1923                    let query = Self::completion_query(buffer, cursor_position);
 1924                    cx.spawn(move |this, mut cx| async move {
 1925                        completion_menu
 1926                            .filter(query.as_deref(), cx.background_executor().clone())
 1927                            .await;
 1928
 1929                        this.update(&mut cx, |this, cx| {
 1930                            let mut context_menu = this.context_menu.borrow_mut();
 1931                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1932                            else {
 1933                                return;
 1934                            };
 1935
 1936                            if menu.id > completion_menu.id {
 1937                                return;
 1938                            }
 1939
 1940                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1941                            drop(context_menu);
 1942                            cx.notify();
 1943                        })
 1944                    })
 1945                    .detach();
 1946
 1947                    if show_completions {
 1948                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1949                    }
 1950                } else {
 1951                    drop(context_menu);
 1952                    self.hide_context_menu(cx);
 1953                }
 1954            } else {
 1955                drop(context_menu);
 1956            }
 1957
 1958            hide_hover(self, cx);
 1959
 1960            if old_cursor_position.to_display_point(&display_map).row()
 1961                != new_cursor_position.to_display_point(&display_map).row()
 1962            {
 1963                self.available_code_actions.take();
 1964            }
 1965            self.refresh_code_actions(cx);
 1966            self.refresh_document_highlights(cx);
 1967            refresh_matching_bracket_highlights(self, cx);
 1968            self.update_visible_inline_completion(cx);
 1969            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1970            if self.git_blame_inline_enabled {
 1971                self.start_inline_blame_timer(cx);
 1972            }
 1973        }
 1974
 1975        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1976        cx.emit(EditorEvent::SelectionsChanged { local });
 1977
 1978        if self.selections.disjoint_anchors().len() == 1 {
 1979            cx.emit(SearchEvent::ActiveMatchChanged)
 1980        }
 1981        cx.notify();
 1982    }
 1983
 1984    pub fn change_selections<R>(
 1985        &mut self,
 1986        autoscroll: Option<Autoscroll>,
 1987        cx: &mut ViewContext<Self>,
 1988        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1989    ) -> R {
 1990        self.change_selections_inner(autoscroll, true, cx, change)
 1991    }
 1992
 1993    pub fn change_selections_inner<R>(
 1994        &mut self,
 1995        autoscroll: Option<Autoscroll>,
 1996        request_completions: bool,
 1997        cx: &mut ViewContext<Self>,
 1998        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1999    ) -> R {
 2000        let old_cursor_position = self.selections.newest_anchor().head();
 2001        self.push_to_selection_history();
 2002
 2003        let (changed, result) = self.selections.change_with(cx, change);
 2004
 2005        if changed {
 2006            if let Some(autoscroll) = autoscroll {
 2007                self.request_autoscroll(autoscroll, cx);
 2008            }
 2009            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2010
 2011            if self.should_open_signature_help_automatically(
 2012                &old_cursor_position,
 2013                self.signature_help_state.backspace_pressed(),
 2014                cx,
 2015            ) {
 2016                self.show_signature_help(&ShowSignatureHelp, cx);
 2017            }
 2018            self.signature_help_state.set_backspace_pressed(false);
 2019        }
 2020
 2021        result
 2022    }
 2023
 2024    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2025    where
 2026        I: IntoIterator<Item = (Range<S>, T)>,
 2027        S: ToOffset,
 2028        T: Into<Arc<str>>,
 2029    {
 2030        if self.read_only(cx) {
 2031            return;
 2032        }
 2033
 2034        self.buffer
 2035            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2036    }
 2037
 2038    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2039    where
 2040        I: IntoIterator<Item = (Range<S>, T)>,
 2041        S: ToOffset,
 2042        T: Into<Arc<str>>,
 2043    {
 2044        if self.read_only(cx) {
 2045            return;
 2046        }
 2047
 2048        self.buffer.update(cx, |buffer, cx| {
 2049            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2050        });
 2051    }
 2052
 2053    pub fn edit_with_block_indent<I, S, T>(
 2054        &mut self,
 2055        edits: I,
 2056        original_indent_columns: Vec<u32>,
 2057        cx: &mut ViewContext<Self>,
 2058    ) where
 2059        I: IntoIterator<Item = (Range<S>, T)>,
 2060        S: ToOffset,
 2061        T: Into<Arc<str>>,
 2062    {
 2063        if self.read_only(cx) {
 2064            return;
 2065        }
 2066
 2067        self.buffer.update(cx, |buffer, cx| {
 2068            buffer.edit(
 2069                edits,
 2070                Some(AutoindentMode::Block {
 2071                    original_indent_columns,
 2072                }),
 2073                cx,
 2074            )
 2075        });
 2076    }
 2077
 2078    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2079        self.hide_context_menu(cx);
 2080
 2081        match phase {
 2082            SelectPhase::Begin {
 2083                position,
 2084                add,
 2085                click_count,
 2086            } => self.begin_selection(position, add, click_count, cx),
 2087            SelectPhase::BeginColumnar {
 2088                position,
 2089                goal_column,
 2090                reset,
 2091            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2092            SelectPhase::Extend {
 2093                position,
 2094                click_count,
 2095            } => self.extend_selection(position, click_count, cx),
 2096            SelectPhase::Update {
 2097                position,
 2098                goal_column,
 2099                scroll_delta,
 2100            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2101            SelectPhase::End => self.end_selection(cx),
 2102        }
 2103    }
 2104
 2105    fn extend_selection(
 2106        &mut self,
 2107        position: DisplayPoint,
 2108        click_count: usize,
 2109        cx: &mut ViewContext<Self>,
 2110    ) {
 2111        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2112        let tail = self.selections.newest::<usize>(cx).tail();
 2113        self.begin_selection(position, false, click_count, cx);
 2114
 2115        let position = position.to_offset(&display_map, Bias::Left);
 2116        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2117
 2118        let mut pending_selection = self
 2119            .selections
 2120            .pending_anchor()
 2121            .expect("extend_selection not called with pending selection");
 2122        if position >= tail {
 2123            pending_selection.start = tail_anchor;
 2124        } else {
 2125            pending_selection.end = tail_anchor;
 2126            pending_selection.reversed = true;
 2127        }
 2128
 2129        let mut pending_mode = self.selections.pending_mode().unwrap();
 2130        match &mut pending_mode {
 2131            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2132            _ => {}
 2133        }
 2134
 2135        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2136            s.set_pending(pending_selection, pending_mode)
 2137        });
 2138    }
 2139
 2140    fn begin_selection(
 2141        &mut self,
 2142        position: DisplayPoint,
 2143        add: bool,
 2144        click_count: usize,
 2145        cx: &mut ViewContext<Self>,
 2146    ) {
 2147        if !self.focus_handle.is_focused(cx) {
 2148            self.last_focused_descendant = None;
 2149            cx.focus(&self.focus_handle);
 2150        }
 2151
 2152        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2153        let buffer = &display_map.buffer_snapshot;
 2154        let newest_selection = self.selections.newest_anchor().clone();
 2155        let position = display_map.clip_point(position, Bias::Left);
 2156
 2157        let start;
 2158        let end;
 2159        let mode;
 2160        let mut auto_scroll;
 2161        match click_count {
 2162            1 => {
 2163                start = buffer.anchor_before(position.to_point(&display_map));
 2164                end = start;
 2165                mode = SelectMode::Character;
 2166                auto_scroll = true;
 2167            }
 2168            2 => {
 2169                let range = movement::surrounding_word(&display_map, position);
 2170                start = buffer.anchor_before(range.start.to_point(&display_map));
 2171                end = buffer.anchor_before(range.end.to_point(&display_map));
 2172                mode = SelectMode::Word(start..end);
 2173                auto_scroll = true;
 2174            }
 2175            3 => {
 2176                let position = display_map
 2177                    .clip_point(position, Bias::Left)
 2178                    .to_point(&display_map);
 2179                let line_start = display_map.prev_line_boundary(position).0;
 2180                let next_line_start = buffer.clip_point(
 2181                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2182                    Bias::Left,
 2183                );
 2184                start = buffer.anchor_before(line_start);
 2185                end = buffer.anchor_before(next_line_start);
 2186                mode = SelectMode::Line(start..end);
 2187                auto_scroll = true;
 2188            }
 2189            _ => {
 2190                start = buffer.anchor_before(0);
 2191                end = buffer.anchor_before(buffer.len());
 2192                mode = SelectMode::All;
 2193                auto_scroll = false;
 2194            }
 2195        }
 2196        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2197
 2198        let point_to_delete: Option<usize> = {
 2199            let selected_points: Vec<Selection<Point>> =
 2200                self.selections.disjoint_in_range(start..end, cx);
 2201
 2202            if !add || click_count > 1 {
 2203                None
 2204            } else if !selected_points.is_empty() {
 2205                Some(selected_points[0].id)
 2206            } else {
 2207                let clicked_point_already_selected =
 2208                    self.selections.disjoint.iter().find(|selection| {
 2209                        selection.start.to_point(buffer) == start.to_point(buffer)
 2210                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2211                    });
 2212
 2213                clicked_point_already_selected.map(|selection| selection.id)
 2214            }
 2215        };
 2216
 2217        let selections_count = self.selections.count();
 2218
 2219        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2220            if let Some(point_to_delete) = point_to_delete {
 2221                s.delete(point_to_delete);
 2222
 2223                if selections_count == 1 {
 2224                    s.set_pending_anchor_range(start..end, mode);
 2225                }
 2226            } else {
 2227                if !add {
 2228                    s.clear_disjoint();
 2229                } else if click_count > 1 {
 2230                    s.delete(newest_selection.id)
 2231                }
 2232
 2233                s.set_pending_anchor_range(start..end, mode);
 2234            }
 2235        });
 2236    }
 2237
 2238    fn begin_columnar_selection(
 2239        &mut self,
 2240        position: DisplayPoint,
 2241        goal_column: u32,
 2242        reset: bool,
 2243        cx: &mut ViewContext<Self>,
 2244    ) {
 2245        if !self.focus_handle.is_focused(cx) {
 2246            self.last_focused_descendant = None;
 2247            cx.focus(&self.focus_handle);
 2248        }
 2249
 2250        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2251
 2252        if reset {
 2253            let pointer_position = display_map
 2254                .buffer_snapshot
 2255                .anchor_before(position.to_point(&display_map));
 2256
 2257            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2258                s.clear_disjoint();
 2259                s.set_pending_anchor_range(
 2260                    pointer_position..pointer_position,
 2261                    SelectMode::Character,
 2262                );
 2263            });
 2264        }
 2265
 2266        let tail = self.selections.newest::<Point>(cx).tail();
 2267        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2268
 2269        if !reset {
 2270            self.select_columns(
 2271                tail.to_display_point(&display_map),
 2272                position,
 2273                goal_column,
 2274                &display_map,
 2275                cx,
 2276            );
 2277        }
 2278    }
 2279
 2280    fn update_selection(
 2281        &mut self,
 2282        position: DisplayPoint,
 2283        goal_column: u32,
 2284        scroll_delta: gpui::Point<f32>,
 2285        cx: &mut ViewContext<Self>,
 2286    ) {
 2287        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2288
 2289        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2290            let tail = tail.to_display_point(&display_map);
 2291            self.select_columns(tail, position, goal_column, &display_map, cx);
 2292        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2293            let buffer = self.buffer.read(cx).snapshot(cx);
 2294            let head;
 2295            let tail;
 2296            let mode = self.selections.pending_mode().unwrap();
 2297            match &mode {
 2298                SelectMode::Character => {
 2299                    head = position.to_point(&display_map);
 2300                    tail = pending.tail().to_point(&buffer);
 2301                }
 2302                SelectMode::Word(original_range) => {
 2303                    let original_display_range = original_range.start.to_display_point(&display_map)
 2304                        ..original_range.end.to_display_point(&display_map);
 2305                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2306                        ..original_display_range.end.to_point(&display_map);
 2307                    if movement::is_inside_word(&display_map, position)
 2308                        || original_display_range.contains(&position)
 2309                    {
 2310                        let word_range = movement::surrounding_word(&display_map, position);
 2311                        if word_range.start < original_display_range.start {
 2312                            head = word_range.start.to_point(&display_map);
 2313                        } else {
 2314                            head = word_range.end.to_point(&display_map);
 2315                        }
 2316                    } else {
 2317                        head = position.to_point(&display_map);
 2318                    }
 2319
 2320                    if head <= original_buffer_range.start {
 2321                        tail = original_buffer_range.end;
 2322                    } else {
 2323                        tail = original_buffer_range.start;
 2324                    }
 2325                }
 2326                SelectMode::Line(original_range) => {
 2327                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2328
 2329                    let position = display_map
 2330                        .clip_point(position, Bias::Left)
 2331                        .to_point(&display_map);
 2332                    let line_start = display_map.prev_line_boundary(position).0;
 2333                    let next_line_start = buffer.clip_point(
 2334                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2335                        Bias::Left,
 2336                    );
 2337
 2338                    if line_start < original_range.start {
 2339                        head = line_start
 2340                    } else {
 2341                        head = next_line_start
 2342                    }
 2343
 2344                    if head <= original_range.start {
 2345                        tail = original_range.end;
 2346                    } else {
 2347                        tail = original_range.start;
 2348                    }
 2349                }
 2350                SelectMode::All => {
 2351                    return;
 2352                }
 2353            };
 2354
 2355            if head < tail {
 2356                pending.start = buffer.anchor_before(head);
 2357                pending.end = buffer.anchor_before(tail);
 2358                pending.reversed = true;
 2359            } else {
 2360                pending.start = buffer.anchor_before(tail);
 2361                pending.end = buffer.anchor_before(head);
 2362                pending.reversed = false;
 2363            }
 2364
 2365            self.change_selections(None, cx, |s| {
 2366                s.set_pending(pending, mode);
 2367            });
 2368        } else {
 2369            log::error!("update_selection dispatched with no pending selection");
 2370            return;
 2371        }
 2372
 2373        self.apply_scroll_delta(scroll_delta, cx);
 2374        cx.notify();
 2375    }
 2376
 2377    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2378        self.columnar_selection_tail.take();
 2379        if self.selections.pending_anchor().is_some() {
 2380            let selections = self.selections.all::<usize>(cx);
 2381            self.change_selections(None, cx, |s| {
 2382                s.select(selections);
 2383                s.clear_pending();
 2384            });
 2385        }
 2386    }
 2387
 2388    fn select_columns(
 2389        &mut self,
 2390        tail: DisplayPoint,
 2391        head: DisplayPoint,
 2392        goal_column: u32,
 2393        display_map: &DisplaySnapshot,
 2394        cx: &mut ViewContext<Self>,
 2395    ) {
 2396        let start_row = cmp::min(tail.row(), head.row());
 2397        let end_row = cmp::max(tail.row(), head.row());
 2398        let start_column = cmp::min(tail.column(), goal_column);
 2399        let end_column = cmp::max(tail.column(), goal_column);
 2400        let reversed = start_column < tail.column();
 2401
 2402        let selection_ranges = (start_row.0..=end_row.0)
 2403            .map(DisplayRow)
 2404            .filter_map(|row| {
 2405                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2406                    let start = display_map
 2407                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2408                        .to_point(display_map);
 2409                    let end = display_map
 2410                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2411                        .to_point(display_map);
 2412                    if reversed {
 2413                        Some(end..start)
 2414                    } else {
 2415                        Some(start..end)
 2416                    }
 2417                } else {
 2418                    None
 2419                }
 2420            })
 2421            .collect::<Vec<_>>();
 2422
 2423        self.change_selections(None, cx, |s| {
 2424            s.select_ranges(selection_ranges);
 2425        });
 2426        cx.notify();
 2427    }
 2428
 2429    pub fn has_pending_nonempty_selection(&self) -> bool {
 2430        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2431            Some(Selection { start, end, .. }) => start != end,
 2432            None => false,
 2433        };
 2434
 2435        pending_nonempty_selection
 2436            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2437    }
 2438
 2439    pub fn has_pending_selection(&self) -> bool {
 2440        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2441    }
 2442
 2443    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2444        if self.clear_expanded_diff_hunks(cx) {
 2445            cx.notify();
 2446            return;
 2447        }
 2448        if self.dismiss_menus_and_popups(true, cx) {
 2449            return;
 2450        }
 2451
 2452        if self.mode == EditorMode::Full
 2453            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2454        {
 2455            return;
 2456        }
 2457
 2458        cx.propagate();
 2459    }
 2460
 2461    pub fn dismiss_menus_and_popups(
 2462        &mut self,
 2463        should_report_inline_completion_event: bool,
 2464        cx: &mut ViewContext<Self>,
 2465    ) -> bool {
 2466        if self.take_rename(false, cx).is_some() {
 2467            return true;
 2468        }
 2469
 2470        if hide_hover(self, cx) {
 2471            return true;
 2472        }
 2473
 2474        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2475            return true;
 2476        }
 2477
 2478        if self.hide_context_menu(cx).is_some() {
 2479            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2480                self.update_visible_inline_completion(cx);
 2481            }
 2482            return true;
 2483        }
 2484
 2485        if self.mouse_context_menu.take().is_some() {
 2486            return true;
 2487        }
 2488
 2489        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2490            return true;
 2491        }
 2492
 2493        if self.snippet_stack.pop().is_some() {
 2494            return true;
 2495        }
 2496
 2497        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2498            self.dismiss_diagnostics(cx);
 2499            return true;
 2500        }
 2501
 2502        false
 2503    }
 2504
 2505    fn linked_editing_ranges_for(
 2506        &self,
 2507        selection: Range<text::Anchor>,
 2508        cx: &AppContext,
 2509    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2510        if self.linked_edit_ranges.is_empty() {
 2511            return None;
 2512        }
 2513        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2514            selection.end.buffer_id.and_then(|end_buffer_id| {
 2515                if selection.start.buffer_id != Some(end_buffer_id) {
 2516                    return None;
 2517                }
 2518                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2519                let snapshot = buffer.read(cx).snapshot();
 2520                self.linked_edit_ranges
 2521                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2522                    .map(|ranges| (ranges, snapshot, buffer))
 2523            })?;
 2524        use text::ToOffset as TO;
 2525        // find offset from the start of current range to current cursor position
 2526        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2527
 2528        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2529        let start_difference = start_offset - start_byte_offset;
 2530        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2531        let end_difference = end_offset - start_byte_offset;
 2532        // Current range has associated linked ranges.
 2533        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2534        for range in linked_ranges.iter() {
 2535            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2536            let end_offset = start_offset + end_difference;
 2537            let start_offset = start_offset + start_difference;
 2538            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2539                continue;
 2540            }
 2541            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2542                if s.start.buffer_id != selection.start.buffer_id
 2543                    || s.end.buffer_id != selection.end.buffer_id
 2544                {
 2545                    return false;
 2546                }
 2547                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2548                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2549            }) {
 2550                continue;
 2551            }
 2552            let start = buffer_snapshot.anchor_after(start_offset);
 2553            let end = buffer_snapshot.anchor_after(end_offset);
 2554            linked_edits
 2555                .entry(buffer.clone())
 2556                .or_default()
 2557                .push(start..end);
 2558        }
 2559        Some(linked_edits)
 2560    }
 2561
 2562    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2563        let text: Arc<str> = text.into();
 2564
 2565        if self.read_only(cx) {
 2566            return;
 2567        }
 2568
 2569        let selections = self.selections.all_adjusted(cx);
 2570        let mut bracket_inserted = false;
 2571        let mut edits = Vec::new();
 2572        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2573        let mut new_selections = Vec::with_capacity(selections.len());
 2574        let mut new_autoclose_regions = Vec::new();
 2575        let snapshot = self.buffer.read(cx).read(cx);
 2576
 2577        for (selection, autoclose_region) in
 2578            self.selections_with_autoclose_regions(selections, &snapshot)
 2579        {
 2580            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2581                // Determine if the inserted text matches the opening or closing
 2582                // bracket of any of this language's bracket pairs.
 2583                let mut bracket_pair = None;
 2584                let mut is_bracket_pair_start = false;
 2585                let mut is_bracket_pair_end = false;
 2586                if !text.is_empty() {
 2587                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2588                    //  and they are removing the character that triggered IME popup.
 2589                    for (pair, enabled) in scope.brackets() {
 2590                        if !pair.close && !pair.surround {
 2591                            continue;
 2592                        }
 2593
 2594                        if enabled && pair.start.ends_with(text.as_ref()) {
 2595                            let prefix_len = pair.start.len() - text.len();
 2596                            let preceding_text_matches_prefix = prefix_len == 0
 2597                                || (selection.start.column >= (prefix_len as u32)
 2598                                    && snapshot.contains_str_at(
 2599                                        Point::new(
 2600                                            selection.start.row,
 2601                                            selection.start.column - (prefix_len as u32),
 2602                                        ),
 2603                                        &pair.start[..prefix_len],
 2604                                    ));
 2605                            if preceding_text_matches_prefix {
 2606                                bracket_pair = Some(pair.clone());
 2607                                is_bracket_pair_start = true;
 2608                                break;
 2609                            }
 2610                        }
 2611                        if pair.end.as_str() == text.as_ref() {
 2612                            bracket_pair = Some(pair.clone());
 2613                            is_bracket_pair_end = true;
 2614                            break;
 2615                        }
 2616                    }
 2617                }
 2618
 2619                if let Some(bracket_pair) = bracket_pair {
 2620                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2621                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2622                    let auto_surround =
 2623                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2624                    if selection.is_empty() {
 2625                        if is_bracket_pair_start {
 2626                            // If the inserted text is a suffix of an opening bracket and the
 2627                            // selection is preceded by the rest of the opening bracket, then
 2628                            // insert the closing bracket.
 2629                            let following_text_allows_autoclose = snapshot
 2630                                .chars_at(selection.start)
 2631                                .next()
 2632                                .map_or(true, |c| scope.should_autoclose_before(c));
 2633
 2634                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2635                                && bracket_pair.start.len() == 1
 2636                            {
 2637                                let target = bracket_pair.start.chars().next().unwrap();
 2638                                let current_line_count = snapshot
 2639                                    .reversed_chars_at(selection.start)
 2640                                    .take_while(|&c| c != '\n')
 2641                                    .filter(|&c| c == target)
 2642                                    .count();
 2643                                current_line_count % 2 == 1
 2644                            } else {
 2645                                false
 2646                            };
 2647
 2648                            if autoclose
 2649                                && bracket_pair.close
 2650                                && following_text_allows_autoclose
 2651                                && !is_closing_quote
 2652                            {
 2653                                let anchor = snapshot.anchor_before(selection.end);
 2654                                new_selections.push((selection.map(|_| anchor), text.len()));
 2655                                new_autoclose_regions.push((
 2656                                    anchor,
 2657                                    text.len(),
 2658                                    selection.id,
 2659                                    bracket_pair.clone(),
 2660                                ));
 2661                                edits.push((
 2662                                    selection.range(),
 2663                                    format!("{}{}", text, bracket_pair.end).into(),
 2664                                ));
 2665                                bracket_inserted = true;
 2666                                continue;
 2667                            }
 2668                        }
 2669
 2670                        if let Some(region) = autoclose_region {
 2671                            // If the selection is followed by an auto-inserted closing bracket,
 2672                            // then don't insert that closing bracket again; just move the selection
 2673                            // past the closing bracket.
 2674                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2675                                && text.as_ref() == region.pair.end.as_str();
 2676                            if should_skip {
 2677                                let anchor = snapshot.anchor_after(selection.end);
 2678                                new_selections
 2679                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2680                                continue;
 2681                            }
 2682                        }
 2683
 2684                        let always_treat_brackets_as_autoclosed = snapshot
 2685                            .settings_at(selection.start, cx)
 2686                            .always_treat_brackets_as_autoclosed;
 2687                        if always_treat_brackets_as_autoclosed
 2688                            && is_bracket_pair_end
 2689                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2690                        {
 2691                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2692                            // and the inserted text is a closing bracket and the selection is followed
 2693                            // by the closing bracket then move the selection past the closing bracket.
 2694                            let anchor = snapshot.anchor_after(selection.end);
 2695                            new_selections.push((selection.map(|_| anchor), text.len()));
 2696                            continue;
 2697                        }
 2698                    }
 2699                    // If an opening bracket is 1 character long and is typed while
 2700                    // text is selected, then surround that text with the bracket pair.
 2701                    else if auto_surround
 2702                        && bracket_pair.surround
 2703                        && is_bracket_pair_start
 2704                        && bracket_pair.start.chars().count() == 1
 2705                    {
 2706                        edits.push((selection.start..selection.start, text.clone()));
 2707                        edits.push((
 2708                            selection.end..selection.end,
 2709                            bracket_pair.end.as_str().into(),
 2710                        ));
 2711                        bracket_inserted = true;
 2712                        new_selections.push((
 2713                            Selection {
 2714                                id: selection.id,
 2715                                start: snapshot.anchor_after(selection.start),
 2716                                end: snapshot.anchor_before(selection.end),
 2717                                reversed: selection.reversed,
 2718                                goal: selection.goal,
 2719                            },
 2720                            0,
 2721                        ));
 2722                        continue;
 2723                    }
 2724                }
 2725            }
 2726
 2727            if self.auto_replace_emoji_shortcode
 2728                && selection.is_empty()
 2729                && text.as_ref().ends_with(':')
 2730            {
 2731                if let Some(possible_emoji_short_code) =
 2732                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2733                {
 2734                    if !possible_emoji_short_code.is_empty() {
 2735                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2736                            let emoji_shortcode_start = Point::new(
 2737                                selection.start.row,
 2738                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2739                            );
 2740
 2741                            // Remove shortcode from buffer
 2742                            edits.push((
 2743                                emoji_shortcode_start..selection.start,
 2744                                "".to_string().into(),
 2745                            ));
 2746                            new_selections.push((
 2747                                Selection {
 2748                                    id: selection.id,
 2749                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2750                                    end: snapshot.anchor_before(selection.start),
 2751                                    reversed: selection.reversed,
 2752                                    goal: selection.goal,
 2753                                },
 2754                                0,
 2755                            ));
 2756
 2757                            // Insert emoji
 2758                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2759                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2760                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2761
 2762                            continue;
 2763                        }
 2764                    }
 2765                }
 2766            }
 2767
 2768            // If not handling any auto-close operation, then just replace the selected
 2769            // text with the given input and move the selection to the end of the
 2770            // newly inserted text.
 2771            let anchor = snapshot.anchor_after(selection.end);
 2772            if !self.linked_edit_ranges.is_empty() {
 2773                let start_anchor = snapshot.anchor_before(selection.start);
 2774
 2775                let is_word_char = text.chars().next().map_or(true, |char| {
 2776                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2777                    classifier.is_word(char)
 2778                });
 2779
 2780                if is_word_char {
 2781                    if let Some(ranges) = self
 2782                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2783                    {
 2784                        for (buffer, edits) in ranges {
 2785                            linked_edits
 2786                                .entry(buffer.clone())
 2787                                .or_default()
 2788                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2789                        }
 2790                    }
 2791                }
 2792            }
 2793
 2794            new_selections.push((selection.map(|_| anchor), 0));
 2795            edits.push((selection.start..selection.end, text.clone()));
 2796        }
 2797
 2798        drop(snapshot);
 2799
 2800        self.transact(cx, |this, cx| {
 2801            this.buffer.update(cx, |buffer, cx| {
 2802                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2803            });
 2804            for (buffer, edits) in linked_edits {
 2805                buffer.update(cx, |buffer, cx| {
 2806                    let snapshot = buffer.snapshot();
 2807                    let edits = edits
 2808                        .into_iter()
 2809                        .map(|(range, text)| {
 2810                            use text::ToPoint as TP;
 2811                            let end_point = TP::to_point(&range.end, &snapshot);
 2812                            let start_point = TP::to_point(&range.start, &snapshot);
 2813                            (start_point..end_point, text)
 2814                        })
 2815                        .sorted_by_key(|(range, _)| range.start)
 2816                        .collect::<Vec<_>>();
 2817                    buffer.edit(edits, None, cx);
 2818                })
 2819            }
 2820            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2821            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2822            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2823            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2824                .zip(new_selection_deltas)
 2825                .map(|(selection, delta)| Selection {
 2826                    id: selection.id,
 2827                    start: selection.start + delta,
 2828                    end: selection.end + delta,
 2829                    reversed: selection.reversed,
 2830                    goal: SelectionGoal::None,
 2831                })
 2832                .collect::<Vec<_>>();
 2833
 2834            let mut i = 0;
 2835            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2836                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2837                let start = map.buffer_snapshot.anchor_before(position);
 2838                let end = map.buffer_snapshot.anchor_after(position);
 2839                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2840                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2841                        Ordering::Less => i += 1,
 2842                        Ordering::Greater => break,
 2843                        Ordering::Equal => {
 2844                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2845                                Ordering::Less => i += 1,
 2846                                Ordering::Equal => break,
 2847                                Ordering::Greater => break,
 2848                            }
 2849                        }
 2850                    }
 2851                }
 2852                this.autoclose_regions.insert(
 2853                    i,
 2854                    AutocloseRegion {
 2855                        selection_id,
 2856                        range: start..end,
 2857                        pair,
 2858                    },
 2859                );
 2860            }
 2861
 2862            let had_active_inline_completion = this.has_active_inline_completion();
 2863            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2864                s.select(new_selections)
 2865            });
 2866
 2867            if !bracket_inserted {
 2868                if let Some(on_type_format_task) =
 2869                    this.trigger_on_type_formatting(text.to_string(), cx)
 2870                {
 2871                    on_type_format_task.detach_and_log_err(cx);
 2872                }
 2873            }
 2874
 2875            let editor_settings = EditorSettings::get_global(cx);
 2876            if bracket_inserted
 2877                && (editor_settings.auto_signature_help
 2878                    || editor_settings.show_signature_help_after_edits)
 2879            {
 2880                this.show_signature_help(&ShowSignatureHelp, cx);
 2881            }
 2882
 2883            let trigger_in_words =
 2884                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2885            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2886            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2887            this.refresh_inline_completion(true, false, cx);
 2888        });
 2889    }
 2890
 2891    fn find_possible_emoji_shortcode_at_position(
 2892        snapshot: &MultiBufferSnapshot,
 2893        position: Point,
 2894    ) -> Option<String> {
 2895        let mut chars = Vec::new();
 2896        let mut found_colon = false;
 2897        for char in snapshot.reversed_chars_at(position).take(100) {
 2898            // Found a possible emoji shortcode in the middle of the buffer
 2899            if found_colon {
 2900                if char.is_whitespace() {
 2901                    chars.reverse();
 2902                    return Some(chars.iter().collect());
 2903                }
 2904                // If the previous character is not a whitespace, we are in the middle of a word
 2905                // and we only want to complete the shortcode if the word is made up of other emojis
 2906                let mut containing_word = String::new();
 2907                for ch in snapshot
 2908                    .reversed_chars_at(position)
 2909                    .skip(chars.len() + 1)
 2910                    .take(100)
 2911                {
 2912                    if ch.is_whitespace() {
 2913                        break;
 2914                    }
 2915                    containing_word.push(ch);
 2916                }
 2917                let containing_word = containing_word.chars().rev().collect::<String>();
 2918                if util::word_consists_of_emojis(containing_word.as_str()) {
 2919                    chars.reverse();
 2920                    return Some(chars.iter().collect());
 2921                }
 2922            }
 2923
 2924            if char.is_whitespace() || !char.is_ascii() {
 2925                return None;
 2926            }
 2927            if char == ':' {
 2928                found_colon = true;
 2929            } else {
 2930                chars.push(char);
 2931            }
 2932        }
 2933        // Found a possible emoji shortcode at the beginning of the buffer
 2934        chars.reverse();
 2935        Some(chars.iter().collect())
 2936    }
 2937
 2938    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2939        self.transact(cx, |this, cx| {
 2940            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2941                let selections = this.selections.all::<usize>(cx);
 2942                let multi_buffer = this.buffer.read(cx);
 2943                let buffer = multi_buffer.snapshot(cx);
 2944                selections
 2945                    .iter()
 2946                    .map(|selection| {
 2947                        let start_point = selection.start.to_point(&buffer);
 2948                        let mut indent =
 2949                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2950                        indent.len = cmp::min(indent.len, start_point.column);
 2951                        let start = selection.start;
 2952                        let end = selection.end;
 2953                        let selection_is_empty = start == end;
 2954                        let language_scope = buffer.language_scope_at(start);
 2955                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2956                            &language_scope
 2957                        {
 2958                            let leading_whitespace_len = buffer
 2959                                .reversed_chars_at(start)
 2960                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2961                                .map(|c| c.len_utf8())
 2962                                .sum::<usize>();
 2963
 2964                            let trailing_whitespace_len = buffer
 2965                                .chars_at(end)
 2966                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2967                                .map(|c| c.len_utf8())
 2968                                .sum::<usize>();
 2969
 2970                            let insert_extra_newline =
 2971                                language.brackets().any(|(pair, enabled)| {
 2972                                    let pair_start = pair.start.trim_end();
 2973                                    let pair_end = pair.end.trim_start();
 2974
 2975                                    enabled
 2976                                        && pair.newline
 2977                                        && buffer.contains_str_at(
 2978                                            end + trailing_whitespace_len,
 2979                                            pair_end,
 2980                                        )
 2981                                        && buffer.contains_str_at(
 2982                                            (start - leading_whitespace_len)
 2983                                                .saturating_sub(pair_start.len()),
 2984                                            pair_start,
 2985                                        )
 2986                                });
 2987
 2988                            // Comment extension on newline is allowed only for cursor selections
 2989                            let comment_delimiter = maybe!({
 2990                                if !selection_is_empty {
 2991                                    return None;
 2992                                }
 2993
 2994                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 2995                                    return None;
 2996                                }
 2997
 2998                                let delimiters = language.line_comment_prefixes();
 2999                                let max_len_of_delimiter =
 3000                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3001                                let (snapshot, range) =
 3002                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3003
 3004                                let mut index_of_first_non_whitespace = 0;
 3005                                let comment_candidate = snapshot
 3006                                    .chars_for_range(range)
 3007                                    .skip_while(|c| {
 3008                                        let should_skip = c.is_whitespace();
 3009                                        if should_skip {
 3010                                            index_of_first_non_whitespace += 1;
 3011                                        }
 3012                                        should_skip
 3013                                    })
 3014                                    .take(max_len_of_delimiter)
 3015                                    .collect::<String>();
 3016                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3017                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3018                                })?;
 3019                                let cursor_is_placed_after_comment_marker =
 3020                                    index_of_first_non_whitespace + comment_prefix.len()
 3021                                        <= start_point.column as usize;
 3022                                if cursor_is_placed_after_comment_marker {
 3023                                    Some(comment_prefix.clone())
 3024                                } else {
 3025                                    None
 3026                                }
 3027                            });
 3028                            (comment_delimiter, insert_extra_newline)
 3029                        } else {
 3030                            (None, false)
 3031                        };
 3032
 3033                        let capacity_for_delimiter = comment_delimiter
 3034                            .as_deref()
 3035                            .map(str::len)
 3036                            .unwrap_or_default();
 3037                        let mut new_text =
 3038                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3039                        new_text.push('\n');
 3040                        new_text.extend(indent.chars());
 3041                        if let Some(delimiter) = &comment_delimiter {
 3042                            new_text.push_str(delimiter);
 3043                        }
 3044                        if insert_extra_newline {
 3045                            new_text = new_text.repeat(2);
 3046                        }
 3047
 3048                        let anchor = buffer.anchor_after(end);
 3049                        let new_selection = selection.map(|_| anchor);
 3050                        (
 3051                            (start..end, new_text),
 3052                            (insert_extra_newline, new_selection),
 3053                        )
 3054                    })
 3055                    .unzip()
 3056            };
 3057
 3058            this.edit_with_autoindent(edits, cx);
 3059            let buffer = this.buffer.read(cx).snapshot(cx);
 3060            let new_selections = selection_fixup_info
 3061                .into_iter()
 3062                .map(|(extra_newline_inserted, new_selection)| {
 3063                    let mut cursor = new_selection.end.to_point(&buffer);
 3064                    if extra_newline_inserted {
 3065                        cursor.row -= 1;
 3066                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3067                    }
 3068                    new_selection.map(|_| cursor)
 3069                })
 3070                .collect();
 3071
 3072            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3073            this.refresh_inline_completion(true, false, cx);
 3074        });
 3075    }
 3076
 3077    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3078        let buffer = self.buffer.read(cx);
 3079        let snapshot = buffer.snapshot(cx);
 3080
 3081        let mut edits = Vec::new();
 3082        let mut rows = Vec::new();
 3083
 3084        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3085            let cursor = selection.head();
 3086            let row = cursor.row;
 3087
 3088            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3089
 3090            let newline = "\n".to_string();
 3091            edits.push((start_of_line..start_of_line, newline));
 3092
 3093            rows.push(row + rows_inserted as u32);
 3094        }
 3095
 3096        self.transact(cx, |editor, cx| {
 3097            editor.edit(edits, cx);
 3098
 3099            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3100                let mut index = 0;
 3101                s.move_cursors_with(|map, _, _| {
 3102                    let row = rows[index];
 3103                    index += 1;
 3104
 3105                    let point = Point::new(row, 0);
 3106                    let boundary = map.next_line_boundary(point).1;
 3107                    let clipped = map.clip_point(boundary, Bias::Left);
 3108
 3109                    (clipped, SelectionGoal::None)
 3110                });
 3111            });
 3112
 3113            let mut indent_edits = Vec::new();
 3114            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3115            for row in rows {
 3116                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3117                for (row, indent) in indents {
 3118                    if indent.len == 0 {
 3119                        continue;
 3120                    }
 3121
 3122                    let text = match indent.kind {
 3123                        IndentKind::Space => " ".repeat(indent.len as usize),
 3124                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3125                    };
 3126                    let point = Point::new(row.0, 0);
 3127                    indent_edits.push((point..point, text));
 3128                }
 3129            }
 3130            editor.edit(indent_edits, cx);
 3131        });
 3132    }
 3133
 3134    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3135        let buffer = self.buffer.read(cx);
 3136        let snapshot = buffer.snapshot(cx);
 3137
 3138        let mut edits = Vec::new();
 3139        let mut rows = Vec::new();
 3140        let mut rows_inserted = 0;
 3141
 3142        for selection in self.selections.all_adjusted(cx) {
 3143            let cursor = selection.head();
 3144            let row = cursor.row;
 3145
 3146            let point = Point::new(row + 1, 0);
 3147            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3148
 3149            let newline = "\n".to_string();
 3150            edits.push((start_of_line..start_of_line, newline));
 3151
 3152            rows_inserted += 1;
 3153            rows.push(row + rows_inserted);
 3154        }
 3155
 3156        self.transact(cx, |editor, cx| {
 3157            editor.edit(edits, cx);
 3158
 3159            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3160                let mut index = 0;
 3161                s.move_cursors_with(|map, _, _| {
 3162                    let row = rows[index];
 3163                    index += 1;
 3164
 3165                    let point = Point::new(row, 0);
 3166                    let boundary = map.next_line_boundary(point).1;
 3167                    let clipped = map.clip_point(boundary, Bias::Left);
 3168
 3169                    (clipped, SelectionGoal::None)
 3170                });
 3171            });
 3172
 3173            let mut indent_edits = Vec::new();
 3174            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3175            for row in rows {
 3176                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3177                for (row, indent) in indents {
 3178                    if indent.len == 0 {
 3179                        continue;
 3180                    }
 3181
 3182                    let text = match indent.kind {
 3183                        IndentKind::Space => " ".repeat(indent.len as usize),
 3184                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3185                    };
 3186                    let point = Point::new(row.0, 0);
 3187                    indent_edits.push((point..point, text));
 3188                }
 3189            }
 3190            editor.edit(indent_edits, cx);
 3191        });
 3192    }
 3193
 3194    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3195        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3196            original_indent_columns: Vec::new(),
 3197        });
 3198        self.insert_with_autoindent_mode(text, autoindent, cx);
 3199    }
 3200
 3201    fn insert_with_autoindent_mode(
 3202        &mut self,
 3203        text: &str,
 3204        autoindent_mode: Option<AutoindentMode>,
 3205        cx: &mut ViewContext<Self>,
 3206    ) {
 3207        if self.read_only(cx) {
 3208            return;
 3209        }
 3210
 3211        let text: Arc<str> = text.into();
 3212        self.transact(cx, |this, cx| {
 3213            let old_selections = this.selections.all_adjusted(cx);
 3214            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3215                let anchors = {
 3216                    let snapshot = buffer.read(cx);
 3217                    old_selections
 3218                        .iter()
 3219                        .map(|s| {
 3220                            let anchor = snapshot.anchor_after(s.head());
 3221                            s.map(|_| anchor)
 3222                        })
 3223                        .collect::<Vec<_>>()
 3224                };
 3225                buffer.edit(
 3226                    old_selections
 3227                        .iter()
 3228                        .map(|s| (s.start..s.end, text.clone())),
 3229                    autoindent_mode,
 3230                    cx,
 3231                );
 3232                anchors
 3233            });
 3234
 3235            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3236                s.select_anchors(selection_anchors);
 3237            })
 3238        });
 3239    }
 3240
 3241    fn trigger_completion_on_input(
 3242        &mut self,
 3243        text: &str,
 3244        trigger_in_words: bool,
 3245        cx: &mut ViewContext<Self>,
 3246    ) {
 3247        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3248            self.show_completions(
 3249                &ShowCompletions {
 3250                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3251                },
 3252                cx,
 3253            );
 3254        } else {
 3255            self.hide_context_menu(cx);
 3256        }
 3257    }
 3258
 3259    fn is_completion_trigger(
 3260        &self,
 3261        text: &str,
 3262        trigger_in_words: bool,
 3263        cx: &mut ViewContext<Self>,
 3264    ) -> bool {
 3265        let position = self.selections.newest_anchor().head();
 3266        let multibuffer = self.buffer.read(cx);
 3267        let Some(buffer) = position
 3268            .buffer_id
 3269            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3270        else {
 3271            return false;
 3272        };
 3273
 3274        if let Some(completion_provider) = &self.completion_provider {
 3275            completion_provider.is_completion_trigger(
 3276                &buffer,
 3277                position.text_anchor,
 3278                text,
 3279                trigger_in_words,
 3280                cx,
 3281            )
 3282        } else {
 3283            false
 3284        }
 3285    }
 3286
 3287    /// If any empty selections is touching the start of its innermost containing autoclose
 3288    /// region, expand it to select the brackets.
 3289    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3290        let selections = self.selections.all::<usize>(cx);
 3291        let buffer = self.buffer.read(cx).read(cx);
 3292        let new_selections = self
 3293            .selections_with_autoclose_regions(selections, &buffer)
 3294            .map(|(mut selection, region)| {
 3295                if !selection.is_empty() {
 3296                    return selection;
 3297                }
 3298
 3299                if let Some(region) = region {
 3300                    let mut range = region.range.to_offset(&buffer);
 3301                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3302                        range.start -= region.pair.start.len();
 3303                        if buffer.contains_str_at(range.start, &region.pair.start)
 3304                            && buffer.contains_str_at(range.end, &region.pair.end)
 3305                        {
 3306                            range.end += region.pair.end.len();
 3307                            selection.start = range.start;
 3308                            selection.end = range.end;
 3309
 3310                            return selection;
 3311                        }
 3312                    }
 3313                }
 3314
 3315                let always_treat_brackets_as_autoclosed = buffer
 3316                    .settings_at(selection.start, cx)
 3317                    .always_treat_brackets_as_autoclosed;
 3318
 3319                if !always_treat_brackets_as_autoclosed {
 3320                    return selection;
 3321                }
 3322
 3323                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3324                    for (pair, enabled) in scope.brackets() {
 3325                        if !enabled || !pair.close {
 3326                            continue;
 3327                        }
 3328
 3329                        if buffer.contains_str_at(selection.start, &pair.end) {
 3330                            let pair_start_len = pair.start.len();
 3331                            if buffer.contains_str_at(
 3332                                selection.start.saturating_sub(pair_start_len),
 3333                                &pair.start,
 3334                            ) {
 3335                                selection.start -= pair_start_len;
 3336                                selection.end += pair.end.len();
 3337
 3338                                return selection;
 3339                            }
 3340                        }
 3341                    }
 3342                }
 3343
 3344                selection
 3345            })
 3346            .collect();
 3347
 3348        drop(buffer);
 3349        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3350    }
 3351
 3352    /// Iterate the given selections, and for each one, find the smallest surrounding
 3353    /// autoclose region. This uses the ordering of the selections and the autoclose
 3354    /// regions to avoid repeated comparisons.
 3355    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3356        &'a self,
 3357        selections: impl IntoIterator<Item = Selection<D>>,
 3358        buffer: &'a MultiBufferSnapshot,
 3359    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3360        let mut i = 0;
 3361        let mut regions = self.autoclose_regions.as_slice();
 3362        selections.into_iter().map(move |selection| {
 3363            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3364
 3365            let mut enclosing = None;
 3366            while let Some(pair_state) = regions.get(i) {
 3367                if pair_state.range.end.to_offset(buffer) < range.start {
 3368                    regions = &regions[i + 1..];
 3369                    i = 0;
 3370                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3371                    break;
 3372                } else {
 3373                    if pair_state.selection_id == selection.id {
 3374                        enclosing = Some(pair_state);
 3375                    }
 3376                    i += 1;
 3377                }
 3378            }
 3379
 3380            (selection, enclosing)
 3381        })
 3382    }
 3383
 3384    /// Remove any autoclose regions that no longer contain their selection.
 3385    fn invalidate_autoclose_regions(
 3386        &mut self,
 3387        mut selections: &[Selection<Anchor>],
 3388        buffer: &MultiBufferSnapshot,
 3389    ) {
 3390        self.autoclose_regions.retain(|state| {
 3391            let mut i = 0;
 3392            while let Some(selection) = selections.get(i) {
 3393                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3394                    selections = &selections[1..];
 3395                    continue;
 3396                }
 3397                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3398                    break;
 3399                }
 3400                if selection.id == state.selection_id {
 3401                    return true;
 3402                } else {
 3403                    i += 1;
 3404                }
 3405            }
 3406            false
 3407        });
 3408    }
 3409
 3410    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3411        let offset = position.to_offset(buffer);
 3412        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3413        if offset > word_range.start && kind == Some(CharKind::Word) {
 3414            Some(
 3415                buffer
 3416                    .text_for_range(word_range.start..offset)
 3417                    .collect::<String>(),
 3418            )
 3419        } else {
 3420            None
 3421        }
 3422    }
 3423
 3424    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3425        self.refresh_inlay_hints(
 3426            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3427            cx,
 3428        );
 3429    }
 3430
 3431    pub fn inlay_hints_enabled(&self) -> bool {
 3432        self.inlay_hint_cache.enabled
 3433    }
 3434
 3435    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3436        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3437            return;
 3438        }
 3439
 3440        let reason_description = reason.description();
 3441        let ignore_debounce = matches!(
 3442            reason,
 3443            InlayHintRefreshReason::SettingsChange(_)
 3444                | InlayHintRefreshReason::Toggle(_)
 3445                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3446        );
 3447        let (invalidate_cache, required_languages) = match reason {
 3448            InlayHintRefreshReason::Toggle(enabled) => {
 3449                self.inlay_hint_cache.enabled = enabled;
 3450                if enabled {
 3451                    (InvalidationStrategy::RefreshRequested, None)
 3452                } else {
 3453                    self.inlay_hint_cache.clear();
 3454                    self.splice_inlays(
 3455                        self.visible_inlay_hints(cx)
 3456                            .iter()
 3457                            .map(|inlay| inlay.id)
 3458                            .collect(),
 3459                        Vec::new(),
 3460                        cx,
 3461                    );
 3462                    return;
 3463                }
 3464            }
 3465            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3466                match self.inlay_hint_cache.update_settings(
 3467                    &self.buffer,
 3468                    new_settings,
 3469                    self.visible_inlay_hints(cx),
 3470                    cx,
 3471                ) {
 3472                    ControlFlow::Break(Some(InlaySplice {
 3473                        to_remove,
 3474                        to_insert,
 3475                    })) => {
 3476                        self.splice_inlays(to_remove, to_insert, cx);
 3477                        return;
 3478                    }
 3479                    ControlFlow::Break(None) => return,
 3480                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3481                }
 3482            }
 3483            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3484                if let Some(InlaySplice {
 3485                    to_remove,
 3486                    to_insert,
 3487                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3488                {
 3489                    self.splice_inlays(to_remove, to_insert, cx);
 3490                }
 3491                return;
 3492            }
 3493            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3494            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3495                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3496            }
 3497            InlayHintRefreshReason::RefreshRequested => {
 3498                (InvalidationStrategy::RefreshRequested, None)
 3499            }
 3500        };
 3501
 3502        if let Some(InlaySplice {
 3503            to_remove,
 3504            to_insert,
 3505        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3506            reason_description,
 3507            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3508            invalidate_cache,
 3509            ignore_debounce,
 3510            cx,
 3511        ) {
 3512            self.splice_inlays(to_remove, to_insert, cx);
 3513        }
 3514    }
 3515
 3516    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3517        self.display_map
 3518            .read(cx)
 3519            .current_inlays()
 3520            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3521            .cloned()
 3522            .collect()
 3523    }
 3524
 3525    pub fn excerpts_for_inlay_hints_query(
 3526        &self,
 3527        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3528        cx: &mut ViewContext<Editor>,
 3529    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3530        let Some(project) = self.project.as_ref() else {
 3531            return HashMap::default();
 3532        };
 3533        let project = project.read(cx);
 3534        let multi_buffer = self.buffer().read(cx);
 3535        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3536        let multi_buffer_visible_start = self
 3537            .scroll_manager
 3538            .anchor()
 3539            .anchor
 3540            .to_point(&multi_buffer_snapshot);
 3541        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3542            multi_buffer_visible_start
 3543                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3544            Bias::Left,
 3545        );
 3546        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3547        multi_buffer
 3548            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3549            .into_iter()
 3550            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3551            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3552                let buffer = buffer_handle.read(cx);
 3553                let buffer_file = project::File::from_dyn(buffer.file())?;
 3554                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3555                let worktree_entry = buffer_worktree
 3556                    .read(cx)
 3557                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3558                if worktree_entry.is_ignored {
 3559                    return None;
 3560                }
 3561
 3562                let language = buffer.language()?;
 3563                if let Some(restrict_to_languages) = restrict_to_languages {
 3564                    if !restrict_to_languages.contains(language) {
 3565                        return None;
 3566                    }
 3567                }
 3568                Some((
 3569                    excerpt_id,
 3570                    (
 3571                        buffer_handle,
 3572                        buffer.version().clone(),
 3573                        excerpt_visible_range,
 3574                    ),
 3575                ))
 3576            })
 3577            .collect()
 3578    }
 3579
 3580    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3581        TextLayoutDetails {
 3582            text_system: cx.text_system().clone(),
 3583            editor_style: self.style.clone().unwrap(),
 3584            rem_size: cx.rem_size(),
 3585            scroll_anchor: self.scroll_manager.anchor(),
 3586            visible_rows: self.visible_line_count(),
 3587            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3588        }
 3589    }
 3590
 3591    fn splice_inlays(
 3592        &self,
 3593        to_remove: Vec<InlayId>,
 3594        to_insert: Vec<Inlay>,
 3595        cx: &mut ViewContext<Self>,
 3596    ) {
 3597        self.display_map.update(cx, |display_map, cx| {
 3598            display_map.splice_inlays(to_remove, to_insert, cx)
 3599        });
 3600        cx.notify();
 3601    }
 3602
 3603    fn trigger_on_type_formatting(
 3604        &self,
 3605        input: String,
 3606        cx: &mut ViewContext<Self>,
 3607    ) -> Option<Task<Result<()>>> {
 3608        if input.len() != 1 {
 3609            return None;
 3610        }
 3611
 3612        let project = self.project.as_ref()?;
 3613        let position = self.selections.newest_anchor().head();
 3614        let (buffer, buffer_position) = self
 3615            .buffer
 3616            .read(cx)
 3617            .text_anchor_for_position(position, cx)?;
 3618
 3619        let settings = language_settings::language_settings(
 3620            buffer
 3621                .read(cx)
 3622                .language_at(buffer_position)
 3623                .map(|l| l.name()),
 3624            buffer.read(cx).file(),
 3625            cx,
 3626        );
 3627        if !settings.use_on_type_format {
 3628            return None;
 3629        }
 3630
 3631        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3632        // hence we do LSP request & edit on host side only — add formats to host's history.
 3633        let push_to_lsp_host_history = true;
 3634        // If this is not the host, append its history with new edits.
 3635        let push_to_client_history = project.read(cx).is_via_collab();
 3636
 3637        let on_type_formatting = project.update(cx, |project, cx| {
 3638            project.on_type_format(
 3639                buffer.clone(),
 3640                buffer_position,
 3641                input,
 3642                push_to_lsp_host_history,
 3643                cx,
 3644            )
 3645        });
 3646        Some(cx.spawn(|editor, mut cx| async move {
 3647            if let Some(transaction) = on_type_formatting.await? {
 3648                if push_to_client_history {
 3649                    buffer
 3650                        .update(&mut cx, |buffer, _| {
 3651                            buffer.push_transaction(transaction, Instant::now());
 3652                        })
 3653                        .ok();
 3654                }
 3655                editor.update(&mut cx, |editor, cx| {
 3656                    editor.refresh_document_highlights(cx);
 3657                })?;
 3658            }
 3659            Ok(())
 3660        }))
 3661    }
 3662
 3663    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3664        if self.pending_rename.is_some() {
 3665            return;
 3666        }
 3667
 3668        let Some(provider) = self.completion_provider.as_ref() else {
 3669            return;
 3670        };
 3671
 3672        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3673            return;
 3674        }
 3675
 3676        let position = self.selections.newest_anchor().head();
 3677        let (buffer, buffer_position) =
 3678            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3679                output
 3680            } else {
 3681                return;
 3682            };
 3683        let show_completion_documentation = buffer
 3684            .read(cx)
 3685            .snapshot()
 3686            .settings_at(buffer_position, cx)
 3687            .show_completion_documentation;
 3688
 3689        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3690
 3691        let trigger_kind = match &options.trigger {
 3692            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3693                CompletionTriggerKind::TRIGGER_CHARACTER
 3694            }
 3695            _ => CompletionTriggerKind::INVOKED,
 3696        };
 3697        let completion_context = CompletionContext {
 3698            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3699                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3700                    Some(String::from(trigger))
 3701                } else {
 3702                    None
 3703                }
 3704            }),
 3705            trigger_kind,
 3706        };
 3707        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3708        let sort_completions = provider.sort_completions();
 3709
 3710        let id = post_inc(&mut self.next_completion_id);
 3711        let task = cx.spawn(|editor, mut cx| {
 3712            async move {
 3713                editor.update(&mut cx, |this, _| {
 3714                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3715                })?;
 3716                let completions = completions.await.log_err();
 3717                let menu = if let Some(completions) = completions {
 3718                    let mut menu = CompletionsMenu::new(
 3719                        id,
 3720                        sort_completions,
 3721                        show_completion_documentation,
 3722                        position,
 3723                        buffer.clone(),
 3724                        completions.into(),
 3725                    );
 3726
 3727                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3728                        .await;
 3729
 3730                    menu.visible().then_some(menu)
 3731                } else {
 3732                    None
 3733                };
 3734
 3735                editor.update(&mut cx, |editor, cx| {
 3736                    match editor.context_menu.borrow().as_ref() {
 3737                        None => {}
 3738                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3739                            if prev_menu.id > id {
 3740                                return;
 3741                            }
 3742                        }
 3743                        _ => return,
 3744                    }
 3745
 3746                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3747                        let mut menu = menu.unwrap();
 3748                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3749
 3750                        if editor.show_inline_completions_in_menu(cx) {
 3751                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3752                                menu.show_inline_completion_hint(hint);
 3753                            }
 3754                        } else {
 3755                            editor.discard_inline_completion(false, cx);
 3756                        }
 3757
 3758                        *editor.context_menu.borrow_mut() =
 3759                            Some(CodeContextMenu::Completions(menu));
 3760
 3761                        cx.notify();
 3762                    } else if editor.completion_tasks.len() <= 1 {
 3763                        // If there are no more completion tasks and the last menu was
 3764                        // empty, we should hide it.
 3765                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3766                        // If it was already hidden and we don't show inline
 3767                        // completions in the menu, we should also show the
 3768                        // inline-completion when available.
 3769                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3770                            editor.update_visible_inline_completion(cx);
 3771                        }
 3772                    }
 3773                })?;
 3774
 3775                Ok::<_, anyhow::Error>(())
 3776            }
 3777            .log_err()
 3778        });
 3779
 3780        self.completion_tasks.push((id, task));
 3781    }
 3782
 3783    pub fn confirm_completion(
 3784        &mut self,
 3785        action: &ConfirmCompletion,
 3786        cx: &mut ViewContext<Self>,
 3787    ) -> Option<Task<Result<()>>> {
 3788        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3789    }
 3790
 3791    pub fn compose_completion(
 3792        &mut self,
 3793        action: &ComposeCompletion,
 3794        cx: &mut ViewContext<Self>,
 3795    ) -> Option<Task<Result<()>>> {
 3796        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3797    }
 3798
 3799    fn do_completion(
 3800        &mut self,
 3801        item_ix: Option<usize>,
 3802        intent: CompletionIntent,
 3803        cx: &mut ViewContext<Editor>,
 3804    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3805        use language::ToOffset as _;
 3806
 3807        let completions_menu =
 3808            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3809                menu
 3810            } else {
 3811                return None;
 3812            };
 3813
 3814        let mat = completions_menu
 3815            .entries
 3816            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3817
 3818        let mat = match mat {
 3819            CompletionEntry::InlineCompletionHint { .. } => {
 3820                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3821                cx.stop_propagation();
 3822                return Some(Task::ready(Ok(())));
 3823            }
 3824            CompletionEntry::Match(mat) => {
 3825                if self.show_inline_completions_in_menu(cx) {
 3826                    self.discard_inline_completion(true, cx);
 3827                }
 3828                mat
 3829            }
 3830        };
 3831
 3832        let buffer_handle = completions_menu.buffer;
 3833        let completion = completions_menu
 3834            .completions
 3835            .borrow()
 3836            .get(mat.candidate_id)?
 3837            .clone();
 3838        cx.stop_propagation();
 3839
 3840        let snippet;
 3841        let text;
 3842
 3843        if completion.is_snippet() {
 3844            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3845            text = snippet.as_ref().unwrap().text.clone();
 3846        } else {
 3847            snippet = None;
 3848            text = completion.new_text.clone();
 3849        };
 3850        let selections = self.selections.all::<usize>(cx);
 3851        let buffer = buffer_handle.read(cx);
 3852        let old_range = completion.old_range.to_offset(buffer);
 3853        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3854
 3855        let newest_selection = self.selections.newest_anchor();
 3856        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3857            return None;
 3858        }
 3859
 3860        let lookbehind = newest_selection
 3861            .start
 3862            .text_anchor
 3863            .to_offset(buffer)
 3864            .saturating_sub(old_range.start);
 3865        let lookahead = old_range
 3866            .end
 3867            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3868        let mut common_prefix_len = old_text
 3869            .bytes()
 3870            .zip(text.bytes())
 3871            .take_while(|(a, b)| a == b)
 3872            .count();
 3873
 3874        let snapshot = self.buffer.read(cx).snapshot(cx);
 3875        let mut range_to_replace: Option<Range<isize>> = None;
 3876        let mut ranges = Vec::new();
 3877        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3878        for selection in &selections {
 3879            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3880                let start = selection.start.saturating_sub(lookbehind);
 3881                let end = selection.end + lookahead;
 3882                if selection.id == newest_selection.id {
 3883                    range_to_replace = Some(
 3884                        ((start + common_prefix_len) as isize - selection.start as isize)
 3885                            ..(end as isize - selection.start as isize),
 3886                    );
 3887                }
 3888                ranges.push(start + common_prefix_len..end);
 3889            } else {
 3890                common_prefix_len = 0;
 3891                ranges.clear();
 3892                ranges.extend(selections.iter().map(|s| {
 3893                    if s.id == newest_selection.id {
 3894                        range_to_replace = Some(
 3895                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3896                                - selection.start as isize
 3897                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3898                                    - selection.start as isize,
 3899                        );
 3900                        old_range.clone()
 3901                    } else {
 3902                        s.start..s.end
 3903                    }
 3904                }));
 3905                break;
 3906            }
 3907            if !self.linked_edit_ranges.is_empty() {
 3908                let start_anchor = snapshot.anchor_before(selection.head());
 3909                let end_anchor = snapshot.anchor_after(selection.tail());
 3910                if let Some(ranges) = self
 3911                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3912                {
 3913                    for (buffer, edits) in ranges {
 3914                        linked_edits.entry(buffer.clone()).or_default().extend(
 3915                            edits
 3916                                .into_iter()
 3917                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3918                        );
 3919                    }
 3920                }
 3921            }
 3922        }
 3923        let text = &text[common_prefix_len..];
 3924
 3925        cx.emit(EditorEvent::InputHandled {
 3926            utf16_range_to_replace: range_to_replace,
 3927            text: text.into(),
 3928        });
 3929
 3930        self.transact(cx, |this, cx| {
 3931            if let Some(mut snippet) = snippet {
 3932                snippet.text = text.to_string();
 3933                for tabstop in snippet
 3934                    .tabstops
 3935                    .iter_mut()
 3936                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3937                {
 3938                    tabstop.start -= common_prefix_len as isize;
 3939                    tabstop.end -= common_prefix_len as isize;
 3940                }
 3941
 3942                this.insert_snippet(&ranges, snippet, cx).log_err();
 3943            } else {
 3944                this.buffer.update(cx, |buffer, cx| {
 3945                    buffer.edit(
 3946                        ranges.iter().map(|range| (range.clone(), text)),
 3947                        this.autoindent_mode.clone(),
 3948                        cx,
 3949                    );
 3950                });
 3951            }
 3952            for (buffer, edits) in linked_edits {
 3953                buffer.update(cx, |buffer, cx| {
 3954                    let snapshot = buffer.snapshot();
 3955                    let edits = edits
 3956                        .into_iter()
 3957                        .map(|(range, text)| {
 3958                            use text::ToPoint as TP;
 3959                            let end_point = TP::to_point(&range.end, &snapshot);
 3960                            let start_point = TP::to_point(&range.start, &snapshot);
 3961                            (start_point..end_point, text)
 3962                        })
 3963                        .sorted_by_key(|(range, _)| range.start)
 3964                        .collect::<Vec<_>>();
 3965                    buffer.edit(edits, None, cx);
 3966                })
 3967            }
 3968
 3969            this.refresh_inline_completion(true, false, cx);
 3970        });
 3971
 3972        let show_new_completions_on_confirm = completion
 3973            .confirm
 3974            .as_ref()
 3975            .map_or(false, |confirm| confirm(intent, cx));
 3976        if show_new_completions_on_confirm {
 3977            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3978        }
 3979
 3980        let provider = self.completion_provider.as_ref()?;
 3981        drop(completion);
 3982        let apply_edits = provider.apply_additional_edits_for_completion(
 3983            buffer_handle,
 3984            completions_menu.completions.clone(),
 3985            mat.candidate_id,
 3986            true,
 3987            cx,
 3988        );
 3989
 3990        let editor_settings = EditorSettings::get_global(cx);
 3991        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3992            // After the code completion is finished, users often want to know what signatures are needed.
 3993            // so we should automatically call signature_help
 3994            self.show_signature_help(&ShowSignatureHelp, cx);
 3995        }
 3996
 3997        Some(cx.foreground_executor().spawn(async move {
 3998            apply_edits.await?;
 3999            Ok(())
 4000        }))
 4001    }
 4002
 4003    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4004        let mut context_menu = self.context_menu.borrow_mut();
 4005        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4006            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4007                // Toggle if we're selecting the same one
 4008                *context_menu = None;
 4009                cx.notify();
 4010                return;
 4011            } else {
 4012                // Otherwise, clear it and start a new one
 4013                *context_menu = None;
 4014                cx.notify();
 4015            }
 4016        }
 4017        drop(context_menu);
 4018        let snapshot = self.snapshot(cx);
 4019        let deployed_from_indicator = action.deployed_from_indicator;
 4020        let mut task = self.code_actions_task.take();
 4021        let action = action.clone();
 4022        cx.spawn(|editor, mut cx| async move {
 4023            while let Some(prev_task) = task {
 4024                prev_task.await.log_err();
 4025                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4026            }
 4027
 4028            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4029                if editor.focus_handle.is_focused(cx) {
 4030                    let multibuffer_point = action
 4031                        .deployed_from_indicator
 4032                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4033                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4034                    let (buffer, buffer_row) = snapshot
 4035                        .buffer_snapshot
 4036                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4037                        .and_then(|(buffer_snapshot, range)| {
 4038                            editor
 4039                                .buffer
 4040                                .read(cx)
 4041                                .buffer(buffer_snapshot.remote_id())
 4042                                .map(|buffer| (buffer, range.start.row))
 4043                        })?;
 4044                    let (_, code_actions) = editor
 4045                        .available_code_actions
 4046                        .clone()
 4047                        .and_then(|(location, code_actions)| {
 4048                            let snapshot = location.buffer.read(cx).snapshot();
 4049                            let point_range = location.range.to_point(&snapshot);
 4050                            let point_range = point_range.start.row..=point_range.end.row;
 4051                            if point_range.contains(&buffer_row) {
 4052                                Some((location, code_actions))
 4053                            } else {
 4054                                None
 4055                            }
 4056                        })
 4057                        .unzip();
 4058                    let buffer_id = buffer.read(cx).remote_id();
 4059                    let tasks = editor
 4060                        .tasks
 4061                        .get(&(buffer_id, buffer_row))
 4062                        .map(|t| Arc::new(t.to_owned()));
 4063                    if tasks.is_none() && code_actions.is_none() {
 4064                        return None;
 4065                    }
 4066
 4067                    editor.completion_tasks.clear();
 4068                    editor.discard_inline_completion(false, cx);
 4069                    let task_context =
 4070                        tasks
 4071                            .as_ref()
 4072                            .zip(editor.project.clone())
 4073                            .map(|(tasks, project)| {
 4074                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4075                            });
 4076
 4077                    Some(cx.spawn(|editor, mut cx| async move {
 4078                        let task_context = match task_context {
 4079                            Some(task_context) => task_context.await,
 4080                            None => None,
 4081                        };
 4082                        let resolved_tasks =
 4083                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4084                                Rc::new(ResolvedTasks {
 4085                                    templates: tasks.resolve(&task_context).collect(),
 4086                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4087                                        multibuffer_point.row,
 4088                                        tasks.column,
 4089                                    )),
 4090                                })
 4091                            });
 4092                        let spawn_straight_away = resolved_tasks
 4093                            .as_ref()
 4094                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4095                            && code_actions
 4096                                .as_ref()
 4097                                .map_or(true, |actions| actions.is_empty());
 4098                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4099                            *editor.context_menu.borrow_mut() =
 4100                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4101                                    buffer,
 4102                                    actions: CodeActionContents {
 4103                                        tasks: resolved_tasks,
 4104                                        actions: code_actions,
 4105                                    },
 4106                                    selected_item: Default::default(),
 4107                                    scroll_handle: UniformListScrollHandle::default(),
 4108                                    deployed_from_indicator,
 4109                                }));
 4110                            if spawn_straight_away {
 4111                                if let Some(task) = editor.confirm_code_action(
 4112                                    &ConfirmCodeAction { item_ix: Some(0) },
 4113                                    cx,
 4114                                ) {
 4115                                    cx.notify();
 4116                                    return task;
 4117                                }
 4118                            }
 4119                            cx.notify();
 4120                            Task::ready(Ok(()))
 4121                        }) {
 4122                            task.await
 4123                        } else {
 4124                            Ok(())
 4125                        }
 4126                    }))
 4127                } else {
 4128                    Some(Task::ready(Ok(())))
 4129                }
 4130            })?;
 4131            if let Some(task) = spawned_test_task {
 4132                task.await?;
 4133            }
 4134
 4135            Ok::<_, anyhow::Error>(())
 4136        })
 4137        .detach_and_log_err(cx);
 4138    }
 4139
 4140    pub fn confirm_code_action(
 4141        &mut self,
 4142        action: &ConfirmCodeAction,
 4143        cx: &mut ViewContext<Self>,
 4144    ) -> Option<Task<Result<()>>> {
 4145        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4146            menu
 4147        } else {
 4148            return None;
 4149        };
 4150        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4151        let action = actions_menu.actions.get(action_ix)?;
 4152        let title = action.label();
 4153        let buffer = actions_menu.buffer;
 4154        let workspace = self.workspace()?;
 4155
 4156        match action {
 4157            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4158                workspace.update(cx, |workspace, cx| {
 4159                    workspace::tasks::schedule_resolved_task(
 4160                        workspace,
 4161                        task_source_kind,
 4162                        resolved_task,
 4163                        false,
 4164                        cx,
 4165                    );
 4166
 4167                    Some(Task::ready(Ok(())))
 4168                })
 4169            }
 4170            CodeActionsItem::CodeAction {
 4171                excerpt_id,
 4172                action,
 4173                provider,
 4174            } => {
 4175                let apply_code_action =
 4176                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4177                let workspace = workspace.downgrade();
 4178                Some(cx.spawn(|editor, cx| async move {
 4179                    let project_transaction = apply_code_action.await?;
 4180                    Self::open_project_transaction(
 4181                        &editor,
 4182                        workspace,
 4183                        project_transaction,
 4184                        title,
 4185                        cx,
 4186                    )
 4187                    .await
 4188                }))
 4189            }
 4190        }
 4191    }
 4192
 4193    pub async fn open_project_transaction(
 4194        this: &WeakView<Editor>,
 4195        workspace: WeakView<Workspace>,
 4196        transaction: ProjectTransaction,
 4197        title: String,
 4198        mut cx: AsyncWindowContext,
 4199    ) -> Result<()> {
 4200        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4201        cx.update(|cx| {
 4202            entries.sort_unstable_by_key(|(buffer, _)| {
 4203                buffer.read(cx).file().map(|f| f.path().clone())
 4204            });
 4205        })?;
 4206
 4207        // If the project transaction's edits are all contained within this editor, then
 4208        // avoid opening a new editor to display them.
 4209
 4210        if let Some((buffer, transaction)) = entries.first() {
 4211            if entries.len() == 1 {
 4212                let excerpt = this.update(&mut cx, |editor, cx| {
 4213                    editor
 4214                        .buffer()
 4215                        .read(cx)
 4216                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4217                })?;
 4218                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4219                    if excerpted_buffer == *buffer {
 4220                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4221                            let excerpt_range = excerpt_range.to_offset(buffer);
 4222                            buffer
 4223                                .edited_ranges_for_transaction::<usize>(transaction)
 4224                                .all(|range| {
 4225                                    excerpt_range.start <= range.start
 4226                                        && excerpt_range.end >= range.end
 4227                                })
 4228                        })?;
 4229
 4230                        if all_edits_within_excerpt {
 4231                            return Ok(());
 4232                        }
 4233                    }
 4234                }
 4235            }
 4236        } else {
 4237            return Ok(());
 4238        }
 4239
 4240        let mut ranges_to_highlight = Vec::new();
 4241        let excerpt_buffer = cx.new_model(|cx| {
 4242            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4243            for (buffer_handle, transaction) in &entries {
 4244                let buffer = buffer_handle.read(cx);
 4245                ranges_to_highlight.extend(
 4246                    multibuffer.push_excerpts_with_context_lines(
 4247                        buffer_handle.clone(),
 4248                        buffer
 4249                            .edited_ranges_for_transaction::<usize>(transaction)
 4250                            .collect(),
 4251                        DEFAULT_MULTIBUFFER_CONTEXT,
 4252                        cx,
 4253                    ),
 4254                );
 4255            }
 4256            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4257            multibuffer
 4258        })?;
 4259
 4260        workspace.update(&mut cx, |workspace, cx| {
 4261            let project = workspace.project().clone();
 4262            let editor =
 4263                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4264            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4265            editor.update(cx, |editor, cx| {
 4266                editor.highlight_background::<Self>(
 4267                    &ranges_to_highlight,
 4268                    |theme| theme.editor_highlighted_line_background,
 4269                    cx,
 4270                );
 4271            });
 4272        })?;
 4273
 4274        Ok(())
 4275    }
 4276
 4277    pub fn clear_code_action_providers(&mut self) {
 4278        self.code_action_providers.clear();
 4279        self.available_code_actions.take();
 4280    }
 4281
 4282    pub fn push_code_action_provider(
 4283        &mut self,
 4284        provider: Rc<dyn CodeActionProvider>,
 4285        cx: &mut ViewContext<Self>,
 4286    ) {
 4287        self.code_action_providers.push(provider);
 4288        self.refresh_code_actions(cx);
 4289    }
 4290
 4291    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4292        let buffer = self.buffer.read(cx);
 4293        let newest_selection = self.selections.newest_anchor().clone();
 4294        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4295        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4296        if start_buffer != end_buffer {
 4297            return None;
 4298        }
 4299
 4300        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4301            cx.background_executor()
 4302                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4303                .await;
 4304
 4305            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4306                let providers = this.code_action_providers.clone();
 4307                let tasks = this
 4308                    .code_action_providers
 4309                    .iter()
 4310                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4311                    .collect::<Vec<_>>();
 4312                (providers, tasks)
 4313            })?;
 4314
 4315            let mut actions = Vec::new();
 4316            for (provider, provider_actions) in
 4317                providers.into_iter().zip(future::join_all(tasks).await)
 4318            {
 4319                if let Some(provider_actions) = provider_actions.log_err() {
 4320                    actions.extend(provider_actions.into_iter().map(|action| {
 4321                        AvailableCodeAction {
 4322                            excerpt_id: newest_selection.start.excerpt_id,
 4323                            action,
 4324                            provider: provider.clone(),
 4325                        }
 4326                    }));
 4327                }
 4328            }
 4329
 4330            this.update(&mut cx, |this, cx| {
 4331                this.available_code_actions = if actions.is_empty() {
 4332                    None
 4333                } else {
 4334                    Some((
 4335                        Location {
 4336                            buffer: start_buffer,
 4337                            range: start..end,
 4338                        },
 4339                        actions.into(),
 4340                    ))
 4341                };
 4342                cx.notify();
 4343            })
 4344        }));
 4345        None
 4346    }
 4347
 4348    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4349        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4350            self.show_git_blame_inline = false;
 4351
 4352            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4353                cx.background_executor().timer(delay).await;
 4354
 4355                this.update(&mut cx, |this, cx| {
 4356                    this.show_git_blame_inline = true;
 4357                    cx.notify();
 4358                })
 4359                .log_err();
 4360            }));
 4361        }
 4362    }
 4363
 4364    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4365        if self.pending_rename.is_some() {
 4366            return None;
 4367        }
 4368
 4369        let provider = self.semantics_provider.clone()?;
 4370        let buffer = self.buffer.read(cx);
 4371        let newest_selection = self.selections.newest_anchor().clone();
 4372        let cursor_position = newest_selection.head();
 4373        let (cursor_buffer, cursor_buffer_position) =
 4374            buffer.text_anchor_for_position(cursor_position, cx)?;
 4375        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4376        if cursor_buffer != tail_buffer {
 4377            return None;
 4378        }
 4379        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4380        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4381            cx.background_executor()
 4382                .timer(Duration::from_millis(debounce))
 4383                .await;
 4384
 4385            let highlights = if let Some(highlights) = cx
 4386                .update(|cx| {
 4387                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4388                })
 4389                .ok()
 4390                .flatten()
 4391            {
 4392                highlights.await.log_err()
 4393            } else {
 4394                None
 4395            };
 4396
 4397            if let Some(highlights) = highlights {
 4398                this.update(&mut cx, |this, cx| {
 4399                    if this.pending_rename.is_some() {
 4400                        return;
 4401                    }
 4402
 4403                    let buffer_id = cursor_position.buffer_id;
 4404                    let buffer = this.buffer.read(cx);
 4405                    if !buffer
 4406                        .text_anchor_for_position(cursor_position, cx)
 4407                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4408                    {
 4409                        return;
 4410                    }
 4411
 4412                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4413                    let mut write_ranges = Vec::new();
 4414                    let mut read_ranges = Vec::new();
 4415                    for highlight in highlights {
 4416                        for (excerpt_id, excerpt_range) in
 4417                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4418                        {
 4419                            let start = highlight
 4420                                .range
 4421                                .start
 4422                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4423                            let end = highlight
 4424                                .range
 4425                                .end
 4426                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4427                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4428                                continue;
 4429                            }
 4430
 4431                            let range = Anchor {
 4432                                buffer_id,
 4433                                excerpt_id,
 4434                                text_anchor: start,
 4435                            }..Anchor {
 4436                                buffer_id,
 4437                                excerpt_id,
 4438                                text_anchor: end,
 4439                            };
 4440                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4441                                write_ranges.push(range);
 4442                            } else {
 4443                                read_ranges.push(range);
 4444                            }
 4445                        }
 4446                    }
 4447
 4448                    this.highlight_background::<DocumentHighlightRead>(
 4449                        &read_ranges,
 4450                        |theme| theme.editor_document_highlight_read_background,
 4451                        cx,
 4452                    );
 4453                    this.highlight_background::<DocumentHighlightWrite>(
 4454                        &write_ranges,
 4455                        |theme| theme.editor_document_highlight_write_background,
 4456                        cx,
 4457                    );
 4458                    cx.notify();
 4459                })
 4460                .log_err();
 4461            }
 4462        }));
 4463        None
 4464    }
 4465
 4466    pub fn refresh_inline_completion(
 4467        &mut self,
 4468        debounce: bool,
 4469        user_requested: bool,
 4470        cx: &mut ViewContext<Self>,
 4471    ) -> Option<()> {
 4472        let provider = self.inline_completion_provider()?;
 4473        let cursor = self.selections.newest_anchor().head();
 4474        let (buffer, cursor_buffer_position) =
 4475            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4476
 4477        if !user_requested
 4478            && (!self.enable_inline_completions
 4479                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4480                || !self.is_focused(cx))
 4481        {
 4482            self.discard_inline_completion(false, cx);
 4483            return None;
 4484        }
 4485
 4486        self.update_visible_inline_completion(cx);
 4487        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4488        Some(())
 4489    }
 4490
 4491    fn cycle_inline_completion(
 4492        &mut self,
 4493        direction: Direction,
 4494        cx: &mut ViewContext<Self>,
 4495    ) -> Option<()> {
 4496        let provider = self.inline_completion_provider()?;
 4497        let cursor = self.selections.newest_anchor().head();
 4498        let (buffer, cursor_buffer_position) =
 4499            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4500        if !self.enable_inline_completions
 4501            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4502        {
 4503            return None;
 4504        }
 4505
 4506        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4507        self.update_visible_inline_completion(cx);
 4508
 4509        Some(())
 4510    }
 4511
 4512    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4513        if !self.has_active_inline_completion() {
 4514            self.refresh_inline_completion(false, true, cx);
 4515            return;
 4516        }
 4517
 4518        self.update_visible_inline_completion(cx);
 4519    }
 4520
 4521    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4522        self.show_cursor_names(cx);
 4523    }
 4524
 4525    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4526        self.show_cursor_names = true;
 4527        cx.notify();
 4528        cx.spawn(|this, mut cx| async move {
 4529            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4530            this.update(&mut cx, |this, cx| {
 4531                this.show_cursor_names = false;
 4532                cx.notify()
 4533            })
 4534            .ok()
 4535        })
 4536        .detach();
 4537    }
 4538
 4539    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4540        if self.has_active_inline_completion() {
 4541            self.cycle_inline_completion(Direction::Next, cx);
 4542        } else {
 4543            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4544            if is_copilot_disabled {
 4545                cx.propagate();
 4546            }
 4547        }
 4548    }
 4549
 4550    pub fn previous_inline_completion(
 4551        &mut self,
 4552        _: &PreviousInlineCompletion,
 4553        cx: &mut ViewContext<Self>,
 4554    ) {
 4555        if self.has_active_inline_completion() {
 4556            self.cycle_inline_completion(Direction::Prev, cx);
 4557        } else {
 4558            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4559            if is_copilot_disabled {
 4560                cx.propagate();
 4561            }
 4562        }
 4563    }
 4564
 4565    pub fn accept_inline_completion(
 4566        &mut self,
 4567        _: &AcceptInlineCompletion,
 4568        cx: &mut ViewContext<Self>,
 4569    ) {
 4570        if self.show_inline_completions_in_menu(cx) {
 4571            self.hide_context_menu(cx);
 4572        }
 4573
 4574        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4575            return;
 4576        };
 4577
 4578        self.report_inline_completion_event(true, cx);
 4579
 4580        match &active_inline_completion.completion {
 4581            InlineCompletion::Move(position) => {
 4582                let position = *position;
 4583                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4584                    selections.select_anchor_ranges([position..position]);
 4585                });
 4586            }
 4587            InlineCompletion::Edit(edits) => {
 4588                if let Some(provider) = self.inline_completion_provider() {
 4589                    provider.accept(cx);
 4590                }
 4591
 4592                let snapshot = self.buffer.read(cx).snapshot(cx);
 4593                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4594
 4595                self.buffer.update(cx, |buffer, cx| {
 4596                    buffer.edit(edits.iter().cloned(), None, cx)
 4597                });
 4598
 4599                self.change_selections(None, cx, |s| {
 4600                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4601                });
 4602
 4603                self.update_visible_inline_completion(cx);
 4604                if self.active_inline_completion.is_none() {
 4605                    self.refresh_inline_completion(true, true, cx);
 4606                }
 4607
 4608                cx.notify();
 4609            }
 4610        }
 4611    }
 4612
 4613    pub fn accept_partial_inline_completion(
 4614        &mut self,
 4615        _: &AcceptPartialInlineCompletion,
 4616        cx: &mut ViewContext<Self>,
 4617    ) {
 4618        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4619            return;
 4620        };
 4621        if self.selections.count() != 1 {
 4622            return;
 4623        }
 4624
 4625        self.report_inline_completion_event(true, cx);
 4626
 4627        match &active_inline_completion.completion {
 4628            InlineCompletion::Move(position) => {
 4629                let position = *position;
 4630                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4631                    selections.select_anchor_ranges([position..position]);
 4632                });
 4633            }
 4634            InlineCompletion::Edit(edits) => {
 4635                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4636                    let text = edits[0].1.as_str();
 4637                    let mut partial_completion = text
 4638                        .chars()
 4639                        .by_ref()
 4640                        .take_while(|c| c.is_alphabetic())
 4641                        .collect::<String>();
 4642                    if partial_completion.is_empty() {
 4643                        partial_completion = text
 4644                            .chars()
 4645                            .by_ref()
 4646                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4647                            .collect::<String>();
 4648                    }
 4649
 4650                    cx.emit(EditorEvent::InputHandled {
 4651                        utf16_range_to_replace: None,
 4652                        text: partial_completion.clone().into(),
 4653                    });
 4654
 4655                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4656
 4657                    self.refresh_inline_completion(true, true, cx);
 4658                    cx.notify();
 4659                }
 4660            }
 4661        }
 4662    }
 4663
 4664    fn discard_inline_completion(
 4665        &mut self,
 4666        should_report_inline_completion_event: bool,
 4667        cx: &mut ViewContext<Self>,
 4668    ) -> bool {
 4669        if should_report_inline_completion_event {
 4670            self.report_inline_completion_event(false, cx);
 4671        }
 4672
 4673        if let Some(provider) = self.inline_completion_provider() {
 4674            provider.discard(cx);
 4675        }
 4676
 4677        self.take_active_inline_completion(cx).is_some()
 4678    }
 4679
 4680    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4681        let Some(provider) = self.inline_completion_provider() else {
 4682            return;
 4683        };
 4684        let Some(project) = self.project.as_ref() else {
 4685            return;
 4686        };
 4687        let Some((_, buffer, _)) = self
 4688            .buffer
 4689            .read(cx)
 4690            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4691        else {
 4692            return;
 4693        };
 4694
 4695        let project = project.read(cx);
 4696        let extension = buffer
 4697            .read(cx)
 4698            .file()
 4699            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4700        project.client().telemetry().report_inline_completion_event(
 4701            provider.name().into(),
 4702            accepted,
 4703            extension,
 4704        );
 4705    }
 4706
 4707    pub fn has_active_inline_completion(&self) -> bool {
 4708        self.active_inline_completion.is_some()
 4709    }
 4710
 4711    fn take_active_inline_completion(
 4712        &mut self,
 4713        cx: &mut ViewContext<Self>,
 4714    ) -> Option<InlineCompletion> {
 4715        let active_inline_completion = self.active_inline_completion.take()?;
 4716        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4717        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4718        Some(active_inline_completion.completion)
 4719    }
 4720
 4721    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4722        let selection = self.selections.newest_anchor();
 4723        let cursor = selection.head();
 4724        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4725        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4726        let excerpt_id = cursor.excerpt_id;
 4727
 4728        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4729            && (self.context_menu.borrow().is_some()
 4730                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4731        if completions_menu_has_precedence
 4732            || !offset_selection.is_empty()
 4733            || self
 4734                .active_inline_completion
 4735                .as_ref()
 4736                .map_or(false, |completion| {
 4737                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4738                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4739                    !invalidation_range.contains(&offset_selection.head())
 4740                })
 4741        {
 4742            self.discard_inline_completion(false, cx);
 4743            return None;
 4744        }
 4745
 4746        self.take_active_inline_completion(cx);
 4747        let provider = self.inline_completion_provider()?;
 4748
 4749        let (buffer, cursor_buffer_position) =
 4750            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4751
 4752        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4753        let edits = completion
 4754            .edits
 4755            .into_iter()
 4756            .flat_map(|(range, new_text)| {
 4757                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4758                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4759                Some((start..end, new_text))
 4760            })
 4761            .collect::<Vec<_>>();
 4762        if edits.is_empty() {
 4763            return None;
 4764        }
 4765
 4766        let first_edit_start = edits.first().unwrap().0.start;
 4767        let edit_start_row = first_edit_start
 4768            .to_point(&multibuffer)
 4769            .row
 4770            .saturating_sub(2);
 4771
 4772        let last_edit_end = edits.last().unwrap().0.end;
 4773        let edit_end_row = cmp::min(
 4774            multibuffer.max_point().row,
 4775            last_edit_end.to_point(&multibuffer).row + 2,
 4776        );
 4777
 4778        let cursor_row = cursor.to_point(&multibuffer).row;
 4779
 4780        let mut inlay_ids = Vec::new();
 4781        let invalidation_row_range;
 4782        let completion;
 4783        if cursor_row < edit_start_row {
 4784            invalidation_row_range = cursor_row..edit_end_row;
 4785            completion = InlineCompletion::Move(first_edit_start);
 4786        } else if cursor_row > edit_end_row {
 4787            invalidation_row_range = edit_start_row..cursor_row;
 4788            completion = InlineCompletion::Move(first_edit_start);
 4789        } else {
 4790            if edits
 4791                .iter()
 4792                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4793            {
 4794                let mut inlays = Vec::new();
 4795                for (range, new_text) in &edits {
 4796                    let inlay = Inlay::inline_completion(
 4797                        post_inc(&mut self.next_inlay_id),
 4798                        range.start,
 4799                        new_text.as_str(),
 4800                    );
 4801                    inlay_ids.push(inlay.id);
 4802                    inlays.push(inlay);
 4803                }
 4804
 4805                self.splice_inlays(vec![], inlays, cx);
 4806            } else {
 4807                let background_color = cx.theme().status().deleted_background;
 4808                self.highlight_text::<InlineCompletionHighlight>(
 4809                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4810                    HighlightStyle {
 4811                        background_color: Some(background_color),
 4812                        ..Default::default()
 4813                    },
 4814                    cx,
 4815                );
 4816            }
 4817
 4818            invalidation_row_range = edit_start_row..edit_end_row;
 4819            completion = InlineCompletion::Edit(edits);
 4820        };
 4821
 4822        let invalidation_range = multibuffer
 4823            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4824            ..multibuffer.anchor_after(Point::new(
 4825                invalidation_row_range.end,
 4826                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4827            ));
 4828
 4829        self.active_inline_completion = Some(InlineCompletionState {
 4830            inlay_ids,
 4831            completion,
 4832            invalidation_range,
 4833        });
 4834
 4835        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4836            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4837                match self.context_menu.borrow_mut().as_mut() {
 4838                    Some(CodeContextMenu::Completions(menu)) => {
 4839                        menu.show_inline_completion_hint(hint);
 4840                    }
 4841                    _ => {}
 4842                }
 4843            }
 4844        }
 4845
 4846        cx.notify();
 4847
 4848        Some(())
 4849    }
 4850
 4851    fn inline_completion_menu_hint(
 4852        &mut self,
 4853        cx: &mut ViewContext<Self>,
 4854    ) -> Option<InlineCompletionMenuHint> {
 4855        if self.has_active_inline_completion() {
 4856            let provider_name = self.inline_completion_provider()?.display_name();
 4857            let editor_snapshot = self.snapshot(cx);
 4858
 4859            let text = match &self.active_inline_completion.as_ref()?.completion {
 4860                InlineCompletion::Edit(edits) => {
 4861                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4862                }
 4863                InlineCompletion::Move(target) => {
 4864                    let target_point =
 4865                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4866                    let target_line = target_point.row + 1;
 4867                    InlineCompletionText::Move(
 4868                        format!("Jump to edit in line {}", target_line).into(),
 4869                    )
 4870                }
 4871            };
 4872
 4873            Some(InlineCompletionMenuHint {
 4874                provider_name,
 4875                text,
 4876            })
 4877        } else {
 4878            None
 4879        }
 4880    }
 4881
 4882    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4883        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4884    }
 4885
 4886    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4887        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4888            && self
 4889                .inline_completion_provider()
 4890                .map_or(false, |provider| provider.show_completions_in_menu())
 4891    }
 4892
 4893    fn render_code_actions_indicator(
 4894        &self,
 4895        _style: &EditorStyle,
 4896        row: DisplayRow,
 4897        is_active: bool,
 4898        cx: &mut ViewContext<Self>,
 4899    ) -> Option<IconButton> {
 4900        if self.available_code_actions.is_some() {
 4901            Some(
 4902                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4903                    .shape(ui::IconButtonShape::Square)
 4904                    .icon_size(IconSize::XSmall)
 4905                    .icon_color(Color::Muted)
 4906                    .toggle_state(is_active)
 4907                    .tooltip({
 4908                        let focus_handle = self.focus_handle.clone();
 4909                        move |cx| {
 4910                            Tooltip::for_action_in(
 4911                                "Toggle Code Actions",
 4912                                &ToggleCodeActions {
 4913                                    deployed_from_indicator: None,
 4914                                },
 4915                                &focus_handle,
 4916                                cx,
 4917                            )
 4918                        }
 4919                    })
 4920                    .on_click(cx.listener(move |editor, _e, cx| {
 4921                        editor.focus(cx);
 4922                        editor.toggle_code_actions(
 4923                            &ToggleCodeActions {
 4924                                deployed_from_indicator: Some(row),
 4925                            },
 4926                            cx,
 4927                        );
 4928                    })),
 4929            )
 4930        } else {
 4931            None
 4932        }
 4933    }
 4934
 4935    fn clear_tasks(&mut self) {
 4936        self.tasks.clear()
 4937    }
 4938
 4939    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4940        if self.tasks.insert(key, value).is_some() {
 4941            // This case should hopefully be rare, but just in case...
 4942            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4943        }
 4944    }
 4945
 4946    fn build_tasks_context(
 4947        project: &Model<Project>,
 4948        buffer: &Model<Buffer>,
 4949        buffer_row: u32,
 4950        tasks: &Arc<RunnableTasks>,
 4951        cx: &mut ViewContext<Self>,
 4952    ) -> Task<Option<task::TaskContext>> {
 4953        let position = Point::new(buffer_row, tasks.column);
 4954        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4955        let location = Location {
 4956            buffer: buffer.clone(),
 4957            range: range_start..range_start,
 4958        };
 4959        // Fill in the environmental variables from the tree-sitter captures
 4960        let mut captured_task_variables = TaskVariables::default();
 4961        for (capture_name, value) in tasks.extra_variables.clone() {
 4962            captured_task_variables.insert(
 4963                task::VariableName::Custom(capture_name.into()),
 4964                value.clone(),
 4965            );
 4966        }
 4967        project.update(cx, |project, cx| {
 4968            project.task_store().update(cx, |task_store, cx| {
 4969                task_store.task_context_for_location(captured_task_variables, location, cx)
 4970            })
 4971        })
 4972    }
 4973
 4974    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4975        let Some((workspace, _)) = self.workspace.clone() else {
 4976            return;
 4977        };
 4978        let Some(project) = self.project.clone() else {
 4979            return;
 4980        };
 4981
 4982        // Try to find a closest, enclosing node using tree-sitter that has a
 4983        // task
 4984        let Some((buffer, buffer_row, tasks)) = self
 4985            .find_enclosing_node_task(cx)
 4986            // Or find the task that's closest in row-distance.
 4987            .or_else(|| self.find_closest_task(cx))
 4988        else {
 4989            return;
 4990        };
 4991
 4992        let reveal_strategy = action.reveal;
 4993        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 4994        cx.spawn(|_, mut cx| async move {
 4995            let context = task_context.await?;
 4996            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 4997
 4998            let resolved = resolved_task.resolved.as_mut()?;
 4999            resolved.reveal = reveal_strategy;
 5000
 5001            workspace
 5002                .update(&mut cx, |workspace, cx| {
 5003                    workspace::tasks::schedule_resolved_task(
 5004                        workspace,
 5005                        task_source_kind,
 5006                        resolved_task,
 5007                        false,
 5008                        cx,
 5009                    );
 5010                })
 5011                .ok()
 5012        })
 5013        .detach();
 5014    }
 5015
 5016    fn find_closest_task(
 5017        &mut self,
 5018        cx: &mut ViewContext<Self>,
 5019    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5020        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5021
 5022        let ((buffer_id, row), tasks) = self
 5023            .tasks
 5024            .iter()
 5025            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5026
 5027        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5028        let tasks = Arc::new(tasks.to_owned());
 5029        Some((buffer, *row, tasks))
 5030    }
 5031
 5032    fn find_enclosing_node_task(
 5033        &mut self,
 5034        cx: &mut ViewContext<Self>,
 5035    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5036        let snapshot = self.buffer.read(cx).snapshot(cx);
 5037        let offset = self.selections.newest::<usize>(cx).head();
 5038        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5039        let buffer_id = excerpt.buffer().remote_id();
 5040
 5041        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5042        let mut cursor = layer.node().walk();
 5043
 5044        while cursor.goto_first_child_for_byte(offset).is_some() {
 5045            if cursor.node().end_byte() == offset {
 5046                cursor.goto_next_sibling();
 5047            }
 5048        }
 5049
 5050        // Ascend to the smallest ancestor that contains the range and has a task.
 5051        loop {
 5052            let node = cursor.node();
 5053            let node_range = node.byte_range();
 5054            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5055
 5056            // Check if this node contains our offset
 5057            if node_range.start <= offset && node_range.end >= offset {
 5058                // If it contains offset, check for task
 5059                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5060                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5061                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5062                }
 5063            }
 5064
 5065            if !cursor.goto_parent() {
 5066                break;
 5067            }
 5068        }
 5069        None
 5070    }
 5071
 5072    fn render_run_indicator(
 5073        &self,
 5074        _style: &EditorStyle,
 5075        is_active: bool,
 5076        row: DisplayRow,
 5077        cx: &mut ViewContext<Self>,
 5078    ) -> IconButton {
 5079        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5080            .shape(ui::IconButtonShape::Square)
 5081            .icon_size(IconSize::XSmall)
 5082            .icon_color(Color::Muted)
 5083            .toggle_state(is_active)
 5084            .on_click(cx.listener(move |editor, _e, cx| {
 5085                editor.focus(cx);
 5086                editor.toggle_code_actions(
 5087                    &ToggleCodeActions {
 5088                        deployed_from_indicator: Some(row),
 5089                    },
 5090                    cx,
 5091                );
 5092            }))
 5093    }
 5094
 5095    #[cfg(any(feature = "test-support", test))]
 5096    pub fn context_menu_visible(&self) -> bool {
 5097        self.context_menu
 5098            .borrow()
 5099            .as_ref()
 5100            .map_or(false, |menu| menu.visible())
 5101    }
 5102
 5103    #[cfg(feature = "test-support")]
 5104    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5105        self.context_menu
 5106            .borrow()
 5107            .as_ref()
 5108            .map_or(false, |menu| match menu {
 5109                CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
 5110                    matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5111                }),
 5112                CodeContextMenu::CodeActions(_) => false,
 5113            })
 5114    }
 5115
 5116    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5117        self.context_menu
 5118            .borrow()
 5119            .as_ref()
 5120            .map(|menu| menu.origin(cursor_position))
 5121    }
 5122
 5123    fn render_context_menu(
 5124        &self,
 5125        style: &EditorStyle,
 5126        max_height_in_lines: u32,
 5127        cx: &mut ViewContext<Editor>,
 5128    ) -> Option<AnyElement> {
 5129        self.context_menu.borrow().as_ref().and_then(|menu| {
 5130            if menu.visible() {
 5131                Some(menu.render(style, max_height_in_lines, cx))
 5132            } else {
 5133                None
 5134            }
 5135        })
 5136    }
 5137
 5138    fn render_context_menu_aside(
 5139        &self,
 5140        style: &EditorStyle,
 5141        max_size: Size<Pixels>,
 5142        cx: &mut ViewContext<Editor>,
 5143    ) -> Option<AnyElement> {
 5144        self.context_menu.borrow().as_ref().and_then(|menu| {
 5145            if menu.visible() {
 5146                menu.render_aside(
 5147                    style,
 5148                    max_size,
 5149                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5150                    cx,
 5151                )
 5152            } else {
 5153                None
 5154            }
 5155        })
 5156    }
 5157
 5158    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5159        cx.notify();
 5160        self.completion_tasks.clear();
 5161        let context_menu = self.context_menu.borrow_mut().take();
 5162        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5163            self.update_visible_inline_completion(cx);
 5164        }
 5165        context_menu
 5166    }
 5167
 5168    fn show_snippet_choices(
 5169        &mut self,
 5170        choices: &Vec<String>,
 5171        selection: Range<Anchor>,
 5172        cx: &mut ViewContext<Self>,
 5173    ) {
 5174        if selection.start.buffer_id.is_none() {
 5175            return;
 5176        }
 5177        let buffer_id = selection.start.buffer_id.unwrap();
 5178        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5179        let id = post_inc(&mut self.next_completion_id);
 5180
 5181        if let Some(buffer) = buffer {
 5182            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5183                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5184            ));
 5185        }
 5186    }
 5187
 5188    pub fn insert_snippet(
 5189        &mut self,
 5190        insertion_ranges: &[Range<usize>],
 5191        snippet: Snippet,
 5192        cx: &mut ViewContext<Self>,
 5193    ) -> Result<()> {
 5194        struct Tabstop<T> {
 5195            is_end_tabstop: bool,
 5196            ranges: Vec<Range<T>>,
 5197            choices: Option<Vec<String>>,
 5198        }
 5199
 5200        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5201            let snippet_text: Arc<str> = snippet.text.clone().into();
 5202            buffer.edit(
 5203                insertion_ranges
 5204                    .iter()
 5205                    .cloned()
 5206                    .map(|range| (range, snippet_text.clone())),
 5207                Some(AutoindentMode::EachLine),
 5208                cx,
 5209            );
 5210
 5211            let snapshot = &*buffer.read(cx);
 5212            let snippet = &snippet;
 5213            snippet
 5214                .tabstops
 5215                .iter()
 5216                .map(|tabstop| {
 5217                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5218                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5219                    });
 5220                    let mut tabstop_ranges = tabstop
 5221                        .ranges
 5222                        .iter()
 5223                        .flat_map(|tabstop_range| {
 5224                            let mut delta = 0_isize;
 5225                            insertion_ranges.iter().map(move |insertion_range| {
 5226                                let insertion_start = insertion_range.start as isize + delta;
 5227                                delta +=
 5228                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5229
 5230                                let start = ((insertion_start + tabstop_range.start) as usize)
 5231                                    .min(snapshot.len());
 5232                                let end = ((insertion_start + tabstop_range.end) as usize)
 5233                                    .min(snapshot.len());
 5234                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5235                            })
 5236                        })
 5237                        .collect::<Vec<_>>();
 5238                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5239
 5240                    Tabstop {
 5241                        is_end_tabstop,
 5242                        ranges: tabstop_ranges,
 5243                        choices: tabstop.choices.clone(),
 5244                    }
 5245                })
 5246                .collect::<Vec<_>>()
 5247        });
 5248        if let Some(tabstop) = tabstops.first() {
 5249            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5250                s.select_ranges(tabstop.ranges.iter().cloned());
 5251            });
 5252
 5253            if let Some(choices) = &tabstop.choices {
 5254                if let Some(selection) = tabstop.ranges.first() {
 5255                    self.show_snippet_choices(choices, selection.clone(), cx)
 5256                }
 5257            }
 5258
 5259            // If we're already at the last tabstop and it's at the end of the snippet,
 5260            // we're done, we don't need to keep the state around.
 5261            if !tabstop.is_end_tabstop {
 5262                let choices = tabstops
 5263                    .iter()
 5264                    .map(|tabstop| tabstop.choices.clone())
 5265                    .collect();
 5266
 5267                let ranges = tabstops
 5268                    .into_iter()
 5269                    .map(|tabstop| tabstop.ranges)
 5270                    .collect::<Vec<_>>();
 5271
 5272                self.snippet_stack.push(SnippetState {
 5273                    active_index: 0,
 5274                    ranges,
 5275                    choices,
 5276                });
 5277            }
 5278
 5279            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5280            if self.autoclose_regions.is_empty() {
 5281                let snapshot = self.buffer.read(cx).snapshot(cx);
 5282                for selection in &mut self.selections.all::<Point>(cx) {
 5283                    let selection_head = selection.head();
 5284                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5285                        continue;
 5286                    };
 5287
 5288                    let mut bracket_pair = None;
 5289                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5290                    let prev_chars = snapshot
 5291                        .reversed_chars_at(selection_head)
 5292                        .collect::<String>();
 5293                    for (pair, enabled) in scope.brackets() {
 5294                        if enabled
 5295                            && pair.close
 5296                            && prev_chars.starts_with(pair.start.as_str())
 5297                            && next_chars.starts_with(pair.end.as_str())
 5298                        {
 5299                            bracket_pair = Some(pair.clone());
 5300                            break;
 5301                        }
 5302                    }
 5303                    if let Some(pair) = bracket_pair {
 5304                        let start = snapshot.anchor_after(selection_head);
 5305                        let end = snapshot.anchor_after(selection_head);
 5306                        self.autoclose_regions.push(AutocloseRegion {
 5307                            selection_id: selection.id,
 5308                            range: start..end,
 5309                            pair,
 5310                        });
 5311                    }
 5312                }
 5313            }
 5314        }
 5315        Ok(())
 5316    }
 5317
 5318    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5319        self.move_to_snippet_tabstop(Bias::Right, cx)
 5320    }
 5321
 5322    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5323        self.move_to_snippet_tabstop(Bias::Left, cx)
 5324    }
 5325
 5326    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5327        if let Some(mut snippet) = self.snippet_stack.pop() {
 5328            match bias {
 5329                Bias::Left => {
 5330                    if snippet.active_index > 0 {
 5331                        snippet.active_index -= 1;
 5332                    } else {
 5333                        self.snippet_stack.push(snippet);
 5334                        return false;
 5335                    }
 5336                }
 5337                Bias::Right => {
 5338                    if snippet.active_index + 1 < snippet.ranges.len() {
 5339                        snippet.active_index += 1;
 5340                    } else {
 5341                        self.snippet_stack.push(snippet);
 5342                        return false;
 5343                    }
 5344                }
 5345            }
 5346            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5347                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5348                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5349                });
 5350
 5351                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5352                    if let Some(selection) = current_ranges.first() {
 5353                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5354                    }
 5355                }
 5356
 5357                // If snippet state is not at the last tabstop, push it back on the stack
 5358                if snippet.active_index + 1 < snippet.ranges.len() {
 5359                    self.snippet_stack.push(snippet);
 5360                }
 5361                return true;
 5362            }
 5363        }
 5364
 5365        false
 5366    }
 5367
 5368    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5369        self.transact(cx, |this, cx| {
 5370            this.select_all(&SelectAll, cx);
 5371            this.insert("", cx);
 5372        });
 5373    }
 5374
 5375    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5376        self.transact(cx, |this, cx| {
 5377            this.select_autoclose_pair(cx);
 5378            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5379            if !this.linked_edit_ranges.is_empty() {
 5380                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5381                let snapshot = this.buffer.read(cx).snapshot(cx);
 5382
 5383                for selection in selections.iter() {
 5384                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5385                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5386                    if selection_start.buffer_id != selection_end.buffer_id {
 5387                        continue;
 5388                    }
 5389                    if let Some(ranges) =
 5390                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5391                    {
 5392                        for (buffer, entries) in ranges {
 5393                            linked_ranges.entry(buffer).or_default().extend(entries);
 5394                        }
 5395                    }
 5396                }
 5397            }
 5398
 5399            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5400            if !this.selections.line_mode {
 5401                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5402                for selection in &mut selections {
 5403                    if selection.is_empty() {
 5404                        let old_head = selection.head();
 5405                        let mut new_head =
 5406                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5407                                .to_point(&display_map);
 5408                        if let Some((buffer, line_buffer_range)) = display_map
 5409                            .buffer_snapshot
 5410                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5411                        {
 5412                            let indent_size =
 5413                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5414                            let indent_len = match indent_size.kind {
 5415                                IndentKind::Space => {
 5416                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5417                                }
 5418                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5419                            };
 5420                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5421                                let indent_len = indent_len.get();
 5422                                new_head = cmp::min(
 5423                                    new_head,
 5424                                    MultiBufferPoint::new(
 5425                                        old_head.row,
 5426                                        ((old_head.column - 1) / indent_len) * indent_len,
 5427                                    ),
 5428                                );
 5429                            }
 5430                        }
 5431
 5432                        selection.set_head(new_head, SelectionGoal::None);
 5433                    }
 5434                }
 5435            }
 5436
 5437            this.signature_help_state.set_backspace_pressed(true);
 5438            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5439            this.insert("", cx);
 5440            let empty_str: Arc<str> = Arc::from("");
 5441            for (buffer, edits) in linked_ranges {
 5442                let snapshot = buffer.read(cx).snapshot();
 5443                use text::ToPoint as TP;
 5444
 5445                let edits = edits
 5446                    .into_iter()
 5447                    .map(|range| {
 5448                        let end_point = TP::to_point(&range.end, &snapshot);
 5449                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5450
 5451                        if end_point == start_point {
 5452                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5453                                .saturating_sub(1);
 5454                            start_point =
 5455                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5456                        };
 5457
 5458                        (start_point..end_point, empty_str.clone())
 5459                    })
 5460                    .sorted_by_key(|(range, _)| range.start)
 5461                    .collect::<Vec<_>>();
 5462                buffer.update(cx, |this, cx| {
 5463                    this.edit(edits, None, cx);
 5464                })
 5465            }
 5466            this.refresh_inline_completion(true, false, cx);
 5467            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5468        });
 5469    }
 5470
 5471    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5472        self.transact(cx, |this, cx| {
 5473            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5474                let line_mode = s.line_mode;
 5475                s.move_with(|map, selection| {
 5476                    if selection.is_empty() && !line_mode {
 5477                        let cursor = movement::right(map, selection.head());
 5478                        selection.end = cursor;
 5479                        selection.reversed = true;
 5480                        selection.goal = SelectionGoal::None;
 5481                    }
 5482                })
 5483            });
 5484            this.insert("", cx);
 5485            this.refresh_inline_completion(true, false, cx);
 5486        });
 5487    }
 5488
 5489    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5490        if self.move_to_prev_snippet_tabstop(cx) {
 5491            return;
 5492        }
 5493
 5494        self.outdent(&Outdent, cx);
 5495    }
 5496
 5497    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5498        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5499            return;
 5500        }
 5501
 5502        let mut selections = self.selections.all_adjusted(cx);
 5503        let buffer = self.buffer.read(cx);
 5504        let snapshot = buffer.snapshot(cx);
 5505        let rows_iter = selections.iter().map(|s| s.head().row);
 5506        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5507
 5508        let mut edits = Vec::new();
 5509        let mut prev_edited_row = 0;
 5510        let mut row_delta = 0;
 5511        for selection in &mut selections {
 5512            if selection.start.row != prev_edited_row {
 5513                row_delta = 0;
 5514            }
 5515            prev_edited_row = selection.end.row;
 5516
 5517            // If the selection is non-empty, then increase the indentation of the selected lines.
 5518            if !selection.is_empty() {
 5519                row_delta =
 5520                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5521                continue;
 5522            }
 5523
 5524            // If the selection is empty and the cursor is in the leading whitespace before the
 5525            // suggested indentation, then auto-indent the line.
 5526            let cursor = selection.head();
 5527            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5528            if let Some(suggested_indent) =
 5529                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5530            {
 5531                if cursor.column < suggested_indent.len
 5532                    && cursor.column <= current_indent.len
 5533                    && current_indent.len <= suggested_indent.len
 5534                {
 5535                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5536                    selection.end = selection.start;
 5537                    if row_delta == 0 {
 5538                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5539                            cursor.row,
 5540                            current_indent,
 5541                            suggested_indent,
 5542                        ));
 5543                        row_delta = suggested_indent.len - current_indent.len;
 5544                    }
 5545                    continue;
 5546                }
 5547            }
 5548
 5549            // Otherwise, insert a hard or soft tab.
 5550            let settings = buffer.settings_at(cursor, cx);
 5551            let tab_size = if settings.hard_tabs {
 5552                IndentSize::tab()
 5553            } else {
 5554                let tab_size = settings.tab_size.get();
 5555                let char_column = snapshot
 5556                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5557                    .flat_map(str::chars)
 5558                    .count()
 5559                    + row_delta as usize;
 5560                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5561                IndentSize::spaces(chars_to_next_tab_stop)
 5562            };
 5563            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5564            selection.end = selection.start;
 5565            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5566            row_delta += tab_size.len;
 5567        }
 5568
 5569        self.transact(cx, |this, cx| {
 5570            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5571            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5572            this.refresh_inline_completion(true, false, cx);
 5573        });
 5574    }
 5575
 5576    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5577        if self.read_only(cx) {
 5578            return;
 5579        }
 5580        let mut selections = self.selections.all::<Point>(cx);
 5581        let mut prev_edited_row = 0;
 5582        let mut row_delta = 0;
 5583        let mut edits = Vec::new();
 5584        let buffer = self.buffer.read(cx);
 5585        let snapshot = buffer.snapshot(cx);
 5586        for selection in &mut selections {
 5587            if selection.start.row != prev_edited_row {
 5588                row_delta = 0;
 5589            }
 5590            prev_edited_row = selection.end.row;
 5591
 5592            row_delta =
 5593                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5594        }
 5595
 5596        self.transact(cx, |this, cx| {
 5597            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5598            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5599        });
 5600    }
 5601
 5602    fn indent_selection(
 5603        buffer: &MultiBuffer,
 5604        snapshot: &MultiBufferSnapshot,
 5605        selection: &mut Selection<Point>,
 5606        edits: &mut Vec<(Range<Point>, String)>,
 5607        delta_for_start_row: u32,
 5608        cx: &AppContext,
 5609    ) -> u32 {
 5610        let settings = buffer.settings_at(selection.start, cx);
 5611        let tab_size = settings.tab_size.get();
 5612        let indent_kind = if settings.hard_tabs {
 5613            IndentKind::Tab
 5614        } else {
 5615            IndentKind::Space
 5616        };
 5617        let mut start_row = selection.start.row;
 5618        let mut end_row = selection.end.row + 1;
 5619
 5620        // If a selection ends at the beginning of a line, don't indent
 5621        // that last line.
 5622        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5623            end_row -= 1;
 5624        }
 5625
 5626        // Avoid re-indenting a row that has already been indented by a
 5627        // previous selection, but still update this selection's column
 5628        // to reflect that indentation.
 5629        if delta_for_start_row > 0 {
 5630            start_row += 1;
 5631            selection.start.column += delta_for_start_row;
 5632            if selection.end.row == selection.start.row {
 5633                selection.end.column += delta_for_start_row;
 5634            }
 5635        }
 5636
 5637        let mut delta_for_end_row = 0;
 5638        let has_multiple_rows = start_row + 1 != end_row;
 5639        for row in start_row..end_row {
 5640            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5641            let indent_delta = match (current_indent.kind, indent_kind) {
 5642                (IndentKind::Space, IndentKind::Space) => {
 5643                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5644                    IndentSize::spaces(columns_to_next_tab_stop)
 5645                }
 5646                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5647                (_, IndentKind::Tab) => IndentSize::tab(),
 5648            };
 5649
 5650            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5651                0
 5652            } else {
 5653                selection.start.column
 5654            };
 5655            let row_start = Point::new(row, start);
 5656            edits.push((
 5657                row_start..row_start,
 5658                indent_delta.chars().collect::<String>(),
 5659            ));
 5660
 5661            // Update this selection's endpoints to reflect the indentation.
 5662            if row == selection.start.row {
 5663                selection.start.column += indent_delta.len;
 5664            }
 5665            if row == selection.end.row {
 5666                selection.end.column += indent_delta.len;
 5667                delta_for_end_row = indent_delta.len;
 5668            }
 5669        }
 5670
 5671        if selection.start.row == selection.end.row {
 5672            delta_for_start_row + delta_for_end_row
 5673        } else {
 5674            delta_for_end_row
 5675        }
 5676    }
 5677
 5678    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5679        if self.read_only(cx) {
 5680            return;
 5681        }
 5682        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5683        let selections = self.selections.all::<Point>(cx);
 5684        let mut deletion_ranges = Vec::new();
 5685        let mut last_outdent = None;
 5686        {
 5687            let buffer = self.buffer.read(cx);
 5688            let snapshot = buffer.snapshot(cx);
 5689            for selection in &selections {
 5690                let settings = buffer.settings_at(selection.start, cx);
 5691                let tab_size = settings.tab_size.get();
 5692                let mut rows = selection.spanned_rows(false, &display_map);
 5693
 5694                // Avoid re-outdenting a row that has already been outdented by a
 5695                // previous selection.
 5696                if let Some(last_row) = last_outdent {
 5697                    if last_row == rows.start {
 5698                        rows.start = rows.start.next_row();
 5699                    }
 5700                }
 5701                let has_multiple_rows = rows.len() > 1;
 5702                for row in rows.iter_rows() {
 5703                    let indent_size = snapshot.indent_size_for_line(row);
 5704                    if indent_size.len > 0 {
 5705                        let deletion_len = match indent_size.kind {
 5706                            IndentKind::Space => {
 5707                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5708                                if columns_to_prev_tab_stop == 0 {
 5709                                    tab_size
 5710                                } else {
 5711                                    columns_to_prev_tab_stop
 5712                                }
 5713                            }
 5714                            IndentKind::Tab => 1,
 5715                        };
 5716                        let start = if has_multiple_rows
 5717                            || deletion_len > selection.start.column
 5718                            || indent_size.len < selection.start.column
 5719                        {
 5720                            0
 5721                        } else {
 5722                            selection.start.column - deletion_len
 5723                        };
 5724                        deletion_ranges.push(
 5725                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5726                        );
 5727                        last_outdent = Some(row);
 5728                    }
 5729                }
 5730            }
 5731        }
 5732
 5733        self.transact(cx, |this, cx| {
 5734            this.buffer.update(cx, |buffer, cx| {
 5735                let empty_str: Arc<str> = Arc::default();
 5736                buffer.edit(
 5737                    deletion_ranges
 5738                        .into_iter()
 5739                        .map(|range| (range, empty_str.clone())),
 5740                    None,
 5741                    cx,
 5742                );
 5743            });
 5744            let selections = this.selections.all::<usize>(cx);
 5745            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5746        });
 5747    }
 5748
 5749    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5750        if self.read_only(cx) {
 5751            return;
 5752        }
 5753        let selections = self
 5754            .selections
 5755            .all::<usize>(cx)
 5756            .into_iter()
 5757            .map(|s| s.range());
 5758
 5759        self.transact(cx, |this, cx| {
 5760            this.buffer.update(cx, |buffer, cx| {
 5761                buffer.autoindent_ranges(selections, cx);
 5762            });
 5763            let selections = this.selections.all::<usize>(cx);
 5764            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5765        });
 5766    }
 5767
 5768    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5769        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5770        let selections = self.selections.all::<Point>(cx);
 5771
 5772        let mut new_cursors = Vec::new();
 5773        let mut edit_ranges = Vec::new();
 5774        let mut selections = selections.iter().peekable();
 5775        while let Some(selection) = selections.next() {
 5776            let mut rows = selection.spanned_rows(false, &display_map);
 5777            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5778
 5779            // Accumulate contiguous regions of rows that we want to delete.
 5780            while let Some(next_selection) = selections.peek() {
 5781                let next_rows = next_selection.spanned_rows(false, &display_map);
 5782                if next_rows.start <= rows.end {
 5783                    rows.end = next_rows.end;
 5784                    selections.next().unwrap();
 5785                } else {
 5786                    break;
 5787                }
 5788            }
 5789
 5790            let buffer = &display_map.buffer_snapshot;
 5791            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5792            let edit_end;
 5793            let cursor_buffer_row;
 5794            if buffer.max_point().row >= rows.end.0 {
 5795                // If there's a line after the range, delete the \n from the end of the row range
 5796                // and position the cursor on the next line.
 5797                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5798                cursor_buffer_row = rows.end;
 5799            } else {
 5800                // If there isn't a line after the range, delete the \n from the line before the
 5801                // start of the row range and position the cursor there.
 5802                edit_start = edit_start.saturating_sub(1);
 5803                edit_end = buffer.len();
 5804                cursor_buffer_row = rows.start.previous_row();
 5805            }
 5806
 5807            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5808            *cursor.column_mut() =
 5809                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5810
 5811            new_cursors.push((
 5812                selection.id,
 5813                buffer.anchor_after(cursor.to_point(&display_map)),
 5814            ));
 5815            edit_ranges.push(edit_start..edit_end);
 5816        }
 5817
 5818        self.transact(cx, |this, cx| {
 5819            let buffer = this.buffer.update(cx, |buffer, cx| {
 5820                let empty_str: Arc<str> = Arc::default();
 5821                buffer.edit(
 5822                    edit_ranges
 5823                        .into_iter()
 5824                        .map(|range| (range, empty_str.clone())),
 5825                    None,
 5826                    cx,
 5827                );
 5828                buffer.snapshot(cx)
 5829            });
 5830            let new_selections = new_cursors
 5831                .into_iter()
 5832                .map(|(id, cursor)| {
 5833                    let cursor = cursor.to_point(&buffer);
 5834                    Selection {
 5835                        id,
 5836                        start: cursor,
 5837                        end: cursor,
 5838                        reversed: false,
 5839                        goal: SelectionGoal::None,
 5840                    }
 5841                })
 5842                .collect();
 5843
 5844            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5845                s.select(new_selections);
 5846            });
 5847        });
 5848    }
 5849
 5850    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5851        if self.read_only(cx) {
 5852            return;
 5853        }
 5854        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5855        for selection in self.selections.all::<Point>(cx) {
 5856            let start = MultiBufferRow(selection.start.row);
 5857            // Treat single line selections as if they include the next line. Otherwise this action
 5858            // would do nothing for single line selections individual cursors.
 5859            let end = if selection.start.row == selection.end.row {
 5860                MultiBufferRow(selection.start.row + 1)
 5861            } else {
 5862                MultiBufferRow(selection.end.row)
 5863            };
 5864
 5865            if let Some(last_row_range) = row_ranges.last_mut() {
 5866                if start <= last_row_range.end {
 5867                    last_row_range.end = end;
 5868                    continue;
 5869                }
 5870            }
 5871            row_ranges.push(start..end);
 5872        }
 5873
 5874        let snapshot = self.buffer.read(cx).snapshot(cx);
 5875        let mut cursor_positions = Vec::new();
 5876        for row_range in &row_ranges {
 5877            let anchor = snapshot.anchor_before(Point::new(
 5878                row_range.end.previous_row().0,
 5879                snapshot.line_len(row_range.end.previous_row()),
 5880            ));
 5881            cursor_positions.push(anchor..anchor);
 5882        }
 5883
 5884        self.transact(cx, |this, cx| {
 5885            for row_range in row_ranges.into_iter().rev() {
 5886                for row in row_range.iter_rows().rev() {
 5887                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5888                    let next_line_row = row.next_row();
 5889                    let indent = snapshot.indent_size_for_line(next_line_row);
 5890                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5891
 5892                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5893                        " "
 5894                    } else {
 5895                        ""
 5896                    };
 5897
 5898                    this.buffer.update(cx, |buffer, cx| {
 5899                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5900                    });
 5901                }
 5902            }
 5903
 5904            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5905                s.select_anchor_ranges(cursor_positions)
 5906            });
 5907        });
 5908    }
 5909
 5910    pub fn sort_lines_case_sensitive(
 5911        &mut self,
 5912        _: &SortLinesCaseSensitive,
 5913        cx: &mut ViewContext<Self>,
 5914    ) {
 5915        self.manipulate_lines(cx, |lines| lines.sort())
 5916    }
 5917
 5918    pub fn sort_lines_case_insensitive(
 5919        &mut self,
 5920        _: &SortLinesCaseInsensitive,
 5921        cx: &mut ViewContext<Self>,
 5922    ) {
 5923        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5924    }
 5925
 5926    pub fn unique_lines_case_insensitive(
 5927        &mut self,
 5928        _: &UniqueLinesCaseInsensitive,
 5929        cx: &mut ViewContext<Self>,
 5930    ) {
 5931        self.manipulate_lines(cx, |lines| {
 5932            let mut seen = HashSet::default();
 5933            lines.retain(|line| seen.insert(line.to_lowercase()));
 5934        })
 5935    }
 5936
 5937    pub fn unique_lines_case_sensitive(
 5938        &mut self,
 5939        _: &UniqueLinesCaseSensitive,
 5940        cx: &mut ViewContext<Self>,
 5941    ) {
 5942        self.manipulate_lines(cx, |lines| {
 5943            let mut seen = HashSet::default();
 5944            lines.retain(|line| seen.insert(*line));
 5945        })
 5946    }
 5947
 5948    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5949        let mut revert_changes = HashMap::default();
 5950        let snapshot = self.snapshot(cx);
 5951        for hunk in hunks_for_ranges(
 5952            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5953            &snapshot,
 5954        ) {
 5955            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5956        }
 5957        if !revert_changes.is_empty() {
 5958            self.transact(cx, |editor, cx| {
 5959                editor.revert(revert_changes, cx);
 5960            });
 5961        }
 5962    }
 5963
 5964    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5965        let Some(project) = self.project.clone() else {
 5966            return;
 5967        };
 5968        self.reload(project, cx).detach_and_notify_err(cx);
 5969    }
 5970
 5971    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5972        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5973        if !revert_changes.is_empty() {
 5974            self.transact(cx, |editor, cx| {
 5975                editor.revert(revert_changes, cx);
 5976            });
 5977        }
 5978    }
 5979
 5980    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5981        let snapshot = self.buffer.read(cx).read(cx);
 5982        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5983            drop(snapshot);
 5984            let mut revert_changes = HashMap::default();
 5985            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5986            if !revert_changes.is_empty() {
 5987                self.revert(revert_changes, cx)
 5988            }
 5989        }
 5990    }
 5991
 5992    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5993        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5994            let project_path = buffer.read(cx).project_path(cx)?;
 5995            let project = self.project.as_ref()?.read(cx);
 5996            let entry = project.entry_for_path(&project_path, cx)?;
 5997            let parent = match &entry.canonical_path {
 5998                Some(canonical_path) => canonical_path.to_path_buf(),
 5999                None => project.absolute_path(&project_path, cx)?,
 6000            }
 6001            .parent()?
 6002            .to_path_buf();
 6003            Some(parent)
 6004        }) {
 6005            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6006        }
 6007    }
 6008
 6009    fn gather_revert_changes(
 6010        &mut self,
 6011        selections: &[Selection<Point>],
 6012        cx: &mut ViewContext<'_, Editor>,
 6013    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6014        let mut revert_changes = HashMap::default();
 6015        let snapshot = self.snapshot(cx);
 6016        for hunk in hunks_for_selections(&snapshot, selections) {
 6017            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6018        }
 6019        revert_changes
 6020    }
 6021
 6022    pub fn prepare_revert_change(
 6023        &mut self,
 6024        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6025        hunk: &MultiBufferDiffHunk,
 6026        cx: &AppContext,
 6027    ) -> Option<()> {
 6028        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6029        let buffer = buffer.read(cx);
 6030        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6031        let original_text = change_set
 6032            .read(cx)
 6033            .base_text
 6034            .as_ref()?
 6035            .read(cx)
 6036            .as_rope()
 6037            .slice(hunk.diff_base_byte_range.clone());
 6038        let buffer_snapshot = buffer.snapshot();
 6039        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6040        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6041            probe
 6042                .0
 6043                .start
 6044                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6045                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6046        }) {
 6047            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6048            Some(())
 6049        } else {
 6050            None
 6051        }
 6052    }
 6053
 6054    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6055        self.manipulate_lines(cx, |lines| lines.reverse())
 6056    }
 6057
 6058    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6059        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6060    }
 6061
 6062    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6063    where
 6064        Fn: FnMut(&mut Vec<&str>),
 6065    {
 6066        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6067        let buffer = self.buffer.read(cx).snapshot(cx);
 6068
 6069        let mut edits = Vec::new();
 6070
 6071        let selections = self.selections.all::<Point>(cx);
 6072        let mut selections = selections.iter().peekable();
 6073        let mut contiguous_row_selections = Vec::new();
 6074        let mut new_selections = Vec::new();
 6075        let mut added_lines = 0;
 6076        let mut removed_lines = 0;
 6077
 6078        while let Some(selection) = selections.next() {
 6079            let (start_row, end_row) = consume_contiguous_rows(
 6080                &mut contiguous_row_selections,
 6081                selection,
 6082                &display_map,
 6083                &mut selections,
 6084            );
 6085
 6086            let start_point = Point::new(start_row.0, 0);
 6087            let end_point = Point::new(
 6088                end_row.previous_row().0,
 6089                buffer.line_len(end_row.previous_row()),
 6090            );
 6091            let text = buffer
 6092                .text_for_range(start_point..end_point)
 6093                .collect::<String>();
 6094
 6095            let mut lines = text.split('\n').collect_vec();
 6096
 6097            let lines_before = lines.len();
 6098            callback(&mut lines);
 6099            let lines_after = lines.len();
 6100
 6101            edits.push((start_point..end_point, lines.join("\n")));
 6102
 6103            // Selections must change based on added and removed line count
 6104            let start_row =
 6105                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6106            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6107            new_selections.push(Selection {
 6108                id: selection.id,
 6109                start: start_row,
 6110                end: end_row,
 6111                goal: SelectionGoal::None,
 6112                reversed: selection.reversed,
 6113            });
 6114
 6115            if lines_after > lines_before {
 6116                added_lines += lines_after - lines_before;
 6117            } else if lines_before > lines_after {
 6118                removed_lines += lines_before - lines_after;
 6119            }
 6120        }
 6121
 6122        self.transact(cx, |this, cx| {
 6123            let buffer = this.buffer.update(cx, |buffer, cx| {
 6124                buffer.edit(edits, None, cx);
 6125                buffer.snapshot(cx)
 6126            });
 6127
 6128            // Recalculate offsets on newly edited buffer
 6129            let new_selections = new_selections
 6130                .iter()
 6131                .map(|s| {
 6132                    let start_point = Point::new(s.start.0, 0);
 6133                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6134                    Selection {
 6135                        id: s.id,
 6136                        start: buffer.point_to_offset(start_point),
 6137                        end: buffer.point_to_offset(end_point),
 6138                        goal: s.goal,
 6139                        reversed: s.reversed,
 6140                    }
 6141                })
 6142                .collect();
 6143
 6144            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6145                s.select(new_selections);
 6146            });
 6147
 6148            this.request_autoscroll(Autoscroll::fit(), cx);
 6149        });
 6150    }
 6151
 6152    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6153        self.manipulate_text(cx, |text| text.to_uppercase())
 6154    }
 6155
 6156    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6157        self.manipulate_text(cx, |text| text.to_lowercase())
 6158    }
 6159
 6160    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6161        self.manipulate_text(cx, |text| {
 6162            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6163            // https://github.com/rutrum/convert-case/issues/16
 6164            text.split('\n')
 6165                .map(|line| line.to_case(Case::Title))
 6166                .join("\n")
 6167        })
 6168    }
 6169
 6170    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6171        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6172    }
 6173
 6174    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6175        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6176    }
 6177
 6178    pub fn convert_to_upper_camel_case(
 6179        &mut self,
 6180        _: &ConvertToUpperCamelCase,
 6181        cx: &mut ViewContext<Self>,
 6182    ) {
 6183        self.manipulate_text(cx, |text| {
 6184            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6185            // https://github.com/rutrum/convert-case/issues/16
 6186            text.split('\n')
 6187                .map(|line| line.to_case(Case::UpperCamel))
 6188                .join("\n")
 6189        })
 6190    }
 6191
 6192    pub fn convert_to_lower_camel_case(
 6193        &mut self,
 6194        _: &ConvertToLowerCamelCase,
 6195        cx: &mut ViewContext<Self>,
 6196    ) {
 6197        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6198    }
 6199
 6200    pub fn convert_to_opposite_case(
 6201        &mut self,
 6202        _: &ConvertToOppositeCase,
 6203        cx: &mut ViewContext<Self>,
 6204    ) {
 6205        self.manipulate_text(cx, |text| {
 6206            text.chars()
 6207                .fold(String::with_capacity(text.len()), |mut t, c| {
 6208                    if c.is_uppercase() {
 6209                        t.extend(c.to_lowercase());
 6210                    } else {
 6211                        t.extend(c.to_uppercase());
 6212                    }
 6213                    t
 6214                })
 6215        })
 6216    }
 6217
 6218    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6219    where
 6220        Fn: FnMut(&str) -> String,
 6221    {
 6222        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6223        let buffer = self.buffer.read(cx).snapshot(cx);
 6224
 6225        let mut new_selections = Vec::new();
 6226        let mut edits = Vec::new();
 6227        let mut selection_adjustment = 0i32;
 6228
 6229        for selection in self.selections.all::<usize>(cx) {
 6230            let selection_is_empty = selection.is_empty();
 6231
 6232            let (start, end) = if selection_is_empty {
 6233                let word_range = movement::surrounding_word(
 6234                    &display_map,
 6235                    selection.start.to_display_point(&display_map),
 6236                );
 6237                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6238                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6239                (start, end)
 6240            } else {
 6241                (selection.start, selection.end)
 6242            };
 6243
 6244            let text = buffer.text_for_range(start..end).collect::<String>();
 6245            let old_length = text.len() as i32;
 6246            let text = callback(&text);
 6247
 6248            new_selections.push(Selection {
 6249                start: (start as i32 - selection_adjustment) as usize,
 6250                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6251                goal: SelectionGoal::None,
 6252                ..selection
 6253            });
 6254
 6255            selection_adjustment += old_length - text.len() as i32;
 6256
 6257            edits.push((start..end, text));
 6258        }
 6259
 6260        self.transact(cx, |this, cx| {
 6261            this.buffer.update(cx, |buffer, cx| {
 6262                buffer.edit(edits, None, cx);
 6263            });
 6264
 6265            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6266                s.select(new_selections);
 6267            });
 6268
 6269            this.request_autoscroll(Autoscroll::fit(), cx);
 6270        });
 6271    }
 6272
 6273    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6274        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6275        let buffer = &display_map.buffer_snapshot;
 6276        let selections = self.selections.all::<Point>(cx);
 6277
 6278        let mut edits = Vec::new();
 6279        let mut selections_iter = selections.iter().peekable();
 6280        while let Some(selection) = selections_iter.next() {
 6281            let mut rows = selection.spanned_rows(false, &display_map);
 6282            // duplicate line-wise
 6283            if whole_lines || selection.start == selection.end {
 6284                // Avoid duplicating the same lines twice.
 6285                while let Some(next_selection) = selections_iter.peek() {
 6286                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6287                    if next_rows.start < rows.end {
 6288                        rows.end = next_rows.end;
 6289                        selections_iter.next().unwrap();
 6290                    } else {
 6291                        break;
 6292                    }
 6293                }
 6294
 6295                // Copy the text from the selected row region and splice it either at the start
 6296                // or end of the region.
 6297                let start = Point::new(rows.start.0, 0);
 6298                let end = Point::new(
 6299                    rows.end.previous_row().0,
 6300                    buffer.line_len(rows.end.previous_row()),
 6301                );
 6302                let text = buffer
 6303                    .text_for_range(start..end)
 6304                    .chain(Some("\n"))
 6305                    .collect::<String>();
 6306                let insert_location = if upwards {
 6307                    Point::new(rows.end.0, 0)
 6308                } else {
 6309                    start
 6310                };
 6311                edits.push((insert_location..insert_location, text));
 6312            } else {
 6313                // duplicate character-wise
 6314                let start = selection.start;
 6315                let end = selection.end;
 6316                let text = buffer.text_for_range(start..end).collect::<String>();
 6317                edits.push((selection.end..selection.end, text));
 6318            }
 6319        }
 6320
 6321        self.transact(cx, |this, cx| {
 6322            this.buffer.update(cx, |buffer, cx| {
 6323                buffer.edit(edits, None, cx);
 6324            });
 6325
 6326            this.request_autoscroll(Autoscroll::fit(), cx);
 6327        });
 6328    }
 6329
 6330    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6331        self.duplicate(true, true, cx);
 6332    }
 6333
 6334    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6335        self.duplicate(false, true, cx);
 6336    }
 6337
 6338    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6339        self.duplicate(false, false, cx);
 6340    }
 6341
 6342    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6343        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6344        let buffer = self.buffer.read(cx).snapshot(cx);
 6345
 6346        let mut edits = Vec::new();
 6347        let mut unfold_ranges = Vec::new();
 6348        let mut refold_creases = Vec::new();
 6349
 6350        let selections = self.selections.all::<Point>(cx);
 6351        let mut selections = selections.iter().peekable();
 6352        let mut contiguous_row_selections = Vec::new();
 6353        let mut new_selections = Vec::new();
 6354
 6355        while let Some(selection) = selections.next() {
 6356            // Find all the selections that span a contiguous row range
 6357            let (start_row, end_row) = consume_contiguous_rows(
 6358                &mut contiguous_row_selections,
 6359                selection,
 6360                &display_map,
 6361                &mut selections,
 6362            );
 6363
 6364            // Move the text spanned by the row range to be before the line preceding the row range
 6365            if start_row.0 > 0 {
 6366                let range_to_move = Point::new(
 6367                    start_row.previous_row().0,
 6368                    buffer.line_len(start_row.previous_row()),
 6369                )
 6370                    ..Point::new(
 6371                        end_row.previous_row().0,
 6372                        buffer.line_len(end_row.previous_row()),
 6373                    );
 6374                let insertion_point = display_map
 6375                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6376                    .0;
 6377
 6378                // Don't move lines across excerpts
 6379                if buffer
 6380                    .excerpt_boundaries_in_range((
 6381                        Bound::Excluded(insertion_point),
 6382                        Bound::Included(range_to_move.end),
 6383                    ))
 6384                    .next()
 6385                    .is_none()
 6386                {
 6387                    let text = buffer
 6388                        .text_for_range(range_to_move.clone())
 6389                        .flat_map(|s| s.chars())
 6390                        .skip(1)
 6391                        .chain(['\n'])
 6392                        .collect::<String>();
 6393
 6394                    edits.push((
 6395                        buffer.anchor_after(range_to_move.start)
 6396                            ..buffer.anchor_before(range_to_move.end),
 6397                        String::new(),
 6398                    ));
 6399                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6400                    edits.push((insertion_anchor..insertion_anchor, text));
 6401
 6402                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6403
 6404                    // Move selections up
 6405                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6406                        |mut selection| {
 6407                            selection.start.row -= row_delta;
 6408                            selection.end.row -= row_delta;
 6409                            selection
 6410                        },
 6411                    ));
 6412
 6413                    // Move folds up
 6414                    unfold_ranges.push(range_to_move.clone());
 6415                    for fold in display_map.folds_in_range(
 6416                        buffer.anchor_before(range_to_move.start)
 6417                            ..buffer.anchor_after(range_to_move.end),
 6418                    ) {
 6419                        let mut start = fold.range.start.to_point(&buffer);
 6420                        let mut end = fold.range.end.to_point(&buffer);
 6421                        start.row -= row_delta;
 6422                        end.row -= row_delta;
 6423                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6424                    }
 6425                }
 6426            }
 6427
 6428            // If we didn't move line(s), preserve the existing selections
 6429            new_selections.append(&mut contiguous_row_selections);
 6430        }
 6431
 6432        self.transact(cx, |this, cx| {
 6433            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6434            this.buffer.update(cx, |buffer, cx| {
 6435                for (range, text) in edits {
 6436                    buffer.edit([(range, text)], None, cx);
 6437                }
 6438            });
 6439            this.fold_creases(refold_creases, true, cx);
 6440            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6441                s.select(new_selections);
 6442            })
 6443        });
 6444    }
 6445
 6446    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6447        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6448        let buffer = self.buffer.read(cx).snapshot(cx);
 6449
 6450        let mut edits = Vec::new();
 6451        let mut unfold_ranges = Vec::new();
 6452        let mut refold_creases = Vec::new();
 6453
 6454        let selections = self.selections.all::<Point>(cx);
 6455        let mut selections = selections.iter().peekable();
 6456        let mut contiguous_row_selections = Vec::new();
 6457        let mut new_selections = Vec::new();
 6458
 6459        while let Some(selection) = selections.next() {
 6460            // Find all the selections that span a contiguous row range
 6461            let (start_row, end_row) = consume_contiguous_rows(
 6462                &mut contiguous_row_selections,
 6463                selection,
 6464                &display_map,
 6465                &mut selections,
 6466            );
 6467
 6468            // Move the text spanned by the row range to be after the last line of the row range
 6469            if end_row.0 <= buffer.max_point().row {
 6470                let range_to_move =
 6471                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6472                let insertion_point = display_map
 6473                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6474                    .0;
 6475
 6476                // Don't move lines across excerpt boundaries
 6477                if buffer
 6478                    .excerpt_boundaries_in_range((
 6479                        Bound::Excluded(range_to_move.start),
 6480                        Bound::Included(insertion_point),
 6481                    ))
 6482                    .next()
 6483                    .is_none()
 6484                {
 6485                    let mut text = String::from("\n");
 6486                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6487                    text.pop(); // Drop trailing newline
 6488                    edits.push((
 6489                        buffer.anchor_after(range_to_move.start)
 6490                            ..buffer.anchor_before(range_to_move.end),
 6491                        String::new(),
 6492                    ));
 6493                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6494                    edits.push((insertion_anchor..insertion_anchor, text));
 6495
 6496                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6497
 6498                    // Move selections down
 6499                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6500                        |mut selection| {
 6501                            selection.start.row += row_delta;
 6502                            selection.end.row += row_delta;
 6503                            selection
 6504                        },
 6505                    ));
 6506
 6507                    // Move folds down
 6508                    unfold_ranges.push(range_to_move.clone());
 6509                    for fold in display_map.folds_in_range(
 6510                        buffer.anchor_before(range_to_move.start)
 6511                            ..buffer.anchor_after(range_to_move.end),
 6512                    ) {
 6513                        let mut start = fold.range.start.to_point(&buffer);
 6514                        let mut end = fold.range.end.to_point(&buffer);
 6515                        start.row += row_delta;
 6516                        end.row += row_delta;
 6517                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6518                    }
 6519                }
 6520            }
 6521
 6522            // If we didn't move line(s), preserve the existing selections
 6523            new_selections.append(&mut contiguous_row_selections);
 6524        }
 6525
 6526        self.transact(cx, |this, cx| {
 6527            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6528            this.buffer.update(cx, |buffer, cx| {
 6529                for (range, text) in edits {
 6530                    buffer.edit([(range, text)], None, cx);
 6531                }
 6532            });
 6533            this.fold_creases(refold_creases, true, cx);
 6534            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6535        });
 6536    }
 6537
 6538    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6539        let text_layout_details = &self.text_layout_details(cx);
 6540        self.transact(cx, |this, cx| {
 6541            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6542                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6543                let line_mode = s.line_mode;
 6544                s.move_with(|display_map, selection| {
 6545                    if !selection.is_empty() || line_mode {
 6546                        return;
 6547                    }
 6548
 6549                    let mut head = selection.head();
 6550                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6551                    if head.column() == display_map.line_len(head.row()) {
 6552                        transpose_offset = display_map
 6553                            .buffer_snapshot
 6554                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6555                    }
 6556
 6557                    if transpose_offset == 0 {
 6558                        return;
 6559                    }
 6560
 6561                    *head.column_mut() += 1;
 6562                    head = display_map.clip_point(head, Bias::Right);
 6563                    let goal = SelectionGoal::HorizontalPosition(
 6564                        display_map
 6565                            .x_for_display_point(head, text_layout_details)
 6566                            .into(),
 6567                    );
 6568                    selection.collapse_to(head, goal);
 6569
 6570                    let transpose_start = display_map
 6571                        .buffer_snapshot
 6572                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6573                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6574                        let transpose_end = display_map
 6575                            .buffer_snapshot
 6576                            .clip_offset(transpose_offset + 1, Bias::Right);
 6577                        if let Some(ch) =
 6578                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6579                        {
 6580                            edits.push((transpose_start..transpose_offset, String::new()));
 6581                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6582                        }
 6583                    }
 6584                });
 6585                edits
 6586            });
 6587            this.buffer
 6588                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6589            let selections = this.selections.all::<usize>(cx);
 6590            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6591                s.select(selections);
 6592            });
 6593        });
 6594    }
 6595
 6596    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6597        self.rewrap_impl(IsVimMode::No, cx)
 6598    }
 6599
 6600    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6601        let buffer = self.buffer.read(cx).snapshot(cx);
 6602        let selections = self.selections.all::<Point>(cx);
 6603        let mut selections = selections.iter().peekable();
 6604
 6605        let mut edits = Vec::new();
 6606        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6607
 6608        while let Some(selection) = selections.next() {
 6609            let mut start_row = selection.start.row;
 6610            let mut end_row = selection.end.row;
 6611
 6612            // Skip selections that overlap with a range that has already been rewrapped.
 6613            let selection_range = start_row..end_row;
 6614            if rewrapped_row_ranges
 6615                .iter()
 6616                .any(|range| range.overlaps(&selection_range))
 6617            {
 6618                continue;
 6619            }
 6620
 6621            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6622
 6623            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6624                match language_scope.language_name().0.as_ref() {
 6625                    "Markdown" | "Plain Text" => {
 6626                        should_rewrap = true;
 6627                    }
 6628                    _ => {}
 6629                }
 6630            }
 6631
 6632            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6633
 6634            // Since not all lines in the selection may be at the same indent
 6635            // level, choose the indent size that is the most common between all
 6636            // of the lines.
 6637            //
 6638            // If there is a tie, we use the deepest indent.
 6639            let (indent_size, indent_end) = {
 6640                let mut indent_size_occurrences = HashMap::default();
 6641                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6642
 6643                for row in start_row..=end_row {
 6644                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6645                    rows_by_indent_size.entry(indent).or_default().push(row);
 6646                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6647                }
 6648
 6649                let indent_size = indent_size_occurrences
 6650                    .into_iter()
 6651                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6652                    .map(|(indent, _)| indent)
 6653                    .unwrap_or_default();
 6654                let row = rows_by_indent_size[&indent_size][0];
 6655                let indent_end = Point::new(row, indent_size.len);
 6656
 6657                (indent_size, indent_end)
 6658            };
 6659
 6660            let mut line_prefix = indent_size.chars().collect::<String>();
 6661
 6662            if let Some(comment_prefix) =
 6663                buffer
 6664                    .language_scope_at(selection.head())
 6665                    .and_then(|language| {
 6666                        language
 6667                            .line_comment_prefixes()
 6668                            .iter()
 6669                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6670                            .cloned()
 6671                    })
 6672            {
 6673                line_prefix.push_str(&comment_prefix);
 6674                should_rewrap = true;
 6675            }
 6676
 6677            if !should_rewrap {
 6678                continue;
 6679            }
 6680
 6681            if selection.is_empty() {
 6682                'expand_upwards: while start_row > 0 {
 6683                    let prev_row = start_row - 1;
 6684                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6685                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6686                    {
 6687                        start_row = prev_row;
 6688                    } else {
 6689                        break 'expand_upwards;
 6690                    }
 6691                }
 6692
 6693                'expand_downwards: while end_row < buffer.max_point().row {
 6694                    let next_row = end_row + 1;
 6695                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6696                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6697                    {
 6698                        end_row = next_row;
 6699                    } else {
 6700                        break 'expand_downwards;
 6701                    }
 6702                }
 6703            }
 6704
 6705            let start = Point::new(start_row, 0);
 6706            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6707            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6708            let Some(lines_without_prefixes) = selection_text
 6709                .lines()
 6710                .map(|line| {
 6711                    line.strip_prefix(&line_prefix)
 6712                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6713                        .ok_or_else(|| {
 6714                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6715                        })
 6716                })
 6717                .collect::<Result<Vec<_>, _>>()
 6718                .log_err()
 6719            else {
 6720                continue;
 6721            };
 6722
 6723            let wrap_column = buffer
 6724                .settings_at(Point::new(start_row, 0), cx)
 6725                .preferred_line_length as usize;
 6726            let wrapped_text = wrap_with_prefix(
 6727                line_prefix,
 6728                lines_without_prefixes.join(" "),
 6729                wrap_column,
 6730                tab_size,
 6731            );
 6732
 6733            // TODO: should always use char-based diff while still supporting cursor behavior that
 6734            // matches vim.
 6735            let diff = match is_vim_mode {
 6736                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6737                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6738            };
 6739            let mut offset = start.to_offset(&buffer);
 6740            let mut moved_since_edit = true;
 6741
 6742            for change in diff.iter_all_changes() {
 6743                let value = change.value();
 6744                match change.tag() {
 6745                    ChangeTag::Equal => {
 6746                        offset += value.len();
 6747                        moved_since_edit = true;
 6748                    }
 6749                    ChangeTag::Delete => {
 6750                        let start = buffer.anchor_after(offset);
 6751                        let end = buffer.anchor_before(offset + value.len());
 6752
 6753                        if moved_since_edit {
 6754                            edits.push((start..end, String::new()));
 6755                        } else {
 6756                            edits.last_mut().unwrap().0.end = end;
 6757                        }
 6758
 6759                        offset += value.len();
 6760                        moved_since_edit = false;
 6761                    }
 6762                    ChangeTag::Insert => {
 6763                        if moved_since_edit {
 6764                            let anchor = buffer.anchor_after(offset);
 6765                            edits.push((anchor..anchor, value.to_string()));
 6766                        } else {
 6767                            edits.last_mut().unwrap().1.push_str(value);
 6768                        }
 6769
 6770                        moved_since_edit = false;
 6771                    }
 6772                }
 6773            }
 6774
 6775            rewrapped_row_ranges.push(start_row..=end_row);
 6776        }
 6777
 6778        self.buffer
 6779            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6780    }
 6781
 6782    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6783        let mut text = String::new();
 6784        let buffer = self.buffer.read(cx).snapshot(cx);
 6785        let mut selections = self.selections.all::<Point>(cx);
 6786        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6787        {
 6788            let max_point = buffer.max_point();
 6789            let mut is_first = true;
 6790            for selection in &mut selections {
 6791                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6792                if is_entire_line {
 6793                    selection.start = Point::new(selection.start.row, 0);
 6794                    if !selection.is_empty() && selection.end.column == 0 {
 6795                        selection.end = cmp::min(max_point, selection.end);
 6796                    } else {
 6797                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6798                    }
 6799                    selection.goal = SelectionGoal::None;
 6800                }
 6801                if is_first {
 6802                    is_first = false;
 6803                } else {
 6804                    text += "\n";
 6805                }
 6806                let mut len = 0;
 6807                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6808                    text.push_str(chunk);
 6809                    len += chunk.len();
 6810                }
 6811                clipboard_selections.push(ClipboardSelection {
 6812                    len,
 6813                    is_entire_line,
 6814                    first_line_indent: buffer
 6815                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6816                        .len,
 6817                });
 6818            }
 6819        }
 6820
 6821        self.transact(cx, |this, cx| {
 6822            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6823                s.select(selections);
 6824            });
 6825            this.insert("", cx);
 6826        });
 6827        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6828    }
 6829
 6830    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6831        let item = self.cut_common(cx);
 6832        cx.write_to_clipboard(item);
 6833    }
 6834
 6835    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6836        self.change_selections(None, cx, |s| {
 6837            s.move_with(|snapshot, sel| {
 6838                if sel.is_empty() {
 6839                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6840                }
 6841            });
 6842        });
 6843        let item = self.cut_common(cx);
 6844        cx.set_global(KillRing(item))
 6845    }
 6846
 6847    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6848        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6849            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6850                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6851            } else {
 6852                return;
 6853            }
 6854        } else {
 6855            return;
 6856        };
 6857        self.do_paste(&text, metadata, false, cx);
 6858    }
 6859
 6860    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6861        let selections = self.selections.all::<Point>(cx);
 6862        let buffer = self.buffer.read(cx).read(cx);
 6863        let mut text = String::new();
 6864
 6865        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6866        {
 6867            let max_point = buffer.max_point();
 6868            let mut is_first = true;
 6869            for selection in selections.iter() {
 6870                let mut start = selection.start;
 6871                let mut end = selection.end;
 6872                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6873                if is_entire_line {
 6874                    start = Point::new(start.row, 0);
 6875                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6876                }
 6877                if is_first {
 6878                    is_first = false;
 6879                } else {
 6880                    text += "\n";
 6881                }
 6882                let mut len = 0;
 6883                for chunk in buffer.text_for_range(start..end) {
 6884                    text.push_str(chunk);
 6885                    len += chunk.len();
 6886                }
 6887                clipboard_selections.push(ClipboardSelection {
 6888                    len,
 6889                    is_entire_line,
 6890                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6891                });
 6892            }
 6893        }
 6894
 6895        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6896            text,
 6897            clipboard_selections,
 6898        ));
 6899    }
 6900
 6901    pub fn do_paste(
 6902        &mut self,
 6903        text: &String,
 6904        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6905        handle_entire_lines: bool,
 6906        cx: &mut ViewContext<Self>,
 6907    ) {
 6908        if self.read_only(cx) {
 6909            return;
 6910        }
 6911
 6912        let clipboard_text = Cow::Borrowed(text);
 6913
 6914        self.transact(cx, |this, cx| {
 6915            if let Some(mut clipboard_selections) = clipboard_selections {
 6916                let old_selections = this.selections.all::<usize>(cx);
 6917                let all_selections_were_entire_line =
 6918                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6919                let first_selection_indent_column =
 6920                    clipboard_selections.first().map(|s| s.first_line_indent);
 6921                if clipboard_selections.len() != old_selections.len() {
 6922                    clipboard_selections.drain(..);
 6923                }
 6924                let cursor_offset = this.selections.last::<usize>(cx).head();
 6925                let mut auto_indent_on_paste = true;
 6926
 6927                this.buffer.update(cx, |buffer, cx| {
 6928                    let snapshot = buffer.read(cx);
 6929                    auto_indent_on_paste =
 6930                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6931
 6932                    let mut start_offset = 0;
 6933                    let mut edits = Vec::new();
 6934                    let mut original_indent_columns = Vec::new();
 6935                    for (ix, selection) in old_selections.iter().enumerate() {
 6936                        let to_insert;
 6937                        let entire_line;
 6938                        let original_indent_column;
 6939                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6940                            let end_offset = start_offset + clipboard_selection.len;
 6941                            to_insert = &clipboard_text[start_offset..end_offset];
 6942                            entire_line = clipboard_selection.is_entire_line;
 6943                            start_offset = end_offset + 1;
 6944                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6945                        } else {
 6946                            to_insert = clipboard_text.as_str();
 6947                            entire_line = all_selections_were_entire_line;
 6948                            original_indent_column = first_selection_indent_column
 6949                        }
 6950
 6951                        // If the corresponding selection was empty when this slice of the
 6952                        // clipboard text was written, then the entire line containing the
 6953                        // selection was copied. If this selection is also currently empty,
 6954                        // then paste the line before the current line of the buffer.
 6955                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6956                            let column = selection.start.to_point(&snapshot).column as usize;
 6957                            let line_start = selection.start - column;
 6958                            line_start..line_start
 6959                        } else {
 6960                            selection.range()
 6961                        };
 6962
 6963                        edits.push((range, to_insert));
 6964                        original_indent_columns.extend(original_indent_column);
 6965                    }
 6966                    drop(snapshot);
 6967
 6968                    buffer.edit(
 6969                        edits,
 6970                        if auto_indent_on_paste {
 6971                            Some(AutoindentMode::Block {
 6972                                original_indent_columns,
 6973                            })
 6974                        } else {
 6975                            None
 6976                        },
 6977                        cx,
 6978                    );
 6979                });
 6980
 6981                let selections = this.selections.all::<usize>(cx);
 6982                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6983            } else {
 6984                this.insert(&clipboard_text, cx);
 6985            }
 6986        });
 6987    }
 6988
 6989    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6990        if let Some(item) = cx.read_from_clipboard() {
 6991            let entries = item.entries();
 6992
 6993            match entries.first() {
 6994                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6995                // of all the pasted entries.
 6996                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6997                    .do_paste(
 6998                        clipboard_string.text(),
 6999                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7000                        true,
 7001                        cx,
 7002                    ),
 7003                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7004            }
 7005        }
 7006    }
 7007
 7008    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7009        if self.read_only(cx) {
 7010            return;
 7011        }
 7012
 7013        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7014            if let Some((selections, _)) =
 7015                self.selection_history.transaction(transaction_id).cloned()
 7016            {
 7017                self.change_selections(None, cx, |s| {
 7018                    s.select_anchors(selections.to_vec());
 7019                });
 7020            }
 7021            self.request_autoscroll(Autoscroll::fit(), cx);
 7022            self.unmark_text(cx);
 7023            self.refresh_inline_completion(true, false, cx);
 7024            cx.emit(EditorEvent::Edited { transaction_id });
 7025            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7026        }
 7027    }
 7028
 7029    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7030        if self.read_only(cx) {
 7031            return;
 7032        }
 7033
 7034        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7035            if let Some((_, Some(selections))) =
 7036                self.selection_history.transaction(transaction_id).cloned()
 7037            {
 7038                self.change_selections(None, cx, |s| {
 7039                    s.select_anchors(selections.to_vec());
 7040                });
 7041            }
 7042            self.request_autoscroll(Autoscroll::fit(), cx);
 7043            self.unmark_text(cx);
 7044            self.refresh_inline_completion(true, false, cx);
 7045            cx.emit(EditorEvent::Edited { transaction_id });
 7046        }
 7047    }
 7048
 7049    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7050        self.buffer
 7051            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7052    }
 7053
 7054    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7055        self.buffer
 7056            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7057    }
 7058
 7059    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7060        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7061            let line_mode = s.line_mode;
 7062            s.move_with(|map, selection| {
 7063                let cursor = if selection.is_empty() && !line_mode {
 7064                    movement::left(map, selection.start)
 7065                } else {
 7066                    selection.start
 7067                };
 7068                selection.collapse_to(cursor, SelectionGoal::None);
 7069            });
 7070        })
 7071    }
 7072
 7073    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7074        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7075            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7076        })
 7077    }
 7078
 7079    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7080        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7081            let line_mode = s.line_mode;
 7082            s.move_with(|map, selection| {
 7083                let cursor = if selection.is_empty() && !line_mode {
 7084                    movement::right(map, selection.end)
 7085                } else {
 7086                    selection.end
 7087                };
 7088                selection.collapse_to(cursor, SelectionGoal::None)
 7089            });
 7090        })
 7091    }
 7092
 7093    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7094        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7095            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7096        })
 7097    }
 7098
 7099    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7100        if self.take_rename(true, cx).is_some() {
 7101            return;
 7102        }
 7103
 7104        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7105            cx.propagate();
 7106            return;
 7107        }
 7108
 7109        let text_layout_details = &self.text_layout_details(cx);
 7110        let selection_count = self.selections.count();
 7111        let first_selection = self.selections.first_anchor();
 7112
 7113        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7114            let line_mode = s.line_mode;
 7115            s.move_with(|map, selection| {
 7116                if !selection.is_empty() && !line_mode {
 7117                    selection.goal = SelectionGoal::None;
 7118                }
 7119                let (cursor, goal) = movement::up(
 7120                    map,
 7121                    selection.start,
 7122                    selection.goal,
 7123                    false,
 7124                    text_layout_details,
 7125                );
 7126                selection.collapse_to(cursor, goal);
 7127            });
 7128        });
 7129
 7130        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7131        {
 7132            cx.propagate();
 7133        }
 7134    }
 7135
 7136    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7137        if self.take_rename(true, cx).is_some() {
 7138            return;
 7139        }
 7140
 7141        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7142            cx.propagate();
 7143            return;
 7144        }
 7145
 7146        let text_layout_details = &self.text_layout_details(cx);
 7147
 7148        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7149            let line_mode = s.line_mode;
 7150            s.move_with(|map, selection| {
 7151                if !selection.is_empty() && !line_mode {
 7152                    selection.goal = SelectionGoal::None;
 7153                }
 7154                let (cursor, goal) = movement::up_by_rows(
 7155                    map,
 7156                    selection.start,
 7157                    action.lines,
 7158                    selection.goal,
 7159                    false,
 7160                    text_layout_details,
 7161                );
 7162                selection.collapse_to(cursor, goal);
 7163            });
 7164        })
 7165    }
 7166
 7167    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7168        if self.take_rename(true, cx).is_some() {
 7169            return;
 7170        }
 7171
 7172        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7173            cx.propagate();
 7174            return;
 7175        }
 7176
 7177        let text_layout_details = &self.text_layout_details(cx);
 7178
 7179        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7180            let line_mode = s.line_mode;
 7181            s.move_with(|map, selection| {
 7182                if !selection.is_empty() && !line_mode {
 7183                    selection.goal = SelectionGoal::None;
 7184                }
 7185                let (cursor, goal) = movement::down_by_rows(
 7186                    map,
 7187                    selection.start,
 7188                    action.lines,
 7189                    selection.goal,
 7190                    false,
 7191                    text_layout_details,
 7192                );
 7193                selection.collapse_to(cursor, goal);
 7194            });
 7195        })
 7196    }
 7197
 7198    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7199        let text_layout_details = &self.text_layout_details(cx);
 7200        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7201            s.move_heads_with(|map, head, goal| {
 7202                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7203            })
 7204        })
 7205    }
 7206
 7207    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7208        let text_layout_details = &self.text_layout_details(cx);
 7209        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7210            s.move_heads_with(|map, head, goal| {
 7211                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7212            })
 7213        })
 7214    }
 7215
 7216    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7217        let Some(row_count) = self.visible_row_count() else {
 7218            return;
 7219        };
 7220
 7221        let text_layout_details = &self.text_layout_details(cx);
 7222
 7223        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7224            s.move_heads_with(|map, head, goal| {
 7225                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7226            })
 7227        })
 7228    }
 7229
 7230    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7231        if self.take_rename(true, cx).is_some() {
 7232            return;
 7233        }
 7234
 7235        if self
 7236            .context_menu
 7237            .borrow_mut()
 7238            .as_mut()
 7239            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7240            .unwrap_or(false)
 7241        {
 7242            return;
 7243        }
 7244
 7245        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7246            cx.propagate();
 7247            return;
 7248        }
 7249
 7250        let Some(row_count) = self.visible_row_count() else {
 7251            return;
 7252        };
 7253
 7254        let autoscroll = if action.center_cursor {
 7255            Autoscroll::center()
 7256        } else {
 7257            Autoscroll::fit()
 7258        };
 7259
 7260        let text_layout_details = &self.text_layout_details(cx);
 7261
 7262        self.change_selections(Some(autoscroll), cx, |s| {
 7263            let line_mode = s.line_mode;
 7264            s.move_with(|map, selection| {
 7265                if !selection.is_empty() && !line_mode {
 7266                    selection.goal = SelectionGoal::None;
 7267                }
 7268                let (cursor, goal) = movement::up_by_rows(
 7269                    map,
 7270                    selection.end,
 7271                    row_count,
 7272                    selection.goal,
 7273                    false,
 7274                    text_layout_details,
 7275                );
 7276                selection.collapse_to(cursor, goal);
 7277            });
 7278        });
 7279    }
 7280
 7281    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7282        let text_layout_details = &self.text_layout_details(cx);
 7283        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7284            s.move_heads_with(|map, head, goal| {
 7285                movement::up(map, head, goal, false, text_layout_details)
 7286            })
 7287        })
 7288    }
 7289
 7290    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7291        self.take_rename(true, cx);
 7292
 7293        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7294            cx.propagate();
 7295            return;
 7296        }
 7297
 7298        let text_layout_details = &self.text_layout_details(cx);
 7299        let selection_count = self.selections.count();
 7300        let first_selection = self.selections.first_anchor();
 7301
 7302        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7303            let line_mode = s.line_mode;
 7304            s.move_with(|map, selection| {
 7305                if !selection.is_empty() && !line_mode {
 7306                    selection.goal = SelectionGoal::None;
 7307                }
 7308                let (cursor, goal) = movement::down(
 7309                    map,
 7310                    selection.end,
 7311                    selection.goal,
 7312                    false,
 7313                    text_layout_details,
 7314                );
 7315                selection.collapse_to(cursor, goal);
 7316            });
 7317        });
 7318
 7319        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7320        {
 7321            cx.propagate();
 7322        }
 7323    }
 7324
 7325    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7326        let Some(row_count) = self.visible_row_count() else {
 7327            return;
 7328        };
 7329
 7330        let text_layout_details = &self.text_layout_details(cx);
 7331
 7332        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7333            s.move_heads_with(|map, head, goal| {
 7334                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7335            })
 7336        })
 7337    }
 7338
 7339    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7340        if self.take_rename(true, cx).is_some() {
 7341            return;
 7342        }
 7343
 7344        if self
 7345            .context_menu
 7346            .borrow_mut()
 7347            .as_mut()
 7348            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7349            .unwrap_or(false)
 7350        {
 7351            return;
 7352        }
 7353
 7354        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7355            cx.propagate();
 7356            return;
 7357        }
 7358
 7359        let Some(row_count) = self.visible_row_count() else {
 7360            return;
 7361        };
 7362
 7363        let autoscroll = if action.center_cursor {
 7364            Autoscroll::center()
 7365        } else {
 7366            Autoscroll::fit()
 7367        };
 7368
 7369        let text_layout_details = &self.text_layout_details(cx);
 7370        self.change_selections(Some(autoscroll), cx, |s| {
 7371            let line_mode = s.line_mode;
 7372            s.move_with(|map, selection| {
 7373                if !selection.is_empty() && !line_mode {
 7374                    selection.goal = SelectionGoal::None;
 7375                }
 7376                let (cursor, goal) = movement::down_by_rows(
 7377                    map,
 7378                    selection.end,
 7379                    row_count,
 7380                    selection.goal,
 7381                    false,
 7382                    text_layout_details,
 7383                );
 7384                selection.collapse_to(cursor, goal);
 7385            });
 7386        });
 7387    }
 7388
 7389    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7390        let text_layout_details = &self.text_layout_details(cx);
 7391        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7392            s.move_heads_with(|map, head, goal| {
 7393                movement::down(map, head, goal, false, text_layout_details)
 7394            })
 7395        });
 7396    }
 7397
 7398    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7399        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7400            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7401        }
 7402    }
 7403
 7404    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7405        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7406            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7407        }
 7408    }
 7409
 7410    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7411        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7412            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7413        }
 7414    }
 7415
 7416    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7417        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7418            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7419        }
 7420    }
 7421
 7422    pub fn move_to_previous_word_start(
 7423        &mut self,
 7424        _: &MoveToPreviousWordStart,
 7425        cx: &mut ViewContext<Self>,
 7426    ) {
 7427        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7428            s.move_cursors_with(|map, head, _| {
 7429                (
 7430                    movement::previous_word_start(map, head),
 7431                    SelectionGoal::None,
 7432                )
 7433            });
 7434        })
 7435    }
 7436
 7437    pub fn move_to_previous_subword_start(
 7438        &mut self,
 7439        _: &MoveToPreviousSubwordStart,
 7440        cx: &mut ViewContext<Self>,
 7441    ) {
 7442        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7443            s.move_cursors_with(|map, head, _| {
 7444                (
 7445                    movement::previous_subword_start(map, head),
 7446                    SelectionGoal::None,
 7447                )
 7448            });
 7449        })
 7450    }
 7451
 7452    pub fn select_to_previous_word_start(
 7453        &mut self,
 7454        _: &SelectToPreviousWordStart,
 7455        cx: &mut ViewContext<Self>,
 7456    ) {
 7457        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7458            s.move_heads_with(|map, head, _| {
 7459                (
 7460                    movement::previous_word_start(map, head),
 7461                    SelectionGoal::None,
 7462                )
 7463            });
 7464        })
 7465    }
 7466
 7467    pub fn select_to_previous_subword_start(
 7468        &mut self,
 7469        _: &SelectToPreviousSubwordStart,
 7470        cx: &mut ViewContext<Self>,
 7471    ) {
 7472        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7473            s.move_heads_with(|map, head, _| {
 7474                (
 7475                    movement::previous_subword_start(map, head),
 7476                    SelectionGoal::None,
 7477                )
 7478            });
 7479        })
 7480    }
 7481
 7482    pub fn delete_to_previous_word_start(
 7483        &mut self,
 7484        action: &DeleteToPreviousWordStart,
 7485        cx: &mut ViewContext<Self>,
 7486    ) {
 7487        self.transact(cx, |this, cx| {
 7488            this.select_autoclose_pair(cx);
 7489            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7490                let line_mode = s.line_mode;
 7491                s.move_with(|map, selection| {
 7492                    if selection.is_empty() && !line_mode {
 7493                        let cursor = if action.ignore_newlines {
 7494                            movement::previous_word_start(map, selection.head())
 7495                        } else {
 7496                            movement::previous_word_start_or_newline(map, selection.head())
 7497                        };
 7498                        selection.set_head(cursor, SelectionGoal::None);
 7499                    }
 7500                });
 7501            });
 7502            this.insert("", cx);
 7503        });
 7504    }
 7505
 7506    pub fn delete_to_previous_subword_start(
 7507        &mut self,
 7508        _: &DeleteToPreviousSubwordStart,
 7509        cx: &mut ViewContext<Self>,
 7510    ) {
 7511        self.transact(cx, |this, cx| {
 7512            this.select_autoclose_pair(cx);
 7513            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7514                let line_mode = s.line_mode;
 7515                s.move_with(|map, selection| {
 7516                    if selection.is_empty() && !line_mode {
 7517                        let cursor = movement::previous_subword_start(map, selection.head());
 7518                        selection.set_head(cursor, SelectionGoal::None);
 7519                    }
 7520                });
 7521            });
 7522            this.insert("", cx);
 7523        });
 7524    }
 7525
 7526    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7527        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7528            s.move_cursors_with(|map, head, _| {
 7529                (movement::next_word_end(map, head), SelectionGoal::None)
 7530            });
 7531        })
 7532    }
 7533
 7534    pub fn move_to_next_subword_end(
 7535        &mut self,
 7536        _: &MoveToNextSubwordEnd,
 7537        cx: &mut ViewContext<Self>,
 7538    ) {
 7539        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7540            s.move_cursors_with(|map, head, _| {
 7541                (movement::next_subword_end(map, head), SelectionGoal::None)
 7542            });
 7543        })
 7544    }
 7545
 7546    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7547        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7548            s.move_heads_with(|map, head, _| {
 7549                (movement::next_word_end(map, head), SelectionGoal::None)
 7550            });
 7551        })
 7552    }
 7553
 7554    pub fn select_to_next_subword_end(
 7555        &mut self,
 7556        _: &SelectToNextSubwordEnd,
 7557        cx: &mut ViewContext<Self>,
 7558    ) {
 7559        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7560            s.move_heads_with(|map, head, _| {
 7561                (movement::next_subword_end(map, head), SelectionGoal::None)
 7562            });
 7563        })
 7564    }
 7565
 7566    pub fn delete_to_next_word_end(
 7567        &mut self,
 7568        action: &DeleteToNextWordEnd,
 7569        cx: &mut ViewContext<Self>,
 7570    ) {
 7571        self.transact(cx, |this, cx| {
 7572            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7573                let line_mode = s.line_mode;
 7574                s.move_with(|map, selection| {
 7575                    if selection.is_empty() && !line_mode {
 7576                        let cursor = if action.ignore_newlines {
 7577                            movement::next_word_end(map, selection.head())
 7578                        } else {
 7579                            movement::next_word_end_or_newline(map, selection.head())
 7580                        };
 7581                        selection.set_head(cursor, SelectionGoal::None);
 7582                    }
 7583                });
 7584            });
 7585            this.insert("", cx);
 7586        });
 7587    }
 7588
 7589    pub fn delete_to_next_subword_end(
 7590        &mut self,
 7591        _: &DeleteToNextSubwordEnd,
 7592        cx: &mut ViewContext<Self>,
 7593    ) {
 7594        self.transact(cx, |this, cx| {
 7595            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7596                s.move_with(|map, selection| {
 7597                    if selection.is_empty() {
 7598                        let cursor = movement::next_subword_end(map, selection.head());
 7599                        selection.set_head(cursor, SelectionGoal::None);
 7600                    }
 7601                });
 7602            });
 7603            this.insert("", cx);
 7604        });
 7605    }
 7606
 7607    pub fn move_to_beginning_of_line(
 7608        &mut self,
 7609        action: &MoveToBeginningOfLine,
 7610        cx: &mut ViewContext<Self>,
 7611    ) {
 7612        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7613            s.move_cursors_with(|map, head, _| {
 7614                (
 7615                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7616                    SelectionGoal::None,
 7617                )
 7618            });
 7619        })
 7620    }
 7621
 7622    pub fn select_to_beginning_of_line(
 7623        &mut self,
 7624        action: &SelectToBeginningOfLine,
 7625        cx: &mut ViewContext<Self>,
 7626    ) {
 7627        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7628            s.move_heads_with(|map, head, _| {
 7629                (
 7630                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7631                    SelectionGoal::None,
 7632                )
 7633            });
 7634        });
 7635    }
 7636
 7637    pub fn delete_to_beginning_of_line(
 7638        &mut self,
 7639        _: &DeleteToBeginningOfLine,
 7640        cx: &mut ViewContext<Self>,
 7641    ) {
 7642        self.transact(cx, |this, cx| {
 7643            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7644                s.move_with(|_, selection| {
 7645                    selection.reversed = true;
 7646                });
 7647            });
 7648
 7649            this.select_to_beginning_of_line(
 7650                &SelectToBeginningOfLine {
 7651                    stop_at_soft_wraps: false,
 7652                },
 7653                cx,
 7654            );
 7655            this.backspace(&Backspace, cx);
 7656        });
 7657    }
 7658
 7659    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7660        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7661            s.move_cursors_with(|map, head, _| {
 7662                (
 7663                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7664                    SelectionGoal::None,
 7665                )
 7666            });
 7667        })
 7668    }
 7669
 7670    pub fn select_to_end_of_line(
 7671        &mut self,
 7672        action: &SelectToEndOfLine,
 7673        cx: &mut ViewContext<Self>,
 7674    ) {
 7675        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7676            s.move_heads_with(|map, head, _| {
 7677                (
 7678                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7679                    SelectionGoal::None,
 7680                )
 7681            });
 7682        })
 7683    }
 7684
 7685    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7686        self.transact(cx, |this, cx| {
 7687            this.select_to_end_of_line(
 7688                &SelectToEndOfLine {
 7689                    stop_at_soft_wraps: false,
 7690                },
 7691                cx,
 7692            );
 7693            this.delete(&Delete, cx);
 7694        });
 7695    }
 7696
 7697    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7698        self.transact(cx, |this, cx| {
 7699            this.select_to_end_of_line(
 7700                &SelectToEndOfLine {
 7701                    stop_at_soft_wraps: false,
 7702                },
 7703                cx,
 7704            );
 7705            this.cut(&Cut, cx);
 7706        });
 7707    }
 7708
 7709    pub fn move_to_start_of_paragraph(
 7710        &mut self,
 7711        _: &MoveToStartOfParagraph,
 7712        cx: &mut ViewContext<Self>,
 7713    ) {
 7714        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7715            cx.propagate();
 7716            return;
 7717        }
 7718
 7719        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7720            s.move_with(|map, selection| {
 7721                selection.collapse_to(
 7722                    movement::start_of_paragraph(map, selection.head(), 1),
 7723                    SelectionGoal::None,
 7724                )
 7725            });
 7726        })
 7727    }
 7728
 7729    pub fn move_to_end_of_paragraph(
 7730        &mut self,
 7731        _: &MoveToEndOfParagraph,
 7732        cx: &mut ViewContext<Self>,
 7733    ) {
 7734        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7735            cx.propagate();
 7736            return;
 7737        }
 7738
 7739        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7740            s.move_with(|map, selection| {
 7741                selection.collapse_to(
 7742                    movement::end_of_paragraph(map, selection.head(), 1),
 7743                    SelectionGoal::None,
 7744                )
 7745            });
 7746        })
 7747    }
 7748
 7749    pub fn select_to_start_of_paragraph(
 7750        &mut self,
 7751        _: &SelectToStartOfParagraph,
 7752        cx: &mut ViewContext<Self>,
 7753    ) {
 7754        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7755            cx.propagate();
 7756            return;
 7757        }
 7758
 7759        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7760            s.move_heads_with(|map, head, _| {
 7761                (
 7762                    movement::start_of_paragraph(map, head, 1),
 7763                    SelectionGoal::None,
 7764                )
 7765            });
 7766        })
 7767    }
 7768
 7769    pub fn select_to_end_of_paragraph(
 7770        &mut self,
 7771        _: &SelectToEndOfParagraph,
 7772        cx: &mut ViewContext<Self>,
 7773    ) {
 7774        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7775            cx.propagate();
 7776            return;
 7777        }
 7778
 7779        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7780            s.move_heads_with(|map, head, _| {
 7781                (
 7782                    movement::end_of_paragraph(map, head, 1),
 7783                    SelectionGoal::None,
 7784                )
 7785            });
 7786        })
 7787    }
 7788
 7789    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7790        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7791            cx.propagate();
 7792            return;
 7793        }
 7794
 7795        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7796            s.select_ranges(vec![0..0]);
 7797        });
 7798    }
 7799
 7800    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7801        let mut selection = self.selections.last::<Point>(cx);
 7802        selection.set_head(Point::zero(), SelectionGoal::None);
 7803
 7804        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7805            s.select(vec![selection]);
 7806        });
 7807    }
 7808
 7809    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7810        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7811            cx.propagate();
 7812            return;
 7813        }
 7814
 7815        let cursor = self.buffer.read(cx).read(cx).len();
 7816        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7817            s.select_ranges(vec![cursor..cursor])
 7818        });
 7819    }
 7820
 7821    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7822        self.nav_history = nav_history;
 7823    }
 7824
 7825    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7826        self.nav_history.as_ref()
 7827    }
 7828
 7829    fn push_to_nav_history(
 7830        &mut self,
 7831        cursor_anchor: Anchor,
 7832        new_position: Option<Point>,
 7833        cx: &mut ViewContext<Self>,
 7834    ) {
 7835        if let Some(nav_history) = self.nav_history.as_mut() {
 7836            let buffer = self.buffer.read(cx).read(cx);
 7837            let cursor_position = cursor_anchor.to_point(&buffer);
 7838            let scroll_state = self.scroll_manager.anchor();
 7839            let scroll_top_row = scroll_state.top_row(&buffer);
 7840            drop(buffer);
 7841
 7842            if let Some(new_position) = new_position {
 7843                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7844                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7845                    return;
 7846                }
 7847            }
 7848
 7849            nav_history.push(
 7850                Some(NavigationData {
 7851                    cursor_anchor,
 7852                    cursor_position,
 7853                    scroll_anchor: scroll_state,
 7854                    scroll_top_row,
 7855                }),
 7856                cx,
 7857            );
 7858        }
 7859    }
 7860
 7861    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7862        let buffer = self.buffer.read(cx).snapshot(cx);
 7863        let mut selection = self.selections.first::<usize>(cx);
 7864        selection.set_head(buffer.len(), SelectionGoal::None);
 7865        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7866            s.select(vec![selection]);
 7867        });
 7868    }
 7869
 7870    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7871        let end = self.buffer.read(cx).read(cx).len();
 7872        self.change_selections(None, cx, |s| {
 7873            s.select_ranges(vec![0..end]);
 7874        });
 7875    }
 7876
 7877    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7878        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7879        let mut selections = self.selections.all::<Point>(cx);
 7880        let max_point = display_map.buffer_snapshot.max_point();
 7881        for selection in &mut selections {
 7882            let rows = selection.spanned_rows(true, &display_map);
 7883            selection.start = Point::new(rows.start.0, 0);
 7884            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7885            selection.reversed = false;
 7886        }
 7887        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7888            s.select(selections);
 7889        });
 7890    }
 7891
 7892    pub fn split_selection_into_lines(
 7893        &mut self,
 7894        _: &SplitSelectionIntoLines,
 7895        cx: &mut ViewContext<Self>,
 7896    ) {
 7897        let mut to_unfold = Vec::new();
 7898        let mut new_selection_ranges = Vec::new();
 7899        {
 7900            let selections = self.selections.all::<Point>(cx);
 7901            let buffer = self.buffer.read(cx).read(cx);
 7902            for selection in selections {
 7903                for row in selection.start.row..selection.end.row {
 7904                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7905                    new_selection_ranges.push(cursor..cursor);
 7906                }
 7907                new_selection_ranges.push(selection.end..selection.end);
 7908                to_unfold.push(selection.start..selection.end);
 7909            }
 7910        }
 7911        self.unfold_ranges(&to_unfold, true, true, cx);
 7912        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7913            s.select_ranges(new_selection_ranges);
 7914        });
 7915    }
 7916
 7917    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7918        self.add_selection(true, cx);
 7919    }
 7920
 7921    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7922        self.add_selection(false, cx);
 7923    }
 7924
 7925    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7926        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7927        let mut selections = self.selections.all::<Point>(cx);
 7928        let text_layout_details = self.text_layout_details(cx);
 7929        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7930            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7931            let range = oldest_selection.display_range(&display_map).sorted();
 7932
 7933            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7934            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7935            let positions = start_x.min(end_x)..start_x.max(end_x);
 7936
 7937            selections.clear();
 7938            let mut stack = Vec::new();
 7939            for row in range.start.row().0..=range.end.row().0 {
 7940                if let Some(selection) = self.selections.build_columnar_selection(
 7941                    &display_map,
 7942                    DisplayRow(row),
 7943                    &positions,
 7944                    oldest_selection.reversed,
 7945                    &text_layout_details,
 7946                ) {
 7947                    stack.push(selection.id);
 7948                    selections.push(selection);
 7949                }
 7950            }
 7951
 7952            if above {
 7953                stack.reverse();
 7954            }
 7955
 7956            AddSelectionsState { above, stack }
 7957        });
 7958
 7959        let last_added_selection = *state.stack.last().unwrap();
 7960        let mut new_selections = Vec::new();
 7961        if above == state.above {
 7962            let end_row = if above {
 7963                DisplayRow(0)
 7964            } else {
 7965                display_map.max_point().row()
 7966            };
 7967
 7968            'outer: for selection in selections {
 7969                if selection.id == last_added_selection {
 7970                    let range = selection.display_range(&display_map).sorted();
 7971                    debug_assert_eq!(range.start.row(), range.end.row());
 7972                    let mut row = range.start.row();
 7973                    let positions =
 7974                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7975                            px(start)..px(end)
 7976                        } else {
 7977                            let start_x =
 7978                                display_map.x_for_display_point(range.start, &text_layout_details);
 7979                            let end_x =
 7980                                display_map.x_for_display_point(range.end, &text_layout_details);
 7981                            start_x.min(end_x)..start_x.max(end_x)
 7982                        };
 7983
 7984                    while row != end_row {
 7985                        if above {
 7986                            row.0 -= 1;
 7987                        } else {
 7988                            row.0 += 1;
 7989                        }
 7990
 7991                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7992                            &display_map,
 7993                            row,
 7994                            &positions,
 7995                            selection.reversed,
 7996                            &text_layout_details,
 7997                        ) {
 7998                            state.stack.push(new_selection.id);
 7999                            if above {
 8000                                new_selections.push(new_selection);
 8001                                new_selections.push(selection);
 8002                            } else {
 8003                                new_selections.push(selection);
 8004                                new_selections.push(new_selection);
 8005                            }
 8006
 8007                            continue 'outer;
 8008                        }
 8009                    }
 8010                }
 8011
 8012                new_selections.push(selection);
 8013            }
 8014        } else {
 8015            new_selections = selections;
 8016            new_selections.retain(|s| s.id != last_added_selection);
 8017            state.stack.pop();
 8018        }
 8019
 8020        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8021            s.select(new_selections);
 8022        });
 8023        if state.stack.len() > 1 {
 8024            self.add_selections_state = Some(state);
 8025        }
 8026    }
 8027
 8028    pub fn select_next_match_internal(
 8029        &mut self,
 8030        display_map: &DisplaySnapshot,
 8031        replace_newest: bool,
 8032        autoscroll: Option<Autoscroll>,
 8033        cx: &mut ViewContext<Self>,
 8034    ) -> Result<()> {
 8035        fn select_next_match_ranges(
 8036            this: &mut Editor,
 8037            range: Range<usize>,
 8038            replace_newest: bool,
 8039            auto_scroll: Option<Autoscroll>,
 8040            cx: &mut ViewContext<Editor>,
 8041        ) {
 8042            this.unfold_ranges(&[range.clone()], false, true, cx);
 8043            this.change_selections(auto_scroll, cx, |s| {
 8044                if replace_newest {
 8045                    s.delete(s.newest_anchor().id);
 8046                }
 8047                s.insert_range(range.clone());
 8048            });
 8049        }
 8050
 8051        let buffer = &display_map.buffer_snapshot;
 8052        let mut selections = self.selections.all::<usize>(cx);
 8053        if let Some(mut select_next_state) = self.select_next_state.take() {
 8054            let query = &select_next_state.query;
 8055            if !select_next_state.done {
 8056                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8057                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8058                let mut next_selected_range = None;
 8059
 8060                let bytes_after_last_selection =
 8061                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8062                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8063                let query_matches = query
 8064                    .stream_find_iter(bytes_after_last_selection)
 8065                    .map(|result| (last_selection.end, result))
 8066                    .chain(
 8067                        query
 8068                            .stream_find_iter(bytes_before_first_selection)
 8069                            .map(|result| (0, result)),
 8070                    );
 8071
 8072                for (start_offset, query_match) in query_matches {
 8073                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8074                    let offset_range =
 8075                        start_offset + query_match.start()..start_offset + query_match.end();
 8076                    let display_range = offset_range.start.to_display_point(display_map)
 8077                        ..offset_range.end.to_display_point(display_map);
 8078
 8079                    if !select_next_state.wordwise
 8080                        || (!movement::is_inside_word(display_map, display_range.start)
 8081                            && !movement::is_inside_word(display_map, display_range.end))
 8082                    {
 8083                        // TODO: This is n^2, because we might check all the selections
 8084                        if !selections
 8085                            .iter()
 8086                            .any(|selection| selection.range().overlaps(&offset_range))
 8087                        {
 8088                            next_selected_range = Some(offset_range);
 8089                            break;
 8090                        }
 8091                    }
 8092                }
 8093
 8094                if let Some(next_selected_range) = next_selected_range {
 8095                    select_next_match_ranges(
 8096                        self,
 8097                        next_selected_range,
 8098                        replace_newest,
 8099                        autoscroll,
 8100                        cx,
 8101                    );
 8102                } else {
 8103                    select_next_state.done = true;
 8104                }
 8105            }
 8106
 8107            self.select_next_state = Some(select_next_state);
 8108        } else {
 8109            let mut only_carets = true;
 8110            let mut same_text_selected = true;
 8111            let mut selected_text = None;
 8112
 8113            let mut selections_iter = selections.iter().peekable();
 8114            while let Some(selection) = selections_iter.next() {
 8115                if selection.start != selection.end {
 8116                    only_carets = false;
 8117                }
 8118
 8119                if same_text_selected {
 8120                    if selected_text.is_none() {
 8121                        selected_text =
 8122                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8123                    }
 8124
 8125                    if let Some(next_selection) = selections_iter.peek() {
 8126                        if next_selection.range().len() == selection.range().len() {
 8127                            let next_selected_text = buffer
 8128                                .text_for_range(next_selection.range())
 8129                                .collect::<String>();
 8130                            if Some(next_selected_text) != selected_text {
 8131                                same_text_selected = false;
 8132                                selected_text = None;
 8133                            }
 8134                        } else {
 8135                            same_text_selected = false;
 8136                            selected_text = None;
 8137                        }
 8138                    }
 8139                }
 8140            }
 8141
 8142            if only_carets {
 8143                for selection in &mut selections {
 8144                    let word_range = movement::surrounding_word(
 8145                        display_map,
 8146                        selection.start.to_display_point(display_map),
 8147                    );
 8148                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8149                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8150                    selection.goal = SelectionGoal::None;
 8151                    selection.reversed = false;
 8152                    select_next_match_ranges(
 8153                        self,
 8154                        selection.start..selection.end,
 8155                        replace_newest,
 8156                        autoscroll,
 8157                        cx,
 8158                    );
 8159                }
 8160
 8161                if selections.len() == 1 {
 8162                    let selection = selections
 8163                        .last()
 8164                        .expect("ensured that there's only one selection");
 8165                    let query = buffer
 8166                        .text_for_range(selection.start..selection.end)
 8167                        .collect::<String>();
 8168                    let is_empty = query.is_empty();
 8169                    let select_state = SelectNextState {
 8170                        query: AhoCorasick::new(&[query])?,
 8171                        wordwise: true,
 8172                        done: is_empty,
 8173                    };
 8174                    self.select_next_state = Some(select_state);
 8175                } else {
 8176                    self.select_next_state = None;
 8177                }
 8178            } else if let Some(selected_text) = selected_text {
 8179                self.select_next_state = Some(SelectNextState {
 8180                    query: AhoCorasick::new(&[selected_text])?,
 8181                    wordwise: false,
 8182                    done: false,
 8183                });
 8184                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8185            }
 8186        }
 8187        Ok(())
 8188    }
 8189
 8190    pub fn select_all_matches(
 8191        &mut self,
 8192        _action: &SelectAllMatches,
 8193        cx: &mut ViewContext<Self>,
 8194    ) -> Result<()> {
 8195        self.push_to_selection_history();
 8196        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8197
 8198        self.select_next_match_internal(&display_map, false, None, cx)?;
 8199        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8200            return Ok(());
 8201        };
 8202        if select_next_state.done {
 8203            return Ok(());
 8204        }
 8205
 8206        let mut new_selections = self.selections.all::<usize>(cx);
 8207
 8208        let buffer = &display_map.buffer_snapshot;
 8209        let query_matches = select_next_state
 8210            .query
 8211            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8212
 8213        for query_match in query_matches {
 8214            let query_match = query_match.unwrap(); // can only fail due to I/O
 8215            let offset_range = query_match.start()..query_match.end();
 8216            let display_range = offset_range.start.to_display_point(&display_map)
 8217                ..offset_range.end.to_display_point(&display_map);
 8218
 8219            if !select_next_state.wordwise
 8220                || (!movement::is_inside_word(&display_map, display_range.start)
 8221                    && !movement::is_inside_word(&display_map, display_range.end))
 8222            {
 8223                self.selections.change_with(cx, |selections| {
 8224                    new_selections.push(Selection {
 8225                        id: selections.new_selection_id(),
 8226                        start: offset_range.start,
 8227                        end: offset_range.end,
 8228                        reversed: false,
 8229                        goal: SelectionGoal::None,
 8230                    });
 8231                });
 8232            }
 8233        }
 8234
 8235        new_selections.sort_by_key(|selection| selection.start);
 8236        let mut ix = 0;
 8237        while ix + 1 < new_selections.len() {
 8238            let current_selection = &new_selections[ix];
 8239            let next_selection = &new_selections[ix + 1];
 8240            if current_selection.range().overlaps(&next_selection.range()) {
 8241                if current_selection.id < next_selection.id {
 8242                    new_selections.remove(ix + 1);
 8243                } else {
 8244                    new_selections.remove(ix);
 8245                }
 8246            } else {
 8247                ix += 1;
 8248            }
 8249        }
 8250
 8251        select_next_state.done = true;
 8252        self.unfold_ranges(
 8253            &new_selections
 8254                .iter()
 8255                .map(|selection| selection.range())
 8256                .collect::<Vec<_>>(),
 8257            false,
 8258            false,
 8259            cx,
 8260        );
 8261        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8262            selections.select(new_selections)
 8263        });
 8264
 8265        Ok(())
 8266    }
 8267
 8268    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8269        self.push_to_selection_history();
 8270        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8271        self.select_next_match_internal(
 8272            &display_map,
 8273            action.replace_newest,
 8274            Some(Autoscroll::newest()),
 8275            cx,
 8276        )?;
 8277        Ok(())
 8278    }
 8279
 8280    pub fn select_previous(
 8281        &mut self,
 8282        action: &SelectPrevious,
 8283        cx: &mut ViewContext<Self>,
 8284    ) -> Result<()> {
 8285        self.push_to_selection_history();
 8286        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8287        let buffer = &display_map.buffer_snapshot;
 8288        let mut selections = self.selections.all::<usize>(cx);
 8289        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8290            let query = &select_prev_state.query;
 8291            if !select_prev_state.done {
 8292                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8293                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8294                let mut next_selected_range = None;
 8295                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8296                let bytes_before_last_selection =
 8297                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8298                let bytes_after_first_selection =
 8299                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8300                let query_matches = query
 8301                    .stream_find_iter(bytes_before_last_selection)
 8302                    .map(|result| (last_selection.start, result))
 8303                    .chain(
 8304                        query
 8305                            .stream_find_iter(bytes_after_first_selection)
 8306                            .map(|result| (buffer.len(), result)),
 8307                    );
 8308                for (end_offset, query_match) in query_matches {
 8309                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8310                    let offset_range =
 8311                        end_offset - query_match.end()..end_offset - query_match.start();
 8312                    let display_range = offset_range.start.to_display_point(&display_map)
 8313                        ..offset_range.end.to_display_point(&display_map);
 8314
 8315                    if !select_prev_state.wordwise
 8316                        || (!movement::is_inside_word(&display_map, display_range.start)
 8317                            && !movement::is_inside_word(&display_map, display_range.end))
 8318                    {
 8319                        next_selected_range = Some(offset_range);
 8320                        break;
 8321                    }
 8322                }
 8323
 8324                if let Some(next_selected_range) = next_selected_range {
 8325                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8326                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8327                        if action.replace_newest {
 8328                            s.delete(s.newest_anchor().id);
 8329                        }
 8330                        s.insert_range(next_selected_range);
 8331                    });
 8332                } else {
 8333                    select_prev_state.done = true;
 8334                }
 8335            }
 8336
 8337            self.select_prev_state = Some(select_prev_state);
 8338        } else {
 8339            let mut only_carets = true;
 8340            let mut same_text_selected = true;
 8341            let mut selected_text = None;
 8342
 8343            let mut selections_iter = selections.iter().peekable();
 8344            while let Some(selection) = selections_iter.next() {
 8345                if selection.start != selection.end {
 8346                    only_carets = false;
 8347                }
 8348
 8349                if same_text_selected {
 8350                    if selected_text.is_none() {
 8351                        selected_text =
 8352                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8353                    }
 8354
 8355                    if let Some(next_selection) = selections_iter.peek() {
 8356                        if next_selection.range().len() == selection.range().len() {
 8357                            let next_selected_text = buffer
 8358                                .text_for_range(next_selection.range())
 8359                                .collect::<String>();
 8360                            if Some(next_selected_text) != selected_text {
 8361                                same_text_selected = false;
 8362                                selected_text = None;
 8363                            }
 8364                        } else {
 8365                            same_text_selected = false;
 8366                            selected_text = None;
 8367                        }
 8368                    }
 8369                }
 8370            }
 8371
 8372            if only_carets {
 8373                for selection in &mut selections {
 8374                    let word_range = movement::surrounding_word(
 8375                        &display_map,
 8376                        selection.start.to_display_point(&display_map),
 8377                    );
 8378                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8379                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8380                    selection.goal = SelectionGoal::None;
 8381                    selection.reversed = false;
 8382                }
 8383                if selections.len() == 1 {
 8384                    let selection = selections
 8385                        .last()
 8386                        .expect("ensured that there's only one selection");
 8387                    let query = buffer
 8388                        .text_for_range(selection.start..selection.end)
 8389                        .collect::<String>();
 8390                    let is_empty = query.is_empty();
 8391                    let select_state = SelectNextState {
 8392                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8393                        wordwise: true,
 8394                        done: is_empty,
 8395                    };
 8396                    self.select_prev_state = Some(select_state);
 8397                } else {
 8398                    self.select_prev_state = None;
 8399                }
 8400
 8401                self.unfold_ranges(
 8402                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8403                    false,
 8404                    true,
 8405                    cx,
 8406                );
 8407                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8408                    s.select(selections);
 8409                });
 8410            } else if let Some(selected_text) = selected_text {
 8411                self.select_prev_state = Some(SelectNextState {
 8412                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8413                    wordwise: false,
 8414                    done: false,
 8415                });
 8416                self.select_previous(action, cx)?;
 8417            }
 8418        }
 8419        Ok(())
 8420    }
 8421
 8422    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8423        if self.read_only(cx) {
 8424            return;
 8425        }
 8426        let text_layout_details = &self.text_layout_details(cx);
 8427        self.transact(cx, |this, cx| {
 8428            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8429            let mut edits = Vec::new();
 8430            let mut selection_edit_ranges = Vec::new();
 8431            let mut last_toggled_row = None;
 8432            let snapshot = this.buffer.read(cx).read(cx);
 8433            let empty_str: Arc<str> = Arc::default();
 8434            let mut suffixes_inserted = Vec::new();
 8435            let ignore_indent = action.ignore_indent;
 8436
 8437            fn comment_prefix_range(
 8438                snapshot: &MultiBufferSnapshot,
 8439                row: MultiBufferRow,
 8440                comment_prefix: &str,
 8441                comment_prefix_whitespace: &str,
 8442                ignore_indent: bool,
 8443            ) -> Range<Point> {
 8444                let indent_size = if ignore_indent {
 8445                    0
 8446                } else {
 8447                    snapshot.indent_size_for_line(row).len
 8448                };
 8449
 8450                let start = Point::new(row.0, indent_size);
 8451
 8452                let mut line_bytes = snapshot
 8453                    .bytes_in_range(start..snapshot.max_point())
 8454                    .flatten()
 8455                    .copied();
 8456
 8457                // If this line currently begins with the line comment prefix, then record
 8458                // the range containing the prefix.
 8459                if line_bytes
 8460                    .by_ref()
 8461                    .take(comment_prefix.len())
 8462                    .eq(comment_prefix.bytes())
 8463                {
 8464                    // Include any whitespace that matches the comment prefix.
 8465                    let matching_whitespace_len = line_bytes
 8466                        .zip(comment_prefix_whitespace.bytes())
 8467                        .take_while(|(a, b)| a == b)
 8468                        .count() as u32;
 8469                    let end = Point::new(
 8470                        start.row,
 8471                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8472                    );
 8473                    start..end
 8474                } else {
 8475                    start..start
 8476                }
 8477            }
 8478
 8479            fn comment_suffix_range(
 8480                snapshot: &MultiBufferSnapshot,
 8481                row: MultiBufferRow,
 8482                comment_suffix: &str,
 8483                comment_suffix_has_leading_space: bool,
 8484            ) -> Range<Point> {
 8485                let end = Point::new(row.0, snapshot.line_len(row));
 8486                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8487
 8488                let mut line_end_bytes = snapshot
 8489                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8490                    .flatten()
 8491                    .copied();
 8492
 8493                let leading_space_len = if suffix_start_column > 0
 8494                    && line_end_bytes.next() == Some(b' ')
 8495                    && comment_suffix_has_leading_space
 8496                {
 8497                    1
 8498                } else {
 8499                    0
 8500                };
 8501
 8502                // If this line currently begins with the line comment prefix, then record
 8503                // the range containing the prefix.
 8504                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8505                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8506                    start..end
 8507                } else {
 8508                    end..end
 8509                }
 8510            }
 8511
 8512            // TODO: Handle selections that cross excerpts
 8513            for selection in &mut selections {
 8514                let start_column = snapshot
 8515                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8516                    .len;
 8517                let language = if let Some(language) =
 8518                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8519                {
 8520                    language
 8521                } else {
 8522                    continue;
 8523                };
 8524
 8525                selection_edit_ranges.clear();
 8526
 8527                // If multiple selections contain a given row, avoid processing that
 8528                // row more than once.
 8529                let mut start_row = MultiBufferRow(selection.start.row);
 8530                if last_toggled_row == Some(start_row) {
 8531                    start_row = start_row.next_row();
 8532                }
 8533                let end_row =
 8534                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8535                        MultiBufferRow(selection.end.row - 1)
 8536                    } else {
 8537                        MultiBufferRow(selection.end.row)
 8538                    };
 8539                last_toggled_row = Some(end_row);
 8540
 8541                if start_row > end_row {
 8542                    continue;
 8543                }
 8544
 8545                // If the language has line comments, toggle those.
 8546                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8547
 8548                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8549                if ignore_indent {
 8550                    full_comment_prefixes = full_comment_prefixes
 8551                        .into_iter()
 8552                        .map(|s| Arc::from(s.trim_end()))
 8553                        .collect();
 8554                }
 8555
 8556                if !full_comment_prefixes.is_empty() {
 8557                    let first_prefix = full_comment_prefixes
 8558                        .first()
 8559                        .expect("prefixes is non-empty");
 8560                    let prefix_trimmed_lengths = full_comment_prefixes
 8561                        .iter()
 8562                        .map(|p| p.trim_end_matches(' ').len())
 8563                        .collect::<SmallVec<[usize; 4]>>();
 8564
 8565                    let mut all_selection_lines_are_comments = true;
 8566
 8567                    for row in start_row.0..=end_row.0 {
 8568                        let row = MultiBufferRow(row);
 8569                        if start_row < end_row && snapshot.is_line_blank(row) {
 8570                            continue;
 8571                        }
 8572
 8573                        let prefix_range = full_comment_prefixes
 8574                            .iter()
 8575                            .zip(prefix_trimmed_lengths.iter().copied())
 8576                            .map(|(prefix, trimmed_prefix_len)| {
 8577                                comment_prefix_range(
 8578                                    snapshot.deref(),
 8579                                    row,
 8580                                    &prefix[..trimmed_prefix_len],
 8581                                    &prefix[trimmed_prefix_len..],
 8582                                    ignore_indent,
 8583                                )
 8584                            })
 8585                            .max_by_key(|range| range.end.column - range.start.column)
 8586                            .expect("prefixes is non-empty");
 8587
 8588                        if prefix_range.is_empty() {
 8589                            all_selection_lines_are_comments = false;
 8590                        }
 8591
 8592                        selection_edit_ranges.push(prefix_range);
 8593                    }
 8594
 8595                    if all_selection_lines_are_comments {
 8596                        edits.extend(
 8597                            selection_edit_ranges
 8598                                .iter()
 8599                                .cloned()
 8600                                .map(|range| (range, empty_str.clone())),
 8601                        );
 8602                    } else {
 8603                        let min_column = selection_edit_ranges
 8604                            .iter()
 8605                            .map(|range| range.start.column)
 8606                            .min()
 8607                            .unwrap_or(0);
 8608                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8609                            let position = Point::new(range.start.row, min_column);
 8610                            (position..position, first_prefix.clone())
 8611                        }));
 8612                    }
 8613                } else if let Some((full_comment_prefix, comment_suffix)) =
 8614                    language.block_comment_delimiters()
 8615                {
 8616                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8617                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8618                    let prefix_range = comment_prefix_range(
 8619                        snapshot.deref(),
 8620                        start_row,
 8621                        comment_prefix,
 8622                        comment_prefix_whitespace,
 8623                        ignore_indent,
 8624                    );
 8625                    let suffix_range = comment_suffix_range(
 8626                        snapshot.deref(),
 8627                        end_row,
 8628                        comment_suffix.trim_start_matches(' '),
 8629                        comment_suffix.starts_with(' '),
 8630                    );
 8631
 8632                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8633                        edits.push((
 8634                            prefix_range.start..prefix_range.start,
 8635                            full_comment_prefix.clone(),
 8636                        ));
 8637                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8638                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8639                    } else {
 8640                        edits.push((prefix_range, empty_str.clone()));
 8641                        edits.push((suffix_range, empty_str.clone()));
 8642                    }
 8643                } else {
 8644                    continue;
 8645                }
 8646            }
 8647
 8648            drop(snapshot);
 8649            this.buffer.update(cx, |buffer, cx| {
 8650                buffer.edit(edits, None, cx);
 8651            });
 8652
 8653            // Adjust selections so that they end before any comment suffixes that
 8654            // were inserted.
 8655            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8656            let mut selections = this.selections.all::<Point>(cx);
 8657            let snapshot = this.buffer.read(cx).read(cx);
 8658            for selection in &mut selections {
 8659                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8660                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8661                        Ordering::Less => {
 8662                            suffixes_inserted.next();
 8663                            continue;
 8664                        }
 8665                        Ordering::Greater => break,
 8666                        Ordering::Equal => {
 8667                            if selection.end.column == snapshot.line_len(row) {
 8668                                if selection.is_empty() {
 8669                                    selection.start.column -= suffix_len as u32;
 8670                                }
 8671                                selection.end.column -= suffix_len as u32;
 8672                            }
 8673                            break;
 8674                        }
 8675                    }
 8676                }
 8677            }
 8678
 8679            drop(snapshot);
 8680            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8681
 8682            let selections = this.selections.all::<Point>(cx);
 8683            let selections_on_single_row = selections.windows(2).all(|selections| {
 8684                selections[0].start.row == selections[1].start.row
 8685                    && selections[0].end.row == selections[1].end.row
 8686                    && selections[0].start.row == selections[0].end.row
 8687            });
 8688            let selections_selecting = selections
 8689                .iter()
 8690                .any(|selection| selection.start != selection.end);
 8691            let advance_downwards = action.advance_downwards
 8692                && selections_on_single_row
 8693                && !selections_selecting
 8694                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8695
 8696            if advance_downwards {
 8697                let snapshot = this.buffer.read(cx).snapshot(cx);
 8698
 8699                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8700                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8701                        let mut point = display_point.to_point(display_snapshot);
 8702                        point.row += 1;
 8703                        point = snapshot.clip_point(point, Bias::Left);
 8704                        let display_point = point.to_display_point(display_snapshot);
 8705                        let goal = SelectionGoal::HorizontalPosition(
 8706                            display_snapshot
 8707                                .x_for_display_point(display_point, text_layout_details)
 8708                                .into(),
 8709                        );
 8710                        (display_point, goal)
 8711                    })
 8712                });
 8713            }
 8714        });
 8715    }
 8716
 8717    pub fn select_enclosing_symbol(
 8718        &mut self,
 8719        _: &SelectEnclosingSymbol,
 8720        cx: &mut ViewContext<Self>,
 8721    ) {
 8722        let buffer = self.buffer.read(cx).snapshot(cx);
 8723        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8724
 8725        fn update_selection(
 8726            selection: &Selection<usize>,
 8727            buffer_snap: &MultiBufferSnapshot,
 8728        ) -> Option<Selection<usize>> {
 8729            let cursor = selection.head();
 8730            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8731            for symbol in symbols.iter().rev() {
 8732                let start = symbol.range.start.to_offset(buffer_snap);
 8733                let end = symbol.range.end.to_offset(buffer_snap);
 8734                let new_range = start..end;
 8735                if start < selection.start || end > selection.end {
 8736                    return Some(Selection {
 8737                        id: selection.id,
 8738                        start: new_range.start,
 8739                        end: new_range.end,
 8740                        goal: SelectionGoal::None,
 8741                        reversed: selection.reversed,
 8742                    });
 8743                }
 8744            }
 8745            None
 8746        }
 8747
 8748        let mut selected_larger_symbol = false;
 8749        let new_selections = old_selections
 8750            .iter()
 8751            .map(|selection| match update_selection(selection, &buffer) {
 8752                Some(new_selection) => {
 8753                    if new_selection.range() != selection.range() {
 8754                        selected_larger_symbol = true;
 8755                    }
 8756                    new_selection
 8757                }
 8758                None => selection.clone(),
 8759            })
 8760            .collect::<Vec<_>>();
 8761
 8762        if selected_larger_symbol {
 8763            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8764                s.select(new_selections);
 8765            });
 8766        }
 8767    }
 8768
 8769    pub fn select_larger_syntax_node(
 8770        &mut self,
 8771        _: &SelectLargerSyntaxNode,
 8772        cx: &mut ViewContext<Self>,
 8773    ) {
 8774        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8775        let buffer = self.buffer.read(cx).snapshot(cx);
 8776        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8777
 8778        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8779        let mut selected_larger_node = false;
 8780        let new_selections = old_selections
 8781            .iter()
 8782            .map(|selection| {
 8783                let old_range = selection.start..selection.end;
 8784                let mut new_range = old_range.clone();
 8785                let mut new_node = None;
 8786                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8787                {
 8788                    new_node = Some(node);
 8789                    new_range = containing_range;
 8790                    if !display_map.intersects_fold(new_range.start)
 8791                        && !display_map.intersects_fold(new_range.end)
 8792                    {
 8793                        break;
 8794                    }
 8795                }
 8796
 8797                if let Some(node) = new_node {
 8798                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8799                    // nodes. Parent and grandparent are also logged because this operation will not
 8800                    // visit nodes that have the same range as their parent.
 8801                    log::info!("Node: {node:?}");
 8802                    let parent = node.parent();
 8803                    log::info!("Parent: {parent:?}");
 8804                    let grandparent = parent.and_then(|x| x.parent());
 8805                    log::info!("Grandparent: {grandparent:?}");
 8806                }
 8807
 8808                selected_larger_node |= new_range != old_range;
 8809                Selection {
 8810                    id: selection.id,
 8811                    start: new_range.start,
 8812                    end: new_range.end,
 8813                    goal: SelectionGoal::None,
 8814                    reversed: selection.reversed,
 8815                }
 8816            })
 8817            .collect::<Vec<_>>();
 8818
 8819        if selected_larger_node {
 8820            stack.push(old_selections);
 8821            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8822                s.select(new_selections);
 8823            });
 8824        }
 8825        self.select_larger_syntax_node_stack = stack;
 8826    }
 8827
 8828    pub fn select_smaller_syntax_node(
 8829        &mut self,
 8830        _: &SelectSmallerSyntaxNode,
 8831        cx: &mut ViewContext<Self>,
 8832    ) {
 8833        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8834        if let Some(selections) = stack.pop() {
 8835            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8836                s.select(selections.to_vec());
 8837            });
 8838        }
 8839        self.select_larger_syntax_node_stack = stack;
 8840    }
 8841
 8842    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8843        if !EditorSettings::get_global(cx).gutter.runnables {
 8844            self.clear_tasks();
 8845            return Task::ready(());
 8846        }
 8847        let project = self.project.as_ref().map(Model::downgrade);
 8848        cx.spawn(|this, mut cx| async move {
 8849            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8850            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8851                return;
 8852            };
 8853            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8854                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8855            }) else {
 8856                return;
 8857            };
 8858
 8859            let hide_runnables = project
 8860                .update(&mut cx, |project, cx| {
 8861                    // Do not display any test indicators in non-dev server remote projects.
 8862                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8863                })
 8864                .unwrap_or(true);
 8865            if hide_runnables {
 8866                return;
 8867            }
 8868            let new_rows =
 8869                cx.background_executor()
 8870                    .spawn({
 8871                        let snapshot = display_snapshot.clone();
 8872                        async move {
 8873                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8874                        }
 8875                    })
 8876                    .await;
 8877            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8878
 8879            this.update(&mut cx, |this, _| {
 8880                this.clear_tasks();
 8881                for (key, value) in rows {
 8882                    this.insert_tasks(key, value);
 8883                }
 8884            })
 8885            .ok();
 8886        })
 8887    }
 8888    fn fetch_runnable_ranges(
 8889        snapshot: &DisplaySnapshot,
 8890        range: Range<Anchor>,
 8891    ) -> Vec<language::RunnableRange> {
 8892        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8893    }
 8894
 8895    fn runnable_rows(
 8896        project: Model<Project>,
 8897        snapshot: DisplaySnapshot,
 8898        runnable_ranges: Vec<RunnableRange>,
 8899        mut cx: AsyncWindowContext,
 8900    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8901        runnable_ranges
 8902            .into_iter()
 8903            .filter_map(|mut runnable| {
 8904                let tasks = cx
 8905                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8906                    .ok()?;
 8907                if tasks.is_empty() {
 8908                    return None;
 8909                }
 8910
 8911                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8912
 8913                let row = snapshot
 8914                    .buffer_snapshot
 8915                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8916                    .1
 8917                    .start
 8918                    .row;
 8919
 8920                let context_range =
 8921                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8922                Some((
 8923                    (runnable.buffer_id, row),
 8924                    RunnableTasks {
 8925                        templates: tasks,
 8926                        offset: MultiBufferOffset(runnable.run_range.start),
 8927                        context_range,
 8928                        column: point.column,
 8929                        extra_variables: runnable.extra_captures,
 8930                    },
 8931                ))
 8932            })
 8933            .collect()
 8934    }
 8935
 8936    fn templates_with_tags(
 8937        project: &Model<Project>,
 8938        runnable: &mut Runnable,
 8939        cx: &WindowContext<'_>,
 8940    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8941        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8942            let (worktree_id, file) = project
 8943                .buffer_for_id(runnable.buffer, cx)
 8944                .and_then(|buffer| buffer.read(cx).file())
 8945                .map(|file| (file.worktree_id(cx), file.clone()))
 8946                .unzip();
 8947
 8948            (
 8949                project.task_store().read(cx).task_inventory().cloned(),
 8950                worktree_id,
 8951                file,
 8952            )
 8953        });
 8954
 8955        let tags = mem::take(&mut runnable.tags);
 8956        let mut tags: Vec<_> = tags
 8957            .into_iter()
 8958            .flat_map(|tag| {
 8959                let tag = tag.0.clone();
 8960                inventory
 8961                    .as_ref()
 8962                    .into_iter()
 8963                    .flat_map(|inventory| {
 8964                        inventory.read(cx).list_tasks(
 8965                            file.clone(),
 8966                            Some(runnable.language.clone()),
 8967                            worktree_id,
 8968                            cx,
 8969                        )
 8970                    })
 8971                    .filter(move |(_, template)| {
 8972                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8973                    })
 8974            })
 8975            .sorted_by_key(|(kind, _)| kind.to_owned())
 8976            .collect();
 8977        if let Some((leading_tag_source, _)) = tags.first() {
 8978            // Strongest source wins; if we have worktree tag binding, prefer that to
 8979            // global and language bindings;
 8980            // if we have a global binding, prefer that to language binding.
 8981            let first_mismatch = tags
 8982                .iter()
 8983                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8984            if let Some(index) = first_mismatch {
 8985                tags.truncate(index);
 8986            }
 8987        }
 8988
 8989        tags
 8990    }
 8991
 8992    pub fn move_to_enclosing_bracket(
 8993        &mut self,
 8994        _: &MoveToEnclosingBracket,
 8995        cx: &mut ViewContext<Self>,
 8996    ) {
 8997        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8998            s.move_offsets_with(|snapshot, selection| {
 8999                let Some(enclosing_bracket_ranges) =
 9000                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9001                else {
 9002                    return;
 9003                };
 9004
 9005                let mut best_length = usize::MAX;
 9006                let mut best_inside = false;
 9007                let mut best_in_bracket_range = false;
 9008                let mut best_destination = None;
 9009                for (open, close) in enclosing_bracket_ranges {
 9010                    let close = close.to_inclusive();
 9011                    let length = close.end() - open.start;
 9012                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9013                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9014                        || close.contains(&selection.head());
 9015
 9016                    // If best is next to a bracket and current isn't, skip
 9017                    if !in_bracket_range && best_in_bracket_range {
 9018                        continue;
 9019                    }
 9020
 9021                    // Prefer smaller lengths unless best is inside and current isn't
 9022                    if length > best_length && (best_inside || !inside) {
 9023                        continue;
 9024                    }
 9025
 9026                    best_length = length;
 9027                    best_inside = inside;
 9028                    best_in_bracket_range = in_bracket_range;
 9029                    best_destination = Some(
 9030                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9031                            if inside {
 9032                                open.end
 9033                            } else {
 9034                                open.start
 9035                            }
 9036                        } else if inside {
 9037                            *close.start()
 9038                        } else {
 9039                            *close.end()
 9040                        },
 9041                    );
 9042                }
 9043
 9044                if let Some(destination) = best_destination {
 9045                    selection.collapse_to(destination, SelectionGoal::None);
 9046                }
 9047            })
 9048        });
 9049    }
 9050
 9051    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9052        self.end_selection(cx);
 9053        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9054        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9055            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9056            self.select_next_state = entry.select_next_state;
 9057            self.select_prev_state = entry.select_prev_state;
 9058            self.add_selections_state = entry.add_selections_state;
 9059            self.request_autoscroll(Autoscroll::newest(), cx);
 9060        }
 9061        self.selection_history.mode = SelectionHistoryMode::Normal;
 9062    }
 9063
 9064    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9065        self.end_selection(cx);
 9066        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9067        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9068            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9069            self.select_next_state = entry.select_next_state;
 9070            self.select_prev_state = entry.select_prev_state;
 9071            self.add_selections_state = entry.add_selections_state;
 9072            self.request_autoscroll(Autoscroll::newest(), cx);
 9073        }
 9074        self.selection_history.mode = SelectionHistoryMode::Normal;
 9075    }
 9076
 9077    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9078        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9079    }
 9080
 9081    pub fn expand_excerpts_down(
 9082        &mut self,
 9083        action: &ExpandExcerptsDown,
 9084        cx: &mut ViewContext<Self>,
 9085    ) {
 9086        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9087    }
 9088
 9089    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9090        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9091    }
 9092
 9093    pub fn expand_excerpts_for_direction(
 9094        &mut self,
 9095        lines: u32,
 9096        direction: ExpandExcerptDirection,
 9097        cx: &mut ViewContext<Self>,
 9098    ) {
 9099        let selections = self.selections.disjoint_anchors();
 9100
 9101        let lines = if lines == 0 {
 9102            EditorSettings::get_global(cx).expand_excerpt_lines
 9103        } else {
 9104            lines
 9105        };
 9106
 9107        self.buffer.update(cx, |buffer, cx| {
 9108            buffer.expand_excerpts(
 9109                selections
 9110                    .iter()
 9111                    .map(|selection| selection.head().excerpt_id)
 9112                    .dedup(),
 9113                lines,
 9114                direction,
 9115                cx,
 9116            )
 9117        })
 9118    }
 9119
 9120    pub fn expand_excerpt(
 9121        &mut self,
 9122        excerpt: ExcerptId,
 9123        direction: ExpandExcerptDirection,
 9124        cx: &mut ViewContext<Self>,
 9125    ) {
 9126        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9127        self.buffer.update(cx, |buffer, cx| {
 9128            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9129        })
 9130    }
 9131
 9132    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9133        self.go_to_diagnostic_impl(Direction::Next, cx)
 9134    }
 9135
 9136    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9137        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9138    }
 9139
 9140    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9141        let buffer = self.buffer.read(cx).snapshot(cx);
 9142        let selection = self.selections.newest::<usize>(cx);
 9143
 9144        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9145        if direction == Direction::Next {
 9146            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9147                let (group_id, jump_to) = popover.activation_info();
 9148                if self.activate_diagnostics(group_id, cx) {
 9149                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9150                        let mut new_selection = s.newest_anchor().clone();
 9151                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9152                        s.select_anchors(vec![new_selection.clone()]);
 9153                    });
 9154                }
 9155                return;
 9156            }
 9157        }
 9158
 9159        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9160            active_diagnostics
 9161                .primary_range
 9162                .to_offset(&buffer)
 9163                .to_inclusive()
 9164        });
 9165        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9166            if active_primary_range.contains(&selection.head()) {
 9167                *active_primary_range.start()
 9168            } else {
 9169                selection.head()
 9170            }
 9171        } else {
 9172            selection.head()
 9173        };
 9174        let snapshot = self.snapshot(cx);
 9175        loop {
 9176            let diagnostics = if direction == Direction::Prev {
 9177                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9178            } else {
 9179                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9180            }
 9181            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9182            let group = diagnostics
 9183                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9184                // be sorted in a stable way
 9185                // skip until we are at current active diagnostic, if it exists
 9186                .skip_while(|entry| {
 9187                    (match direction {
 9188                        Direction::Prev => entry.range.start >= search_start,
 9189                        Direction::Next => entry.range.start <= search_start,
 9190                    }) && self
 9191                        .active_diagnostics
 9192                        .as_ref()
 9193                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9194                })
 9195                .find_map(|entry| {
 9196                    if entry.diagnostic.is_primary
 9197                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9198                        && !entry.range.is_empty()
 9199                        // if we match with the active diagnostic, skip it
 9200                        && Some(entry.diagnostic.group_id)
 9201                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9202                    {
 9203                        Some((entry.range, entry.diagnostic.group_id))
 9204                    } else {
 9205                        None
 9206                    }
 9207                });
 9208
 9209            if let Some((primary_range, group_id)) = group {
 9210                if self.activate_diagnostics(group_id, cx) {
 9211                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9212                        s.select(vec![Selection {
 9213                            id: selection.id,
 9214                            start: primary_range.start,
 9215                            end: primary_range.start,
 9216                            reversed: false,
 9217                            goal: SelectionGoal::None,
 9218                        }]);
 9219                    });
 9220                }
 9221                break;
 9222            } else {
 9223                // Cycle around to the start of the buffer, potentially moving back to the start of
 9224                // the currently active diagnostic.
 9225                active_primary_range.take();
 9226                if direction == Direction::Prev {
 9227                    if search_start == buffer.len() {
 9228                        break;
 9229                    } else {
 9230                        search_start = buffer.len();
 9231                    }
 9232                } else if search_start == 0 {
 9233                    break;
 9234                } else {
 9235                    search_start = 0;
 9236                }
 9237            }
 9238        }
 9239    }
 9240
 9241    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9242        let snapshot = self.snapshot(cx);
 9243        let selection = self.selections.newest::<Point>(cx);
 9244        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9245    }
 9246
 9247    fn go_to_hunk_after_position(
 9248        &mut self,
 9249        snapshot: &EditorSnapshot,
 9250        position: Point,
 9251        cx: &mut ViewContext<'_, Editor>,
 9252    ) -> Option<MultiBufferDiffHunk> {
 9253        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9254            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9255                snapshot,
 9256                position,
 9257                ix > 0,
 9258                snapshot.diff_map.diff_hunks_in_range(
 9259                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9260                    &snapshot.buffer_snapshot,
 9261                ),
 9262                cx,
 9263            ) {
 9264                return Some(hunk);
 9265            }
 9266        }
 9267        None
 9268    }
 9269
 9270    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9271        let snapshot = self.snapshot(cx);
 9272        let selection = self.selections.newest::<Point>(cx);
 9273        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9274    }
 9275
 9276    fn go_to_hunk_before_position(
 9277        &mut self,
 9278        snapshot: &EditorSnapshot,
 9279        position: Point,
 9280        cx: &mut ViewContext<'_, Editor>,
 9281    ) -> Option<MultiBufferDiffHunk> {
 9282        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9283            .into_iter()
 9284            .enumerate()
 9285        {
 9286            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9287                snapshot,
 9288                position,
 9289                ix > 0,
 9290                snapshot
 9291                    .diff_map
 9292                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9293                cx,
 9294            ) {
 9295                return Some(hunk);
 9296            }
 9297        }
 9298        None
 9299    }
 9300
 9301    fn go_to_next_hunk_in_direction(
 9302        &mut self,
 9303        snapshot: &DisplaySnapshot,
 9304        initial_point: Point,
 9305        is_wrapped: bool,
 9306        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9307        cx: &mut ViewContext<Editor>,
 9308    ) -> Option<MultiBufferDiffHunk> {
 9309        let display_point = initial_point.to_display_point(snapshot);
 9310        let mut hunks = hunks
 9311            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9312            .filter(|(display_hunk, _)| {
 9313                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9314            })
 9315            .dedup();
 9316
 9317        if let Some((display_hunk, hunk)) = hunks.next() {
 9318            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9319                let row = display_hunk.start_display_row();
 9320                let point = DisplayPoint::new(row, 0);
 9321                s.select_display_ranges([point..point]);
 9322            });
 9323
 9324            Some(hunk)
 9325        } else {
 9326            None
 9327        }
 9328    }
 9329
 9330    pub fn go_to_definition(
 9331        &mut self,
 9332        _: &GoToDefinition,
 9333        cx: &mut ViewContext<Self>,
 9334    ) -> Task<Result<Navigated>> {
 9335        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9336        cx.spawn(|editor, mut cx| async move {
 9337            if definition.await? == Navigated::Yes {
 9338                return Ok(Navigated::Yes);
 9339            }
 9340            match editor.update(&mut cx, |editor, cx| {
 9341                editor.find_all_references(&FindAllReferences, cx)
 9342            })? {
 9343                Some(references) => references.await,
 9344                None => Ok(Navigated::No),
 9345            }
 9346        })
 9347    }
 9348
 9349    pub fn go_to_declaration(
 9350        &mut self,
 9351        _: &GoToDeclaration,
 9352        cx: &mut ViewContext<Self>,
 9353    ) -> Task<Result<Navigated>> {
 9354        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9355    }
 9356
 9357    pub fn go_to_declaration_split(
 9358        &mut self,
 9359        _: &GoToDeclaration,
 9360        cx: &mut ViewContext<Self>,
 9361    ) -> Task<Result<Navigated>> {
 9362        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9363    }
 9364
 9365    pub fn go_to_implementation(
 9366        &mut self,
 9367        _: &GoToImplementation,
 9368        cx: &mut ViewContext<Self>,
 9369    ) -> Task<Result<Navigated>> {
 9370        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9371    }
 9372
 9373    pub fn go_to_implementation_split(
 9374        &mut self,
 9375        _: &GoToImplementationSplit,
 9376        cx: &mut ViewContext<Self>,
 9377    ) -> Task<Result<Navigated>> {
 9378        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9379    }
 9380
 9381    pub fn go_to_type_definition(
 9382        &mut self,
 9383        _: &GoToTypeDefinition,
 9384        cx: &mut ViewContext<Self>,
 9385    ) -> Task<Result<Navigated>> {
 9386        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9387    }
 9388
 9389    pub fn go_to_definition_split(
 9390        &mut self,
 9391        _: &GoToDefinitionSplit,
 9392        cx: &mut ViewContext<Self>,
 9393    ) -> Task<Result<Navigated>> {
 9394        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9395    }
 9396
 9397    pub fn go_to_type_definition_split(
 9398        &mut self,
 9399        _: &GoToTypeDefinitionSplit,
 9400        cx: &mut ViewContext<Self>,
 9401    ) -> Task<Result<Navigated>> {
 9402        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9403    }
 9404
 9405    fn go_to_definition_of_kind(
 9406        &mut self,
 9407        kind: GotoDefinitionKind,
 9408        split: bool,
 9409        cx: &mut ViewContext<Self>,
 9410    ) -> Task<Result<Navigated>> {
 9411        let Some(provider) = self.semantics_provider.clone() else {
 9412            return Task::ready(Ok(Navigated::No));
 9413        };
 9414        let head = self.selections.newest::<usize>(cx).head();
 9415        let buffer = self.buffer.read(cx);
 9416        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9417            text_anchor
 9418        } else {
 9419            return Task::ready(Ok(Navigated::No));
 9420        };
 9421
 9422        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9423            return Task::ready(Ok(Navigated::No));
 9424        };
 9425
 9426        cx.spawn(|editor, mut cx| async move {
 9427            let definitions = definitions.await?;
 9428            let navigated = editor
 9429                .update(&mut cx, |editor, cx| {
 9430                    editor.navigate_to_hover_links(
 9431                        Some(kind),
 9432                        definitions
 9433                            .into_iter()
 9434                            .filter(|location| {
 9435                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9436                            })
 9437                            .map(HoverLink::Text)
 9438                            .collect::<Vec<_>>(),
 9439                        split,
 9440                        cx,
 9441                    )
 9442                })?
 9443                .await?;
 9444            anyhow::Ok(navigated)
 9445        })
 9446    }
 9447
 9448    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9449        let selection = self.selections.newest_anchor();
 9450        let head = selection.head();
 9451        let tail = selection.tail();
 9452
 9453        let Some((buffer, start_position)) =
 9454            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9455        else {
 9456            return;
 9457        };
 9458
 9459        let end_position = if head != tail {
 9460            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9461                return;
 9462            };
 9463            Some(pos)
 9464        } else {
 9465            None
 9466        };
 9467
 9468        let url_finder = cx.spawn(|editor, mut cx| async move {
 9469            let url = if let Some(end_pos) = end_position {
 9470                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9471            } else {
 9472                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9473            };
 9474
 9475            if let Some(url) = url {
 9476                editor.update(&mut cx, |_, cx| {
 9477                    cx.open_url(&url);
 9478                })
 9479            } else {
 9480                Ok(())
 9481            }
 9482        });
 9483
 9484        url_finder.detach();
 9485    }
 9486
 9487    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9488        let Some(workspace) = self.workspace() else {
 9489            return;
 9490        };
 9491
 9492        let position = self.selections.newest_anchor().head();
 9493
 9494        let Some((buffer, buffer_position)) =
 9495            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9496        else {
 9497            return;
 9498        };
 9499
 9500        let project = self.project.clone();
 9501
 9502        cx.spawn(|_, mut cx| async move {
 9503            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9504
 9505            if let Some((_, path)) = result {
 9506                workspace
 9507                    .update(&mut cx, |workspace, cx| {
 9508                        workspace.open_resolved_path(path, cx)
 9509                    })?
 9510                    .await?;
 9511            }
 9512            anyhow::Ok(())
 9513        })
 9514        .detach();
 9515    }
 9516
 9517    pub(crate) fn navigate_to_hover_links(
 9518        &mut self,
 9519        kind: Option<GotoDefinitionKind>,
 9520        mut definitions: Vec<HoverLink>,
 9521        split: bool,
 9522        cx: &mut ViewContext<Editor>,
 9523    ) -> Task<Result<Navigated>> {
 9524        // If there is one definition, just open it directly
 9525        if definitions.len() == 1 {
 9526            let definition = definitions.pop().unwrap();
 9527
 9528            enum TargetTaskResult {
 9529                Location(Option<Location>),
 9530                AlreadyNavigated,
 9531            }
 9532
 9533            let target_task = match definition {
 9534                HoverLink::Text(link) => {
 9535                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9536                }
 9537                HoverLink::InlayHint(lsp_location, server_id) => {
 9538                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9539                    cx.background_executor().spawn(async move {
 9540                        let location = computation.await?;
 9541                        Ok(TargetTaskResult::Location(location))
 9542                    })
 9543                }
 9544                HoverLink::Url(url) => {
 9545                    cx.open_url(&url);
 9546                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9547                }
 9548                HoverLink::File(path) => {
 9549                    if let Some(workspace) = self.workspace() {
 9550                        cx.spawn(|_, mut cx| async move {
 9551                            workspace
 9552                                .update(&mut cx, |workspace, cx| {
 9553                                    workspace.open_resolved_path(path, cx)
 9554                                })?
 9555                                .await
 9556                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9557                        })
 9558                    } else {
 9559                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9560                    }
 9561                }
 9562            };
 9563            cx.spawn(|editor, mut cx| async move {
 9564                let target = match target_task.await.context("target resolution task")? {
 9565                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9566                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9567                    TargetTaskResult::Location(Some(target)) => target,
 9568                };
 9569
 9570                editor.update(&mut cx, |editor, cx| {
 9571                    let Some(workspace) = editor.workspace() else {
 9572                        return Navigated::No;
 9573                    };
 9574                    let pane = workspace.read(cx).active_pane().clone();
 9575
 9576                    let range = target.range.to_offset(target.buffer.read(cx));
 9577                    let range = editor.range_for_match(&range);
 9578
 9579                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9580                        let buffer = target.buffer.read(cx);
 9581                        let range = check_multiline_range(buffer, range);
 9582                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9583                            s.select_ranges([range]);
 9584                        });
 9585                    } else {
 9586                        cx.window_context().defer(move |cx| {
 9587                            let target_editor: View<Self> =
 9588                                workspace.update(cx, |workspace, cx| {
 9589                                    let pane = if split {
 9590                                        workspace.adjacent_pane(cx)
 9591                                    } else {
 9592                                        workspace.active_pane().clone()
 9593                                    };
 9594
 9595                                    workspace.open_project_item(
 9596                                        pane,
 9597                                        target.buffer.clone(),
 9598                                        true,
 9599                                        true,
 9600                                        cx,
 9601                                    )
 9602                                });
 9603                            target_editor.update(cx, |target_editor, cx| {
 9604                                // When selecting a definition in a different buffer, disable the nav history
 9605                                // to avoid creating a history entry at the previous cursor location.
 9606                                pane.update(cx, |pane, _| pane.disable_history());
 9607                                let buffer = target.buffer.read(cx);
 9608                                let range = check_multiline_range(buffer, range);
 9609                                target_editor.change_selections(
 9610                                    Some(Autoscroll::focused()),
 9611                                    cx,
 9612                                    |s| {
 9613                                        s.select_ranges([range]);
 9614                                    },
 9615                                );
 9616                                pane.update(cx, |pane, _| pane.enable_history());
 9617                            });
 9618                        });
 9619                    }
 9620                    Navigated::Yes
 9621                })
 9622            })
 9623        } else if !definitions.is_empty() {
 9624            cx.spawn(|editor, mut cx| async move {
 9625                let (title, location_tasks, workspace) = editor
 9626                    .update(&mut cx, |editor, cx| {
 9627                        let tab_kind = match kind {
 9628                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9629                            _ => "Definitions",
 9630                        };
 9631                        let title = definitions
 9632                            .iter()
 9633                            .find_map(|definition| match definition {
 9634                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9635                                    let buffer = origin.buffer.read(cx);
 9636                                    format!(
 9637                                        "{} for {}",
 9638                                        tab_kind,
 9639                                        buffer
 9640                                            .text_for_range(origin.range.clone())
 9641                                            .collect::<String>()
 9642                                    )
 9643                                }),
 9644                                HoverLink::InlayHint(_, _) => None,
 9645                                HoverLink::Url(_) => None,
 9646                                HoverLink::File(_) => None,
 9647                            })
 9648                            .unwrap_or(tab_kind.to_string());
 9649                        let location_tasks = definitions
 9650                            .into_iter()
 9651                            .map(|definition| match definition {
 9652                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9653                                HoverLink::InlayHint(lsp_location, server_id) => {
 9654                                    editor.compute_target_location(lsp_location, server_id, cx)
 9655                                }
 9656                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9657                                HoverLink::File(_) => Task::ready(Ok(None)),
 9658                            })
 9659                            .collect::<Vec<_>>();
 9660                        (title, location_tasks, editor.workspace().clone())
 9661                    })
 9662                    .context("location tasks preparation")?;
 9663
 9664                let locations = future::join_all(location_tasks)
 9665                    .await
 9666                    .into_iter()
 9667                    .filter_map(|location| location.transpose())
 9668                    .collect::<Result<_>>()
 9669                    .context("location tasks")?;
 9670
 9671                let Some(workspace) = workspace else {
 9672                    return Ok(Navigated::No);
 9673                };
 9674                let opened = workspace
 9675                    .update(&mut cx, |workspace, cx| {
 9676                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9677                    })
 9678                    .ok();
 9679
 9680                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9681            })
 9682        } else {
 9683            Task::ready(Ok(Navigated::No))
 9684        }
 9685    }
 9686
 9687    fn compute_target_location(
 9688        &self,
 9689        lsp_location: lsp::Location,
 9690        server_id: LanguageServerId,
 9691        cx: &mut ViewContext<Self>,
 9692    ) -> Task<anyhow::Result<Option<Location>>> {
 9693        let Some(project) = self.project.clone() else {
 9694            return Task::ready(Ok(None));
 9695        };
 9696
 9697        cx.spawn(move |editor, mut cx| async move {
 9698            let location_task = editor.update(&mut cx, |_, cx| {
 9699                project.update(cx, |project, cx| {
 9700                    let language_server_name = project
 9701                        .language_server_statuses(cx)
 9702                        .find(|(id, _)| server_id == *id)
 9703                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9704                    language_server_name.map(|language_server_name| {
 9705                        project.open_local_buffer_via_lsp(
 9706                            lsp_location.uri.clone(),
 9707                            server_id,
 9708                            language_server_name,
 9709                            cx,
 9710                        )
 9711                    })
 9712                })
 9713            })?;
 9714            let location = match location_task {
 9715                Some(task) => Some({
 9716                    let target_buffer_handle = task.await.context("open local buffer")?;
 9717                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9718                        let target_start = target_buffer
 9719                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9720                        let target_end = target_buffer
 9721                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9722                        target_buffer.anchor_after(target_start)
 9723                            ..target_buffer.anchor_before(target_end)
 9724                    })?;
 9725                    Location {
 9726                        buffer: target_buffer_handle,
 9727                        range,
 9728                    }
 9729                }),
 9730                None => None,
 9731            };
 9732            Ok(location)
 9733        })
 9734    }
 9735
 9736    pub fn find_all_references(
 9737        &mut self,
 9738        _: &FindAllReferences,
 9739        cx: &mut ViewContext<Self>,
 9740    ) -> Option<Task<Result<Navigated>>> {
 9741        let selection = self.selections.newest::<usize>(cx);
 9742        let multi_buffer = self.buffer.read(cx);
 9743        let head = selection.head();
 9744
 9745        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9746        let head_anchor = multi_buffer_snapshot.anchor_at(
 9747            head,
 9748            if head < selection.tail() {
 9749                Bias::Right
 9750            } else {
 9751                Bias::Left
 9752            },
 9753        );
 9754
 9755        match self
 9756            .find_all_references_task_sources
 9757            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9758        {
 9759            Ok(_) => {
 9760                log::info!(
 9761                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9762                );
 9763                return None;
 9764            }
 9765            Err(i) => {
 9766                self.find_all_references_task_sources.insert(i, head_anchor);
 9767            }
 9768        }
 9769
 9770        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9771        let workspace = self.workspace()?;
 9772        let project = workspace.read(cx).project().clone();
 9773        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9774        Some(cx.spawn(|editor, mut cx| async move {
 9775            let _cleanup = defer({
 9776                let mut cx = cx.clone();
 9777                move || {
 9778                    let _ = editor.update(&mut cx, |editor, _| {
 9779                        if let Ok(i) =
 9780                            editor
 9781                                .find_all_references_task_sources
 9782                                .binary_search_by(|anchor| {
 9783                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9784                                })
 9785                        {
 9786                            editor.find_all_references_task_sources.remove(i);
 9787                        }
 9788                    });
 9789                }
 9790            });
 9791
 9792            let locations = references.await?;
 9793            if locations.is_empty() {
 9794                return anyhow::Ok(Navigated::No);
 9795            }
 9796
 9797            workspace.update(&mut cx, |workspace, cx| {
 9798                let title = locations
 9799                    .first()
 9800                    .as_ref()
 9801                    .map(|location| {
 9802                        let buffer = location.buffer.read(cx);
 9803                        format!(
 9804                            "References to `{}`",
 9805                            buffer
 9806                                .text_for_range(location.range.clone())
 9807                                .collect::<String>()
 9808                        )
 9809                    })
 9810                    .unwrap();
 9811                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9812                Navigated::Yes
 9813            })
 9814        }))
 9815    }
 9816
 9817    /// Opens a multibuffer with the given project locations in it
 9818    pub fn open_locations_in_multibuffer(
 9819        workspace: &mut Workspace,
 9820        mut locations: Vec<Location>,
 9821        title: String,
 9822        split: bool,
 9823        cx: &mut ViewContext<Workspace>,
 9824    ) {
 9825        // If there are multiple definitions, open them in a multibuffer
 9826        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9827        let mut locations = locations.into_iter().peekable();
 9828        let mut ranges_to_highlight = Vec::new();
 9829        let capability = workspace.project().read(cx).capability();
 9830
 9831        let excerpt_buffer = cx.new_model(|cx| {
 9832            let mut multibuffer = MultiBuffer::new(capability);
 9833            while let Some(location) = locations.next() {
 9834                let buffer = location.buffer.read(cx);
 9835                let mut ranges_for_buffer = Vec::new();
 9836                let range = location.range.to_offset(buffer);
 9837                ranges_for_buffer.push(range.clone());
 9838
 9839                while let Some(next_location) = locations.peek() {
 9840                    if next_location.buffer == location.buffer {
 9841                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9842                        locations.next();
 9843                    } else {
 9844                        break;
 9845                    }
 9846                }
 9847
 9848                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9849                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9850                    location.buffer.clone(),
 9851                    ranges_for_buffer,
 9852                    DEFAULT_MULTIBUFFER_CONTEXT,
 9853                    cx,
 9854                ))
 9855            }
 9856
 9857            multibuffer.with_title(title)
 9858        });
 9859
 9860        let editor = cx.new_view(|cx| {
 9861            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9862        });
 9863        editor.update(cx, |editor, cx| {
 9864            if let Some(first_range) = ranges_to_highlight.first() {
 9865                editor.change_selections(None, cx, |selections| {
 9866                    selections.clear_disjoint();
 9867                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9868                });
 9869            }
 9870            editor.highlight_background::<Self>(
 9871                &ranges_to_highlight,
 9872                |theme| theme.editor_highlighted_line_background,
 9873                cx,
 9874            );
 9875            editor.register_buffers_with_language_servers(cx);
 9876        });
 9877
 9878        let item = Box::new(editor);
 9879        let item_id = item.item_id();
 9880
 9881        if split {
 9882            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9883        } else {
 9884            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9885                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9886                    pane.close_current_preview_item(cx)
 9887                } else {
 9888                    None
 9889                }
 9890            });
 9891            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9892        }
 9893        workspace.active_pane().update(cx, |pane, cx| {
 9894            pane.set_preview_item_id(Some(item_id), cx);
 9895        });
 9896    }
 9897
 9898    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9899        use language::ToOffset as _;
 9900
 9901        let provider = self.semantics_provider.clone()?;
 9902        let selection = self.selections.newest_anchor().clone();
 9903        let (cursor_buffer, cursor_buffer_position) = self
 9904            .buffer
 9905            .read(cx)
 9906            .text_anchor_for_position(selection.head(), cx)?;
 9907        let (tail_buffer, cursor_buffer_position_end) = self
 9908            .buffer
 9909            .read(cx)
 9910            .text_anchor_for_position(selection.tail(), cx)?;
 9911        if tail_buffer != cursor_buffer {
 9912            return None;
 9913        }
 9914
 9915        let snapshot = cursor_buffer.read(cx).snapshot();
 9916        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9917        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9918        let prepare_rename = provider
 9919            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9920            .unwrap_or_else(|| Task::ready(Ok(None)));
 9921        drop(snapshot);
 9922
 9923        Some(cx.spawn(|this, mut cx| async move {
 9924            let rename_range = if let Some(range) = prepare_rename.await? {
 9925                Some(range)
 9926            } else {
 9927                this.update(&mut cx, |this, cx| {
 9928                    let buffer = this.buffer.read(cx).snapshot(cx);
 9929                    let mut buffer_highlights = this
 9930                        .document_highlights_for_position(selection.head(), &buffer)
 9931                        .filter(|highlight| {
 9932                            highlight.start.excerpt_id == selection.head().excerpt_id
 9933                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9934                        });
 9935                    buffer_highlights
 9936                        .next()
 9937                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9938                })?
 9939            };
 9940            if let Some(rename_range) = rename_range {
 9941                this.update(&mut cx, |this, cx| {
 9942                    let snapshot = cursor_buffer.read(cx).snapshot();
 9943                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9944                    let cursor_offset_in_rename_range =
 9945                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9946                    let cursor_offset_in_rename_range_end =
 9947                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9948
 9949                    this.take_rename(false, cx);
 9950                    let buffer = this.buffer.read(cx).read(cx);
 9951                    let cursor_offset = selection.head().to_offset(&buffer);
 9952                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9953                    let rename_end = rename_start + rename_buffer_range.len();
 9954                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9955                    let mut old_highlight_id = None;
 9956                    let old_name: Arc<str> = buffer
 9957                        .chunks(rename_start..rename_end, true)
 9958                        .map(|chunk| {
 9959                            if old_highlight_id.is_none() {
 9960                                old_highlight_id = chunk.syntax_highlight_id;
 9961                            }
 9962                            chunk.text
 9963                        })
 9964                        .collect::<String>()
 9965                        .into();
 9966
 9967                    drop(buffer);
 9968
 9969                    // Position the selection in the rename editor so that it matches the current selection.
 9970                    this.show_local_selections = false;
 9971                    let rename_editor = cx.new_view(|cx| {
 9972                        let mut editor = Editor::single_line(cx);
 9973                        editor.buffer.update(cx, |buffer, cx| {
 9974                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9975                        });
 9976                        let rename_selection_range = match cursor_offset_in_rename_range
 9977                            .cmp(&cursor_offset_in_rename_range_end)
 9978                        {
 9979                            Ordering::Equal => {
 9980                                editor.select_all(&SelectAll, cx);
 9981                                return editor;
 9982                            }
 9983                            Ordering::Less => {
 9984                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9985                            }
 9986                            Ordering::Greater => {
 9987                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9988                            }
 9989                        };
 9990                        if rename_selection_range.end > old_name.len() {
 9991                            editor.select_all(&SelectAll, cx);
 9992                        } else {
 9993                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9994                                s.select_ranges([rename_selection_range]);
 9995                            });
 9996                        }
 9997                        editor
 9998                    });
 9999                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10000                        if e == &EditorEvent::Focused {
10001                            cx.emit(EditorEvent::FocusedIn)
10002                        }
10003                    })
10004                    .detach();
10005
10006                    let write_highlights =
10007                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10008                    let read_highlights =
10009                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10010                    let ranges = write_highlights
10011                        .iter()
10012                        .flat_map(|(_, ranges)| ranges.iter())
10013                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10014                        .cloned()
10015                        .collect();
10016
10017                    this.highlight_text::<Rename>(
10018                        ranges,
10019                        HighlightStyle {
10020                            fade_out: Some(0.6),
10021                            ..Default::default()
10022                        },
10023                        cx,
10024                    );
10025                    let rename_focus_handle = rename_editor.focus_handle(cx);
10026                    cx.focus(&rename_focus_handle);
10027                    let block_id = this.insert_blocks(
10028                        [BlockProperties {
10029                            style: BlockStyle::Flex,
10030                            placement: BlockPlacement::Below(range.start),
10031                            height: 1,
10032                            render: Arc::new({
10033                                let rename_editor = rename_editor.clone();
10034                                move |cx: &mut BlockContext| {
10035                                    let mut text_style = cx.editor_style.text.clone();
10036                                    if let Some(highlight_style) = old_highlight_id
10037                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10038                                    {
10039                                        text_style = text_style.highlight(highlight_style);
10040                                    }
10041                                    div()
10042                                        .block_mouse_down()
10043                                        .pl(cx.anchor_x)
10044                                        .child(EditorElement::new(
10045                                            &rename_editor,
10046                                            EditorStyle {
10047                                                background: cx.theme().system().transparent,
10048                                                local_player: cx.editor_style.local_player,
10049                                                text: text_style,
10050                                                scrollbar_width: cx.editor_style.scrollbar_width,
10051                                                syntax: cx.editor_style.syntax.clone(),
10052                                                status: cx.editor_style.status.clone(),
10053                                                inlay_hints_style: HighlightStyle {
10054                                                    font_weight: Some(FontWeight::BOLD),
10055                                                    ..make_inlay_hints_style(cx)
10056                                                },
10057                                                inline_completion_styles: make_suggestion_styles(
10058                                                    cx,
10059                                                ),
10060                                                ..EditorStyle::default()
10061                                            },
10062                                        ))
10063                                        .into_any_element()
10064                                }
10065                            }),
10066                            priority: 0,
10067                        }],
10068                        Some(Autoscroll::fit()),
10069                        cx,
10070                    )[0];
10071                    this.pending_rename = Some(RenameState {
10072                        range,
10073                        old_name,
10074                        editor: rename_editor,
10075                        block_id,
10076                    });
10077                })?;
10078            }
10079
10080            Ok(())
10081        }))
10082    }
10083
10084    pub fn confirm_rename(
10085        &mut self,
10086        _: &ConfirmRename,
10087        cx: &mut ViewContext<Self>,
10088    ) -> Option<Task<Result<()>>> {
10089        let rename = self.take_rename(false, cx)?;
10090        let workspace = self.workspace()?.downgrade();
10091        let (buffer, start) = self
10092            .buffer
10093            .read(cx)
10094            .text_anchor_for_position(rename.range.start, cx)?;
10095        let (end_buffer, _) = self
10096            .buffer
10097            .read(cx)
10098            .text_anchor_for_position(rename.range.end, cx)?;
10099        if buffer != end_buffer {
10100            return None;
10101        }
10102
10103        let old_name = rename.old_name;
10104        let new_name = rename.editor.read(cx).text(cx);
10105
10106        let rename = self.semantics_provider.as_ref()?.perform_rename(
10107            &buffer,
10108            start,
10109            new_name.clone(),
10110            cx,
10111        )?;
10112
10113        Some(cx.spawn(|editor, mut cx| async move {
10114            let project_transaction = rename.await?;
10115            Self::open_project_transaction(
10116                &editor,
10117                workspace,
10118                project_transaction,
10119                format!("Rename: {}{}", old_name, new_name),
10120                cx.clone(),
10121            )
10122            .await?;
10123
10124            editor.update(&mut cx, |editor, cx| {
10125                editor.refresh_document_highlights(cx);
10126            })?;
10127            Ok(())
10128        }))
10129    }
10130
10131    fn take_rename(
10132        &mut self,
10133        moving_cursor: bool,
10134        cx: &mut ViewContext<Self>,
10135    ) -> Option<RenameState> {
10136        let rename = self.pending_rename.take()?;
10137        if rename.editor.focus_handle(cx).is_focused(cx) {
10138            cx.focus(&self.focus_handle);
10139        }
10140
10141        self.remove_blocks(
10142            [rename.block_id].into_iter().collect(),
10143            Some(Autoscroll::fit()),
10144            cx,
10145        );
10146        self.clear_highlights::<Rename>(cx);
10147        self.show_local_selections = true;
10148
10149        if moving_cursor {
10150            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10151                editor.selections.newest::<usize>(cx).head()
10152            });
10153
10154            // Update the selection to match the position of the selection inside
10155            // the rename editor.
10156            let snapshot = self.buffer.read(cx).read(cx);
10157            let rename_range = rename.range.to_offset(&snapshot);
10158            let cursor_in_editor = snapshot
10159                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10160                .min(rename_range.end);
10161            drop(snapshot);
10162
10163            self.change_selections(None, cx, |s| {
10164                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10165            });
10166        } else {
10167            self.refresh_document_highlights(cx);
10168        }
10169
10170        Some(rename)
10171    }
10172
10173    pub fn pending_rename(&self) -> Option<&RenameState> {
10174        self.pending_rename.as_ref()
10175    }
10176
10177    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10178        let project = match &self.project {
10179            Some(project) => project.clone(),
10180            None => return None,
10181        };
10182
10183        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10184    }
10185
10186    fn format_selections(
10187        &mut self,
10188        _: &FormatSelections,
10189        cx: &mut ViewContext<Self>,
10190    ) -> Option<Task<Result<()>>> {
10191        let project = match &self.project {
10192            Some(project) => project.clone(),
10193            None => return None,
10194        };
10195
10196        let selections = self
10197            .selections
10198            .all_adjusted(cx)
10199            .into_iter()
10200            .filter(|s| !s.is_empty())
10201            .collect_vec();
10202
10203        Some(self.perform_format(
10204            project,
10205            FormatTrigger::Manual,
10206            FormatTarget::Ranges(selections),
10207            cx,
10208        ))
10209    }
10210
10211    fn perform_format(
10212        &mut self,
10213        project: Model<Project>,
10214        trigger: FormatTrigger,
10215        target: FormatTarget,
10216        cx: &mut ViewContext<Self>,
10217    ) -> Task<Result<()>> {
10218        let buffer = self.buffer().clone();
10219        let mut buffers = buffer.read(cx).all_buffers();
10220        if trigger == FormatTrigger::Save {
10221            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10222        }
10223
10224        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10225        let format = project.update(cx, |project, cx| {
10226            project.format(buffers, true, trigger, target, cx)
10227        });
10228
10229        cx.spawn(|_, mut cx| async move {
10230            let transaction = futures::select_biased! {
10231                () = timeout => {
10232                    log::warn!("timed out waiting for formatting");
10233                    None
10234                }
10235                transaction = format.log_err().fuse() => transaction,
10236            };
10237
10238            buffer
10239                .update(&mut cx, |buffer, cx| {
10240                    if let Some(transaction) = transaction {
10241                        if !buffer.is_singleton() {
10242                            buffer.push_transaction(&transaction.0, cx);
10243                        }
10244                    }
10245
10246                    cx.notify();
10247                })
10248                .ok();
10249
10250            Ok(())
10251        })
10252    }
10253
10254    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10255        if let Some(project) = self.project.clone() {
10256            self.buffer.update(cx, |multi_buffer, cx| {
10257                project.update(cx, |project, cx| {
10258                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10259                });
10260            })
10261        }
10262    }
10263
10264    fn cancel_language_server_work(
10265        &mut self,
10266        _: &actions::CancelLanguageServerWork,
10267        cx: &mut ViewContext<Self>,
10268    ) {
10269        if let Some(project) = self.project.clone() {
10270            self.buffer.update(cx, |multi_buffer, cx| {
10271                project.update(cx, |project, cx| {
10272                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10273                });
10274            })
10275        }
10276    }
10277
10278    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10279        cx.show_character_palette();
10280    }
10281
10282    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10283        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10284            let buffer = self.buffer.read(cx).snapshot(cx);
10285            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10286            let is_valid = buffer
10287                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10288                .any(|entry| {
10289                    entry.diagnostic.is_primary
10290                        && !entry.range.is_empty()
10291                        && entry.range.start == primary_range_start
10292                        && entry.diagnostic.message == active_diagnostics.primary_message
10293                });
10294
10295            if is_valid != active_diagnostics.is_valid {
10296                active_diagnostics.is_valid = is_valid;
10297                let mut new_styles = HashMap::default();
10298                for (block_id, diagnostic) in &active_diagnostics.blocks {
10299                    new_styles.insert(
10300                        *block_id,
10301                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10302                    );
10303                }
10304                self.display_map.update(cx, |display_map, _cx| {
10305                    display_map.replace_blocks(new_styles)
10306                });
10307            }
10308        }
10309    }
10310
10311    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10312        self.dismiss_diagnostics(cx);
10313        let snapshot = self.snapshot(cx);
10314        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10315            let buffer = self.buffer.read(cx).snapshot(cx);
10316
10317            let mut primary_range = None;
10318            let mut primary_message = None;
10319            let mut group_end = Point::zero();
10320            let diagnostic_group = buffer
10321                .diagnostic_group::<MultiBufferPoint>(group_id)
10322                .filter_map(|entry| {
10323                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10324                        && (entry.range.start.row == entry.range.end.row
10325                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10326                    {
10327                        return None;
10328                    }
10329                    if entry.range.end > group_end {
10330                        group_end = entry.range.end;
10331                    }
10332                    if entry.diagnostic.is_primary {
10333                        primary_range = Some(entry.range.clone());
10334                        primary_message = Some(entry.diagnostic.message.clone());
10335                    }
10336                    Some(entry)
10337                })
10338                .collect::<Vec<_>>();
10339            let primary_range = primary_range?;
10340            let primary_message = primary_message?;
10341            let primary_range =
10342                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10343
10344            let blocks = display_map
10345                .insert_blocks(
10346                    diagnostic_group.iter().map(|entry| {
10347                        let diagnostic = entry.diagnostic.clone();
10348                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10349                        BlockProperties {
10350                            style: BlockStyle::Fixed,
10351                            placement: BlockPlacement::Below(
10352                                buffer.anchor_after(entry.range.start),
10353                            ),
10354                            height: message_height,
10355                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10356                            priority: 0,
10357                        }
10358                    }),
10359                    cx,
10360                )
10361                .into_iter()
10362                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10363                .collect();
10364
10365            Some(ActiveDiagnosticGroup {
10366                primary_range,
10367                primary_message,
10368                group_id,
10369                blocks,
10370                is_valid: true,
10371            })
10372        });
10373        self.active_diagnostics.is_some()
10374    }
10375
10376    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10377        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10378            self.display_map.update(cx, |display_map, cx| {
10379                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10380            });
10381            cx.notify();
10382        }
10383    }
10384
10385    pub fn set_selections_from_remote(
10386        &mut self,
10387        selections: Vec<Selection<Anchor>>,
10388        pending_selection: Option<Selection<Anchor>>,
10389        cx: &mut ViewContext<Self>,
10390    ) {
10391        let old_cursor_position = self.selections.newest_anchor().head();
10392        self.selections.change_with(cx, |s| {
10393            s.select_anchors(selections);
10394            if let Some(pending_selection) = pending_selection {
10395                s.set_pending(pending_selection, SelectMode::Character);
10396            } else {
10397                s.clear_pending();
10398            }
10399        });
10400        self.selections_did_change(false, &old_cursor_position, true, cx);
10401    }
10402
10403    fn push_to_selection_history(&mut self) {
10404        self.selection_history.push(SelectionHistoryEntry {
10405            selections: self.selections.disjoint_anchors(),
10406            select_next_state: self.select_next_state.clone(),
10407            select_prev_state: self.select_prev_state.clone(),
10408            add_selections_state: self.add_selections_state.clone(),
10409        });
10410    }
10411
10412    pub fn transact(
10413        &mut self,
10414        cx: &mut ViewContext<Self>,
10415        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10416    ) -> Option<TransactionId> {
10417        self.start_transaction_at(Instant::now(), cx);
10418        update(self, cx);
10419        self.end_transaction_at(Instant::now(), cx)
10420    }
10421
10422    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10423        self.end_selection(cx);
10424        if let Some(tx_id) = self
10425            .buffer
10426            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10427        {
10428            self.selection_history
10429                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10430            cx.emit(EditorEvent::TransactionBegun {
10431                transaction_id: tx_id,
10432            })
10433        }
10434    }
10435
10436    pub fn end_transaction_at(
10437        &mut self,
10438        now: Instant,
10439        cx: &mut ViewContext<Self>,
10440    ) -> Option<TransactionId> {
10441        if let Some(transaction_id) = self
10442            .buffer
10443            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10444        {
10445            if let Some((_, end_selections)) =
10446                self.selection_history.transaction_mut(transaction_id)
10447            {
10448                *end_selections = Some(self.selections.disjoint_anchors());
10449            } else {
10450                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10451            }
10452
10453            cx.emit(EditorEvent::Edited { transaction_id });
10454            Some(transaction_id)
10455        } else {
10456            None
10457        }
10458    }
10459
10460    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10461        if self.is_singleton(cx) {
10462            let selection = self.selections.newest::<Point>(cx);
10463
10464            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10465            let range = if selection.is_empty() {
10466                let point = selection.head().to_display_point(&display_map);
10467                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10468                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10469                    .to_point(&display_map);
10470                start..end
10471            } else {
10472                selection.range()
10473            };
10474            if display_map.folds_in_range(range).next().is_some() {
10475                self.unfold_lines(&Default::default(), cx)
10476            } else {
10477                self.fold(&Default::default(), cx)
10478            }
10479        } else {
10480            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10481            let mut toggled_buffers = HashSet::default();
10482            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10483                self.selections
10484                    .disjoint_anchors()
10485                    .into_iter()
10486                    .map(|selection| selection.range()),
10487            ) {
10488                let buffer_id = buffer_snapshot.remote_id();
10489                if toggled_buffers.insert(buffer_id) {
10490                    if self.buffer_folded(buffer_id, cx) {
10491                        self.unfold_buffer(buffer_id, cx);
10492                    } else {
10493                        self.fold_buffer(buffer_id, cx);
10494                    }
10495                }
10496            }
10497        }
10498    }
10499
10500    pub fn toggle_fold_recursive(
10501        &mut self,
10502        _: &actions::ToggleFoldRecursive,
10503        cx: &mut ViewContext<Self>,
10504    ) {
10505        let selection = self.selections.newest::<Point>(cx);
10506
10507        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10508        let range = if selection.is_empty() {
10509            let point = selection.head().to_display_point(&display_map);
10510            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10511            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10512                .to_point(&display_map);
10513            start..end
10514        } else {
10515            selection.range()
10516        };
10517        if display_map.folds_in_range(range).next().is_some() {
10518            self.unfold_recursive(&Default::default(), cx)
10519        } else {
10520            self.fold_recursive(&Default::default(), cx)
10521        }
10522    }
10523
10524    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10525        if self.is_singleton(cx) {
10526            let mut to_fold = Vec::new();
10527            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10528            let selections = self.selections.all_adjusted(cx);
10529
10530            for selection in selections {
10531                let range = selection.range().sorted();
10532                let buffer_start_row = range.start.row;
10533
10534                if range.start.row != range.end.row {
10535                    let mut found = false;
10536                    let mut row = range.start.row;
10537                    while row <= range.end.row {
10538                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10539                        {
10540                            found = true;
10541                            row = crease.range().end.row + 1;
10542                            to_fold.push(crease);
10543                        } else {
10544                            row += 1
10545                        }
10546                    }
10547                    if found {
10548                        continue;
10549                    }
10550                }
10551
10552                for row in (0..=range.start.row).rev() {
10553                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10554                        if crease.range().end.row >= buffer_start_row {
10555                            to_fold.push(crease);
10556                            if row <= range.start.row {
10557                                break;
10558                            }
10559                        }
10560                    }
10561                }
10562            }
10563
10564            self.fold_creases(to_fold, true, cx);
10565        } else {
10566            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10567            let mut folded_buffers = HashSet::default();
10568            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10569                self.selections
10570                    .disjoint_anchors()
10571                    .into_iter()
10572                    .map(|selection| selection.range()),
10573            ) {
10574                let buffer_id = buffer_snapshot.remote_id();
10575                if folded_buffers.insert(buffer_id) {
10576                    self.fold_buffer(buffer_id, cx);
10577                }
10578            }
10579        }
10580    }
10581
10582    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10583        if !self.buffer.read(cx).is_singleton() {
10584            return;
10585        }
10586
10587        let fold_at_level = fold_at.level;
10588        let snapshot = self.buffer.read(cx).snapshot(cx);
10589        let mut to_fold = Vec::new();
10590        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10591
10592        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10593            while start_row < end_row {
10594                match self
10595                    .snapshot(cx)
10596                    .crease_for_buffer_row(MultiBufferRow(start_row))
10597                {
10598                    Some(crease) => {
10599                        let nested_start_row = crease.range().start.row + 1;
10600                        let nested_end_row = crease.range().end.row;
10601
10602                        if current_level < fold_at_level {
10603                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10604                        } else if current_level == fold_at_level {
10605                            to_fold.push(crease);
10606                        }
10607
10608                        start_row = nested_end_row + 1;
10609                    }
10610                    None => start_row += 1,
10611                }
10612            }
10613        }
10614
10615        self.fold_creases(to_fold, true, cx);
10616    }
10617
10618    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10619        if self.buffer.read(cx).is_singleton() {
10620            let mut fold_ranges = Vec::new();
10621            let snapshot = self.buffer.read(cx).snapshot(cx);
10622
10623            for row in 0..snapshot.max_row().0 {
10624                if let Some(foldable_range) =
10625                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10626                {
10627                    fold_ranges.push(foldable_range);
10628                }
10629            }
10630
10631            self.fold_creases(fold_ranges, true, cx);
10632        } else {
10633            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10634                editor
10635                    .update(&mut cx, |editor, cx| {
10636                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10637                            editor.fold_buffer(buffer_id, cx);
10638                        }
10639                    })
10640                    .ok();
10641            });
10642        }
10643    }
10644
10645    pub fn fold_function_bodies(
10646        &mut self,
10647        _: &actions::FoldFunctionBodies,
10648        cx: &mut ViewContext<Self>,
10649    ) {
10650        let snapshot = self.buffer.read(cx).snapshot(cx);
10651        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10652            return;
10653        };
10654        let creases = buffer
10655            .function_body_fold_ranges(0..buffer.len())
10656            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10657            .collect();
10658
10659        self.fold_creases(creases, true, cx);
10660    }
10661
10662    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10663        let mut to_fold = Vec::new();
10664        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10665        let selections = self.selections.all_adjusted(cx);
10666
10667        for selection in selections {
10668            let range = selection.range().sorted();
10669            let buffer_start_row = range.start.row;
10670
10671            if range.start.row != range.end.row {
10672                let mut found = false;
10673                for row in range.start.row..=range.end.row {
10674                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10675                        found = true;
10676                        to_fold.push(crease);
10677                    }
10678                }
10679                if found {
10680                    continue;
10681                }
10682            }
10683
10684            for row in (0..=range.start.row).rev() {
10685                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10686                    if crease.range().end.row >= buffer_start_row {
10687                        to_fold.push(crease);
10688                    } else {
10689                        break;
10690                    }
10691                }
10692            }
10693        }
10694
10695        self.fold_creases(to_fold, true, cx);
10696    }
10697
10698    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10699        let buffer_row = fold_at.buffer_row;
10700        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10701
10702        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10703            let autoscroll = self
10704                .selections
10705                .all::<Point>(cx)
10706                .iter()
10707                .any(|selection| crease.range().overlaps(&selection.range()));
10708
10709            self.fold_creases(vec![crease], autoscroll, cx);
10710        }
10711    }
10712
10713    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10714        if self.is_singleton(cx) {
10715            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10716            let buffer = &display_map.buffer_snapshot;
10717            let selections = self.selections.all::<Point>(cx);
10718            let ranges = selections
10719                .iter()
10720                .map(|s| {
10721                    let range = s.display_range(&display_map).sorted();
10722                    let mut start = range.start.to_point(&display_map);
10723                    let mut end = range.end.to_point(&display_map);
10724                    start.column = 0;
10725                    end.column = buffer.line_len(MultiBufferRow(end.row));
10726                    start..end
10727                })
10728                .collect::<Vec<_>>();
10729
10730            self.unfold_ranges(&ranges, true, true, cx);
10731        } else {
10732            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10733            let mut unfolded_buffers = HashSet::default();
10734            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10735                self.selections
10736                    .disjoint_anchors()
10737                    .into_iter()
10738                    .map(|selection| selection.range()),
10739            ) {
10740                let buffer_id = buffer_snapshot.remote_id();
10741                if unfolded_buffers.insert(buffer_id) {
10742                    self.unfold_buffer(buffer_id, cx);
10743                }
10744            }
10745        }
10746    }
10747
10748    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10749        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10750        let selections = self.selections.all::<Point>(cx);
10751        let ranges = selections
10752            .iter()
10753            .map(|s| {
10754                let mut range = s.display_range(&display_map).sorted();
10755                *range.start.column_mut() = 0;
10756                *range.end.column_mut() = display_map.line_len(range.end.row());
10757                let start = range.start.to_point(&display_map);
10758                let end = range.end.to_point(&display_map);
10759                start..end
10760            })
10761            .collect::<Vec<_>>();
10762
10763        self.unfold_ranges(&ranges, true, true, cx);
10764    }
10765
10766    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10767        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10768
10769        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10770            ..Point::new(
10771                unfold_at.buffer_row.0,
10772                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10773            );
10774
10775        let autoscroll = self
10776            .selections
10777            .all::<Point>(cx)
10778            .iter()
10779            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10780
10781        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10782    }
10783
10784    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10785        if self.buffer.read(cx).is_singleton() {
10786            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10787            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10788        } else {
10789            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10790                editor
10791                    .update(&mut cx, |editor, cx| {
10792                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10793                            editor.unfold_buffer(buffer_id, cx);
10794                        }
10795                    })
10796                    .ok();
10797            });
10798        }
10799    }
10800
10801    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10802        let selections = self.selections.all::<Point>(cx);
10803        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10804        let line_mode = self.selections.line_mode;
10805        let ranges = selections
10806            .into_iter()
10807            .map(|s| {
10808                if line_mode {
10809                    let start = Point::new(s.start.row, 0);
10810                    let end = Point::new(
10811                        s.end.row,
10812                        display_map
10813                            .buffer_snapshot
10814                            .line_len(MultiBufferRow(s.end.row)),
10815                    );
10816                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10817                } else {
10818                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10819                }
10820            })
10821            .collect::<Vec<_>>();
10822        self.fold_creases(ranges, true, cx);
10823    }
10824
10825    pub fn fold_creases<T: ToOffset + Clone>(
10826        &mut self,
10827        creases: Vec<Crease<T>>,
10828        auto_scroll: bool,
10829        cx: &mut ViewContext<Self>,
10830    ) {
10831        if creases.is_empty() {
10832            return;
10833        }
10834
10835        let mut buffers_affected = HashSet::default();
10836        let multi_buffer = self.buffer().read(cx);
10837        for crease in &creases {
10838            if let Some((_, buffer, _)) =
10839                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10840            {
10841                buffers_affected.insert(buffer.read(cx).remote_id());
10842            };
10843        }
10844
10845        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10846
10847        if auto_scroll {
10848            self.request_autoscroll(Autoscroll::fit(), cx);
10849        }
10850
10851        for buffer_id in buffers_affected {
10852            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10853        }
10854
10855        cx.notify();
10856
10857        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10858            // Clear diagnostics block when folding a range that contains it.
10859            let snapshot = self.snapshot(cx);
10860            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10861                drop(snapshot);
10862                self.active_diagnostics = Some(active_diagnostics);
10863                self.dismiss_diagnostics(cx);
10864            } else {
10865                self.active_diagnostics = Some(active_diagnostics);
10866            }
10867        }
10868
10869        self.scrollbar_marker_state.dirty = true;
10870    }
10871
10872    /// Removes any folds whose ranges intersect any of the given ranges.
10873    pub fn unfold_ranges<T: ToOffset + Clone>(
10874        &mut self,
10875        ranges: &[Range<T>],
10876        inclusive: bool,
10877        auto_scroll: bool,
10878        cx: &mut ViewContext<Self>,
10879    ) {
10880        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10881            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10882        });
10883    }
10884
10885    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10886        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10887            return;
10888        }
10889        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10890            return;
10891        };
10892        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10893        self.display_map
10894            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10895        cx.emit(EditorEvent::BufferFoldToggled {
10896            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10897            folded: true,
10898        });
10899        cx.notify();
10900    }
10901
10902    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10903        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10904            return;
10905        }
10906        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10907            return;
10908        };
10909        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10910        self.display_map.update(cx, |display_map, cx| {
10911            display_map.unfold_buffer(buffer_id, cx);
10912        });
10913        cx.emit(EditorEvent::BufferFoldToggled {
10914            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10915            folded: false,
10916        });
10917        cx.notify();
10918    }
10919
10920    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10921        self.display_map.read(cx).buffer_folded(buffer)
10922    }
10923
10924    /// Removes any folds with the given ranges.
10925    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10926        &mut self,
10927        ranges: &[Range<T>],
10928        type_id: TypeId,
10929        auto_scroll: bool,
10930        cx: &mut ViewContext<Self>,
10931    ) {
10932        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10933            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10934        });
10935    }
10936
10937    fn remove_folds_with<T: ToOffset + Clone>(
10938        &mut self,
10939        ranges: &[Range<T>],
10940        auto_scroll: bool,
10941        cx: &mut ViewContext<Self>,
10942        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10943    ) {
10944        if ranges.is_empty() {
10945            return;
10946        }
10947
10948        let mut buffers_affected = HashSet::default();
10949        let multi_buffer = self.buffer().read(cx);
10950        for range in ranges {
10951            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10952                buffers_affected.insert(buffer.read(cx).remote_id());
10953            };
10954        }
10955
10956        self.display_map.update(cx, update);
10957
10958        if auto_scroll {
10959            self.request_autoscroll(Autoscroll::fit(), cx);
10960        }
10961
10962        for buffer_id in buffers_affected {
10963            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10964        }
10965
10966        cx.notify();
10967        self.scrollbar_marker_state.dirty = true;
10968        self.active_indent_guides_state.dirty = true;
10969    }
10970
10971    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10972        self.display_map.read(cx).fold_placeholder.clone()
10973    }
10974
10975    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10976        if hovered != self.gutter_hovered {
10977            self.gutter_hovered = hovered;
10978            cx.notify();
10979        }
10980    }
10981
10982    pub fn insert_blocks(
10983        &mut self,
10984        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10985        autoscroll: Option<Autoscroll>,
10986        cx: &mut ViewContext<Self>,
10987    ) -> Vec<CustomBlockId> {
10988        let blocks = self
10989            .display_map
10990            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10991        if let Some(autoscroll) = autoscroll {
10992            self.request_autoscroll(autoscroll, cx);
10993        }
10994        cx.notify();
10995        blocks
10996    }
10997
10998    pub fn resize_blocks(
10999        &mut self,
11000        heights: HashMap<CustomBlockId, u32>,
11001        autoscroll: Option<Autoscroll>,
11002        cx: &mut ViewContext<Self>,
11003    ) {
11004        self.display_map
11005            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11006        if let Some(autoscroll) = autoscroll {
11007            self.request_autoscroll(autoscroll, cx);
11008        }
11009        cx.notify();
11010    }
11011
11012    pub fn replace_blocks(
11013        &mut self,
11014        renderers: HashMap<CustomBlockId, RenderBlock>,
11015        autoscroll: Option<Autoscroll>,
11016        cx: &mut ViewContext<Self>,
11017    ) {
11018        self.display_map
11019            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11020        if let Some(autoscroll) = autoscroll {
11021            self.request_autoscroll(autoscroll, cx);
11022        }
11023        cx.notify();
11024    }
11025
11026    pub fn remove_blocks(
11027        &mut self,
11028        block_ids: HashSet<CustomBlockId>,
11029        autoscroll: Option<Autoscroll>,
11030        cx: &mut ViewContext<Self>,
11031    ) {
11032        self.display_map.update(cx, |display_map, cx| {
11033            display_map.remove_blocks(block_ids, cx)
11034        });
11035        if let Some(autoscroll) = autoscroll {
11036            self.request_autoscroll(autoscroll, cx);
11037        }
11038        cx.notify();
11039    }
11040
11041    pub fn row_for_block(
11042        &self,
11043        block_id: CustomBlockId,
11044        cx: &mut ViewContext<Self>,
11045    ) -> Option<DisplayRow> {
11046        self.display_map
11047            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11048    }
11049
11050    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11051        self.focused_block = Some(focused_block);
11052    }
11053
11054    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11055        self.focused_block.take()
11056    }
11057
11058    pub fn insert_creases(
11059        &mut self,
11060        creases: impl IntoIterator<Item = Crease<Anchor>>,
11061        cx: &mut ViewContext<Self>,
11062    ) -> Vec<CreaseId> {
11063        self.display_map
11064            .update(cx, |map, cx| map.insert_creases(creases, cx))
11065    }
11066
11067    pub fn remove_creases(
11068        &mut self,
11069        ids: impl IntoIterator<Item = CreaseId>,
11070        cx: &mut ViewContext<Self>,
11071    ) {
11072        self.display_map
11073            .update(cx, |map, cx| map.remove_creases(ids, cx));
11074    }
11075
11076    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11077        self.display_map
11078            .update(cx, |map, cx| map.snapshot(cx))
11079            .longest_row()
11080    }
11081
11082    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11083        self.display_map
11084            .update(cx, |map, cx| map.snapshot(cx))
11085            .max_point()
11086    }
11087
11088    pub fn text(&self, cx: &AppContext) -> String {
11089        self.buffer.read(cx).read(cx).text()
11090    }
11091
11092    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11093        let text = self.text(cx);
11094        let text = text.trim();
11095
11096        if text.is_empty() {
11097            return None;
11098        }
11099
11100        Some(text.to_string())
11101    }
11102
11103    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11104        self.transact(cx, |this, cx| {
11105            this.buffer
11106                .read(cx)
11107                .as_singleton()
11108                .expect("you can only call set_text on editors for singleton buffers")
11109                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11110        });
11111    }
11112
11113    pub fn display_text(&self, cx: &mut AppContext) -> String {
11114        self.display_map
11115            .update(cx, |map, cx| map.snapshot(cx))
11116            .text()
11117    }
11118
11119    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11120        let mut wrap_guides = smallvec::smallvec![];
11121
11122        if self.show_wrap_guides == Some(false) {
11123            return wrap_guides;
11124        }
11125
11126        let settings = self.buffer.read(cx).settings_at(0, cx);
11127        if settings.show_wrap_guides {
11128            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11129                wrap_guides.push((soft_wrap as usize, true));
11130            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11131                wrap_guides.push((soft_wrap as usize, true));
11132            }
11133            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11134        }
11135
11136        wrap_guides
11137    }
11138
11139    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11140        let settings = self.buffer.read(cx).settings_at(0, cx);
11141        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11142        match mode {
11143            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11144                SoftWrap::None
11145            }
11146            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11147            language_settings::SoftWrap::PreferredLineLength => {
11148                SoftWrap::Column(settings.preferred_line_length)
11149            }
11150            language_settings::SoftWrap::Bounded => {
11151                SoftWrap::Bounded(settings.preferred_line_length)
11152            }
11153        }
11154    }
11155
11156    pub fn set_soft_wrap_mode(
11157        &mut self,
11158        mode: language_settings::SoftWrap,
11159        cx: &mut ViewContext<Self>,
11160    ) {
11161        self.soft_wrap_mode_override = Some(mode);
11162        cx.notify();
11163    }
11164
11165    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11166        self.text_style_refinement = Some(style);
11167    }
11168
11169    /// called by the Element so we know what style we were most recently rendered with.
11170    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11171        let rem_size = cx.rem_size();
11172        self.display_map.update(cx, |map, cx| {
11173            map.set_font(
11174                style.text.font(),
11175                style.text.font_size.to_pixels(rem_size),
11176                cx,
11177            )
11178        });
11179        self.style = Some(style);
11180    }
11181
11182    pub fn style(&self) -> Option<&EditorStyle> {
11183        self.style.as_ref()
11184    }
11185
11186    // Called by the element. This method is not designed to be called outside of the editor
11187    // element's layout code because it does not notify when rewrapping is computed synchronously.
11188    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11189        self.display_map
11190            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11191    }
11192
11193    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11194        if self.soft_wrap_mode_override.is_some() {
11195            self.soft_wrap_mode_override.take();
11196        } else {
11197            let soft_wrap = match self.soft_wrap_mode(cx) {
11198                SoftWrap::GitDiff => return,
11199                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11200                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11201                    language_settings::SoftWrap::None
11202                }
11203            };
11204            self.soft_wrap_mode_override = Some(soft_wrap);
11205        }
11206        cx.notify();
11207    }
11208
11209    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11210        let Some(workspace) = self.workspace() else {
11211            return;
11212        };
11213        let fs = workspace.read(cx).app_state().fs.clone();
11214        let current_show = TabBarSettings::get_global(cx).show;
11215        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11216            setting.show = Some(!current_show);
11217        });
11218    }
11219
11220    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11221        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11222            self.buffer
11223                .read(cx)
11224                .settings_at(0, cx)
11225                .indent_guides
11226                .enabled
11227        });
11228        self.show_indent_guides = Some(!currently_enabled);
11229        cx.notify();
11230    }
11231
11232    fn should_show_indent_guides(&self) -> Option<bool> {
11233        self.show_indent_guides
11234    }
11235
11236    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11237        let mut editor_settings = EditorSettings::get_global(cx).clone();
11238        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11239        EditorSettings::override_global(editor_settings, cx);
11240    }
11241
11242    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11243        self.use_relative_line_numbers
11244            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11245    }
11246
11247    pub fn toggle_relative_line_numbers(
11248        &mut self,
11249        _: &ToggleRelativeLineNumbers,
11250        cx: &mut ViewContext<Self>,
11251    ) {
11252        let is_relative = self.should_use_relative_line_numbers(cx);
11253        self.set_relative_line_number(Some(!is_relative), cx)
11254    }
11255
11256    pub fn set_relative_line_number(
11257        &mut self,
11258        is_relative: Option<bool>,
11259        cx: &mut ViewContext<Self>,
11260    ) {
11261        self.use_relative_line_numbers = is_relative;
11262        cx.notify();
11263    }
11264
11265    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11266        self.show_gutter = show_gutter;
11267        cx.notify();
11268    }
11269
11270    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11271        self.show_scrollbars = show_scrollbars;
11272        cx.notify();
11273    }
11274
11275    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11276        self.show_line_numbers = Some(show_line_numbers);
11277        cx.notify();
11278    }
11279
11280    pub fn set_show_git_diff_gutter(
11281        &mut self,
11282        show_git_diff_gutter: bool,
11283        cx: &mut ViewContext<Self>,
11284    ) {
11285        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11286        cx.notify();
11287    }
11288
11289    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11290        self.show_code_actions = Some(show_code_actions);
11291        cx.notify();
11292    }
11293
11294    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11295        self.show_runnables = Some(show_runnables);
11296        cx.notify();
11297    }
11298
11299    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11300        if self.display_map.read(cx).masked != masked {
11301            self.display_map.update(cx, |map, _| map.masked = masked);
11302        }
11303        cx.notify()
11304    }
11305
11306    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11307        self.show_wrap_guides = Some(show_wrap_guides);
11308        cx.notify();
11309    }
11310
11311    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11312        self.show_indent_guides = Some(show_indent_guides);
11313        cx.notify();
11314    }
11315
11316    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11317        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11318            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11319                if let Some(dir) = file.abs_path(cx).parent() {
11320                    return Some(dir.to_owned());
11321                }
11322            }
11323
11324            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11325                return Some(project_path.path.to_path_buf());
11326            }
11327        }
11328
11329        None
11330    }
11331
11332    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11333        self.active_excerpt(cx)?
11334            .1
11335            .read(cx)
11336            .file()
11337            .and_then(|f| f.as_local())
11338    }
11339
11340    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11341        if let Some(target) = self.target_file(cx) {
11342            cx.reveal_path(&target.abs_path(cx));
11343        }
11344    }
11345
11346    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11347        if let Some(file) = self.target_file(cx) {
11348            if let Some(path) = file.abs_path(cx).to_str() {
11349                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11350            }
11351        }
11352    }
11353
11354    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11355        if let Some(file) = self.target_file(cx) {
11356            if let Some(path) = file.path().to_str() {
11357                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11358            }
11359        }
11360    }
11361
11362    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11363        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11364
11365        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11366            self.start_git_blame(true, cx);
11367        }
11368
11369        cx.notify();
11370    }
11371
11372    pub fn toggle_git_blame_inline(
11373        &mut self,
11374        _: &ToggleGitBlameInline,
11375        cx: &mut ViewContext<Self>,
11376    ) {
11377        self.toggle_git_blame_inline_internal(true, cx);
11378        cx.notify();
11379    }
11380
11381    pub fn git_blame_inline_enabled(&self) -> bool {
11382        self.git_blame_inline_enabled
11383    }
11384
11385    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11386        self.show_selection_menu = self
11387            .show_selection_menu
11388            .map(|show_selections_menu| !show_selections_menu)
11389            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11390
11391        cx.notify();
11392    }
11393
11394    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11395        self.show_selection_menu
11396            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11397    }
11398
11399    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11400        if let Some(project) = self.project.as_ref() {
11401            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11402                return;
11403            };
11404
11405            if buffer.read(cx).file().is_none() {
11406                return;
11407            }
11408
11409            let focused = self.focus_handle(cx).contains_focused(cx);
11410
11411            let project = project.clone();
11412            let blame =
11413                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11414            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11415            self.blame = Some(blame);
11416        }
11417    }
11418
11419    fn toggle_git_blame_inline_internal(
11420        &mut self,
11421        user_triggered: bool,
11422        cx: &mut ViewContext<Self>,
11423    ) {
11424        if self.git_blame_inline_enabled {
11425            self.git_blame_inline_enabled = false;
11426            self.show_git_blame_inline = false;
11427            self.show_git_blame_inline_delay_task.take();
11428        } else {
11429            self.git_blame_inline_enabled = true;
11430            self.start_git_blame_inline(user_triggered, cx);
11431        }
11432
11433        cx.notify();
11434    }
11435
11436    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11437        self.start_git_blame(user_triggered, cx);
11438
11439        if ProjectSettings::get_global(cx)
11440            .git
11441            .inline_blame_delay()
11442            .is_some()
11443        {
11444            self.start_inline_blame_timer(cx);
11445        } else {
11446            self.show_git_blame_inline = true
11447        }
11448    }
11449
11450    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11451        self.blame.as_ref()
11452    }
11453
11454    pub fn show_git_blame_gutter(&self) -> bool {
11455        self.show_git_blame_gutter
11456    }
11457
11458    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11459        self.show_git_blame_gutter && self.has_blame_entries(cx)
11460    }
11461
11462    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11463        self.show_git_blame_inline
11464            && self.focus_handle.is_focused(cx)
11465            && !self.newest_selection_head_on_empty_line(cx)
11466            && self.has_blame_entries(cx)
11467    }
11468
11469    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11470        self.blame()
11471            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11472    }
11473
11474    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11475        let cursor_anchor = self.selections.newest_anchor().head();
11476
11477        let snapshot = self.buffer.read(cx).snapshot(cx);
11478        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11479
11480        snapshot.line_len(buffer_row) == 0
11481    }
11482
11483    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11484        let buffer_and_selection = maybe!({
11485            let selection = self.selections.newest::<Point>(cx);
11486            let selection_range = selection.range();
11487
11488            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11489                (buffer, selection_range.start.row..selection_range.end.row)
11490            } else {
11491                let buffer_ranges = self
11492                    .buffer()
11493                    .read(cx)
11494                    .range_to_buffer_ranges(selection_range, cx);
11495
11496                let (buffer, range, _) = if selection.reversed {
11497                    buffer_ranges.first()
11498                } else {
11499                    buffer_ranges.last()
11500                }?;
11501
11502                let snapshot = buffer.read(cx).snapshot();
11503                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11504                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11505                (buffer.clone(), selection)
11506            };
11507
11508            Some((buffer, selection))
11509        });
11510
11511        let Some((buffer, selection)) = buffer_and_selection else {
11512            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11513        };
11514
11515        let Some(project) = self.project.as_ref() else {
11516            return Task::ready(Err(anyhow!("editor does not have project")));
11517        };
11518
11519        project.update(cx, |project, cx| {
11520            project.get_permalink_to_line(&buffer, selection, cx)
11521        })
11522    }
11523
11524    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11525        let permalink_task = self.get_permalink_to_line(cx);
11526        let workspace = self.workspace();
11527
11528        cx.spawn(|_, mut cx| async move {
11529            match permalink_task.await {
11530                Ok(permalink) => {
11531                    cx.update(|cx| {
11532                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11533                    })
11534                    .ok();
11535                }
11536                Err(err) => {
11537                    let message = format!("Failed to copy permalink: {err}");
11538
11539                    Err::<(), anyhow::Error>(err).log_err();
11540
11541                    if let Some(workspace) = workspace {
11542                        workspace
11543                            .update(&mut cx, |workspace, cx| {
11544                                struct CopyPermalinkToLine;
11545
11546                                workspace.show_toast(
11547                                    Toast::new(
11548                                        NotificationId::unique::<CopyPermalinkToLine>(),
11549                                        message,
11550                                    ),
11551                                    cx,
11552                                )
11553                            })
11554                            .ok();
11555                    }
11556                }
11557            }
11558        })
11559        .detach();
11560    }
11561
11562    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11563        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11564        if let Some(file) = self.target_file(cx) {
11565            if let Some(path) = file.path().to_str() {
11566                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11567            }
11568        }
11569    }
11570
11571    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11572        let permalink_task = self.get_permalink_to_line(cx);
11573        let workspace = self.workspace();
11574
11575        cx.spawn(|_, mut cx| async move {
11576            match permalink_task.await {
11577                Ok(permalink) => {
11578                    cx.update(|cx| {
11579                        cx.open_url(permalink.as_ref());
11580                    })
11581                    .ok();
11582                }
11583                Err(err) => {
11584                    let message = format!("Failed to open permalink: {err}");
11585
11586                    Err::<(), anyhow::Error>(err).log_err();
11587
11588                    if let Some(workspace) = workspace {
11589                        workspace
11590                            .update(&mut cx, |workspace, cx| {
11591                                struct OpenPermalinkToLine;
11592
11593                                workspace.show_toast(
11594                                    Toast::new(
11595                                        NotificationId::unique::<OpenPermalinkToLine>(),
11596                                        message,
11597                                    ),
11598                                    cx,
11599                                )
11600                            })
11601                            .ok();
11602                    }
11603                }
11604            }
11605        })
11606        .detach();
11607    }
11608
11609    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11610        self.insert_uuid(UuidVersion::V4, cx);
11611    }
11612
11613    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11614        self.insert_uuid(UuidVersion::V7, cx);
11615    }
11616
11617    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11618        self.transact(cx, |this, cx| {
11619            let edits = this
11620                .selections
11621                .all::<Point>(cx)
11622                .into_iter()
11623                .map(|selection| {
11624                    let uuid = match version {
11625                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11626                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11627                    };
11628
11629                    (selection.range(), uuid.to_string())
11630                });
11631            this.edit(edits, cx);
11632            this.refresh_inline_completion(true, false, cx);
11633        });
11634    }
11635
11636    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11637    /// last highlight added will be used.
11638    ///
11639    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11640    pub fn highlight_rows<T: 'static>(
11641        &mut self,
11642        range: Range<Anchor>,
11643        color: Hsla,
11644        should_autoscroll: bool,
11645        cx: &mut ViewContext<Self>,
11646    ) {
11647        let snapshot = self.buffer().read(cx).snapshot(cx);
11648        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11649        let ix = row_highlights.binary_search_by(|highlight| {
11650            Ordering::Equal
11651                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11652                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11653        });
11654
11655        if let Err(mut ix) = ix {
11656            let index = post_inc(&mut self.highlight_order);
11657
11658            // If this range intersects with the preceding highlight, then merge it with
11659            // the preceding highlight. Otherwise insert a new highlight.
11660            let mut merged = false;
11661            if ix > 0 {
11662                let prev_highlight = &mut row_highlights[ix - 1];
11663                if prev_highlight
11664                    .range
11665                    .end
11666                    .cmp(&range.start, &snapshot)
11667                    .is_ge()
11668                {
11669                    ix -= 1;
11670                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11671                        prev_highlight.range.end = range.end;
11672                    }
11673                    merged = true;
11674                    prev_highlight.index = index;
11675                    prev_highlight.color = color;
11676                    prev_highlight.should_autoscroll = should_autoscroll;
11677                }
11678            }
11679
11680            if !merged {
11681                row_highlights.insert(
11682                    ix,
11683                    RowHighlight {
11684                        range: range.clone(),
11685                        index,
11686                        color,
11687                        should_autoscroll,
11688                    },
11689                );
11690            }
11691
11692            // If any of the following highlights intersect with this one, merge them.
11693            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11694                let highlight = &row_highlights[ix];
11695                if next_highlight
11696                    .range
11697                    .start
11698                    .cmp(&highlight.range.end, &snapshot)
11699                    .is_le()
11700                {
11701                    if next_highlight
11702                        .range
11703                        .end
11704                        .cmp(&highlight.range.end, &snapshot)
11705                        .is_gt()
11706                    {
11707                        row_highlights[ix].range.end = next_highlight.range.end;
11708                    }
11709                    row_highlights.remove(ix + 1);
11710                } else {
11711                    break;
11712                }
11713            }
11714        }
11715    }
11716
11717    /// Remove any highlighted row ranges of the given type that intersect the
11718    /// given ranges.
11719    pub fn remove_highlighted_rows<T: 'static>(
11720        &mut self,
11721        ranges_to_remove: Vec<Range<Anchor>>,
11722        cx: &mut ViewContext<Self>,
11723    ) {
11724        let snapshot = self.buffer().read(cx).snapshot(cx);
11725        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11726        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11727        row_highlights.retain(|highlight| {
11728            while let Some(range_to_remove) = ranges_to_remove.peek() {
11729                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11730                    Ordering::Less | Ordering::Equal => {
11731                        ranges_to_remove.next();
11732                    }
11733                    Ordering::Greater => {
11734                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11735                            Ordering::Less | Ordering::Equal => {
11736                                return false;
11737                            }
11738                            Ordering::Greater => break,
11739                        }
11740                    }
11741                }
11742            }
11743
11744            true
11745        })
11746    }
11747
11748    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11749    pub fn clear_row_highlights<T: 'static>(&mut self) {
11750        self.highlighted_rows.remove(&TypeId::of::<T>());
11751    }
11752
11753    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11754    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11755        self.highlighted_rows
11756            .get(&TypeId::of::<T>())
11757            .map_or(&[] as &[_], |vec| vec.as_slice())
11758            .iter()
11759            .map(|highlight| (highlight.range.clone(), highlight.color))
11760    }
11761
11762    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11763    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11764    /// Allows to ignore certain kinds of highlights.
11765    pub fn highlighted_display_rows(
11766        &mut self,
11767        cx: &mut WindowContext,
11768    ) -> BTreeMap<DisplayRow, Hsla> {
11769        let snapshot = self.snapshot(cx);
11770        let mut used_highlight_orders = HashMap::default();
11771        self.highlighted_rows
11772            .iter()
11773            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11774            .fold(
11775                BTreeMap::<DisplayRow, Hsla>::new(),
11776                |mut unique_rows, highlight| {
11777                    let start = highlight.range.start.to_display_point(&snapshot);
11778                    let end = highlight.range.end.to_display_point(&snapshot);
11779                    let start_row = start.row().0;
11780                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11781                        && end.column() == 0
11782                    {
11783                        end.row().0.saturating_sub(1)
11784                    } else {
11785                        end.row().0
11786                    };
11787                    for row in start_row..=end_row {
11788                        let used_index =
11789                            used_highlight_orders.entry(row).or_insert(highlight.index);
11790                        if highlight.index >= *used_index {
11791                            *used_index = highlight.index;
11792                            unique_rows.insert(DisplayRow(row), highlight.color);
11793                        }
11794                    }
11795                    unique_rows
11796                },
11797            )
11798    }
11799
11800    pub fn highlighted_display_row_for_autoscroll(
11801        &self,
11802        snapshot: &DisplaySnapshot,
11803    ) -> Option<DisplayRow> {
11804        self.highlighted_rows
11805            .values()
11806            .flat_map(|highlighted_rows| highlighted_rows.iter())
11807            .filter_map(|highlight| {
11808                if highlight.should_autoscroll {
11809                    Some(highlight.range.start.to_display_point(snapshot).row())
11810                } else {
11811                    None
11812                }
11813            })
11814            .min()
11815    }
11816
11817    pub fn set_search_within_ranges(
11818        &mut self,
11819        ranges: &[Range<Anchor>],
11820        cx: &mut ViewContext<Self>,
11821    ) {
11822        self.highlight_background::<SearchWithinRange>(
11823            ranges,
11824            |colors| colors.editor_document_highlight_read_background,
11825            cx,
11826        )
11827    }
11828
11829    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11830        self.breadcrumb_header = Some(new_header);
11831    }
11832
11833    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11834        self.clear_background_highlights::<SearchWithinRange>(cx);
11835    }
11836
11837    pub fn highlight_background<T: 'static>(
11838        &mut self,
11839        ranges: &[Range<Anchor>],
11840        color_fetcher: fn(&ThemeColors) -> Hsla,
11841        cx: &mut ViewContext<Self>,
11842    ) {
11843        self.background_highlights
11844            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11845        self.scrollbar_marker_state.dirty = true;
11846        cx.notify();
11847    }
11848
11849    pub fn clear_background_highlights<T: 'static>(
11850        &mut self,
11851        cx: &mut ViewContext<Self>,
11852    ) -> Option<BackgroundHighlight> {
11853        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11854        if !text_highlights.1.is_empty() {
11855            self.scrollbar_marker_state.dirty = true;
11856            cx.notify();
11857        }
11858        Some(text_highlights)
11859    }
11860
11861    pub fn highlight_gutter<T: 'static>(
11862        &mut self,
11863        ranges: &[Range<Anchor>],
11864        color_fetcher: fn(&AppContext) -> Hsla,
11865        cx: &mut ViewContext<Self>,
11866    ) {
11867        self.gutter_highlights
11868            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11869        cx.notify();
11870    }
11871
11872    pub fn clear_gutter_highlights<T: 'static>(
11873        &mut self,
11874        cx: &mut ViewContext<Self>,
11875    ) -> Option<GutterHighlight> {
11876        cx.notify();
11877        self.gutter_highlights.remove(&TypeId::of::<T>())
11878    }
11879
11880    #[cfg(feature = "test-support")]
11881    pub fn all_text_background_highlights(
11882        &mut self,
11883        cx: &mut ViewContext<Self>,
11884    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11885        let snapshot = self.snapshot(cx);
11886        let buffer = &snapshot.buffer_snapshot;
11887        let start = buffer.anchor_before(0);
11888        let end = buffer.anchor_after(buffer.len());
11889        let theme = cx.theme().colors();
11890        self.background_highlights_in_range(start..end, &snapshot, theme)
11891    }
11892
11893    #[cfg(feature = "test-support")]
11894    pub fn search_background_highlights(
11895        &mut self,
11896        cx: &mut ViewContext<Self>,
11897    ) -> Vec<Range<Point>> {
11898        let snapshot = self.buffer().read(cx).snapshot(cx);
11899
11900        let highlights = self
11901            .background_highlights
11902            .get(&TypeId::of::<items::BufferSearchHighlights>());
11903
11904        if let Some((_color, ranges)) = highlights {
11905            ranges
11906                .iter()
11907                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11908                .collect_vec()
11909        } else {
11910            vec![]
11911        }
11912    }
11913
11914    fn document_highlights_for_position<'a>(
11915        &'a self,
11916        position: Anchor,
11917        buffer: &'a MultiBufferSnapshot,
11918    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11919        let read_highlights = self
11920            .background_highlights
11921            .get(&TypeId::of::<DocumentHighlightRead>())
11922            .map(|h| &h.1);
11923        let write_highlights = self
11924            .background_highlights
11925            .get(&TypeId::of::<DocumentHighlightWrite>())
11926            .map(|h| &h.1);
11927        let left_position = position.bias_left(buffer);
11928        let right_position = position.bias_right(buffer);
11929        read_highlights
11930            .into_iter()
11931            .chain(write_highlights)
11932            .flat_map(move |ranges| {
11933                let start_ix = match ranges.binary_search_by(|probe| {
11934                    let cmp = probe.end.cmp(&left_position, buffer);
11935                    if cmp.is_ge() {
11936                        Ordering::Greater
11937                    } else {
11938                        Ordering::Less
11939                    }
11940                }) {
11941                    Ok(i) | Err(i) => i,
11942                };
11943
11944                ranges[start_ix..]
11945                    .iter()
11946                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11947            })
11948    }
11949
11950    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11951        self.background_highlights
11952            .get(&TypeId::of::<T>())
11953            .map_or(false, |(_, highlights)| !highlights.is_empty())
11954    }
11955
11956    pub fn background_highlights_in_range(
11957        &self,
11958        search_range: Range<Anchor>,
11959        display_snapshot: &DisplaySnapshot,
11960        theme: &ThemeColors,
11961    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11962        let mut results = Vec::new();
11963        for (color_fetcher, ranges) in self.background_highlights.values() {
11964            let color = color_fetcher(theme);
11965            let start_ix = match ranges.binary_search_by(|probe| {
11966                let cmp = probe
11967                    .end
11968                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11969                if cmp.is_gt() {
11970                    Ordering::Greater
11971                } else {
11972                    Ordering::Less
11973                }
11974            }) {
11975                Ok(i) | Err(i) => i,
11976            };
11977            for range in &ranges[start_ix..] {
11978                if range
11979                    .start
11980                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11981                    .is_ge()
11982                {
11983                    break;
11984                }
11985
11986                let start = range.start.to_display_point(display_snapshot);
11987                let end = range.end.to_display_point(display_snapshot);
11988                results.push((start..end, color))
11989            }
11990        }
11991        results
11992    }
11993
11994    pub fn background_highlight_row_ranges<T: 'static>(
11995        &self,
11996        search_range: Range<Anchor>,
11997        display_snapshot: &DisplaySnapshot,
11998        count: usize,
11999    ) -> Vec<RangeInclusive<DisplayPoint>> {
12000        let mut results = Vec::new();
12001        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12002            return vec![];
12003        };
12004
12005        let start_ix = match ranges.binary_search_by(|probe| {
12006            let cmp = probe
12007                .end
12008                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12009            if cmp.is_gt() {
12010                Ordering::Greater
12011            } else {
12012                Ordering::Less
12013            }
12014        }) {
12015            Ok(i) | Err(i) => i,
12016        };
12017        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12018            if let (Some(start_display), Some(end_display)) = (start, end) {
12019                results.push(
12020                    start_display.to_display_point(display_snapshot)
12021                        ..=end_display.to_display_point(display_snapshot),
12022                );
12023            }
12024        };
12025        let mut start_row: Option<Point> = None;
12026        let mut end_row: Option<Point> = None;
12027        if ranges.len() > count {
12028            return Vec::new();
12029        }
12030        for range in &ranges[start_ix..] {
12031            if range
12032                .start
12033                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12034                .is_ge()
12035            {
12036                break;
12037            }
12038            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12039            if let Some(current_row) = &end_row {
12040                if end.row == current_row.row {
12041                    continue;
12042                }
12043            }
12044            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12045            if start_row.is_none() {
12046                assert_eq!(end_row, None);
12047                start_row = Some(start);
12048                end_row = Some(end);
12049                continue;
12050            }
12051            if let Some(current_end) = end_row.as_mut() {
12052                if start.row > current_end.row + 1 {
12053                    push_region(start_row, end_row);
12054                    start_row = Some(start);
12055                    end_row = Some(end);
12056                } else {
12057                    // Merge two hunks.
12058                    *current_end = end;
12059                }
12060            } else {
12061                unreachable!();
12062            }
12063        }
12064        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12065        push_region(start_row, end_row);
12066        results
12067    }
12068
12069    pub fn gutter_highlights_in_range(
12070        &self,
12071        search_range: Range<Anchor>,
12072        display_snapshot: &DisplaySnapshot,
12073        cx: &AppContext,
12074    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12075        let mut results = Vec::new();
12076        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12077            let color = color_fetcher(cx);
12078            let start_ix = match ranges.binary_search_by(|probe| {
12079                let cmp = probe
12080                    .end
12081                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12082                if cmp.is_gt() {
12083                    Ordering::Greater
12084                } else {
12085                    Ordering::Less
12086                }
12087            }) {
12088                Ok(i) | Err(i) => i,
12089            };
12090            for range in &ranges[start_ix..] {
12091                if range
12092                    .start
12093                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12094                    .is_ge()
12095                {
12096                    break;
12097                }
12098
12099                let start = range.start.to_display_point(display_snapshot);
12100                let end = range.end.to_display_point(display_snapshot);
12101                results.push((start..end, color))
12102            }
12103        }
12104        results
12105    }
12106
12107    /// Get the text ranges corresponding to the redaction query
12108    pub fn redacted_ranges(
12109        &self,
12110        search_range: Range<Anchor>,
12111        display_snapshot: &DisplaySnapshot,
12112        cx: &WindowContext,
12113    ) -> Vec<Range<DisplayPoint>> {
12114        display_snapshot
12115            .buffer_snapshot
12116            .redacted_ranges(search_range, |file| {
12117                if let Some(file) = file {
12118                    file.is_private()
12119                        && EditorSettings::get(
12120                            Some(SettingsLocation {
12121                                worktree_id: file.worktree_id(cx),
12122                                path: file.path().as_ref(),
12123                            }),
12124                            cx,
12125                        )
12126                        .redact_private_values
12127                } else {
12128                    false
12129                }
12130            })
12131            .map(|range| {
12132                range.start.to_display_point(display_snapshot)
12133                    ..range.end.to_display_point(display_snapshot)
12134            })
12135            .collect()
12136    }
12137
12138    pub fn highlight_text<T: 'static>(
12139        &mut self,
12140        ranges: Vec<Range<Anchor>>,
12141        style: HighlightStyle,
12142        cx: &mut ViewContext<Self>,
12143    ) {
12144        self.display_map.update(cx, |map, _| {
12145            map.highlight_text(TypeId::of::<T>(), ranges, style)
12146        });
12147        cx.notify();
12148    }
12149
12150    pub(crate) fn highlight_inlays<T: 'static>(
12151        &mut self,
12152        highlights: Vec<InlayHighlight>,
12153        style: HighlightStyle,
12154        cx: &mut ViewContext<Self>,
12155    ) {
12156        self.display_map.update(cx, |map, _| {
12157            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12158        });
12159        cx.notify();
12160    }
12161
12162    pub fn text_highlights<'a, T: 'static>(
12163        &'a self,
12164        cx: &'a AppContext,
12165    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12166        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12167    }
12168
12169    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12170        let cleared = self
12171            .display_map
12172            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12173        if cleared {
12174            cx.notify();
12175        }
12176    }
12177
12178    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12179        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12180            && self.focus_handle.is_focused(cx)
12181    }
12182
12183    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12184        self.show_cursor_when_unfocused = is_enabled;
12185        cx.notify();
12186    }
12187
12188    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12189        self.project
12190            .as_ref()
12191            .map(|project| project.read(cx).lsp_store())
12192    }
12193
12194    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12195        cx.notify();
12196    }
12197
12198    fn on_buffer_event(
12199        &mut self,
12200        multibuffer: Model<MultiBuffer>,
12201        event: &multi_buffer::Event,
12202        cx: &mut ViewContext<Self>,
12203    ) {
12204        match event {
12205            multi_buffer::Event::Edited {
12206                singleton_buffer_edited,
12207                edited_buffer: buffer_edited,
12208            } => {
12209                self.scrollbar_marker_state.dirty = true;
12210                self.active_indent_guides_state.dirty = true;
12211                self.refresh_active_diagnostics(cx);
12212                self.refresh_code_actions(cx);
12213                if self.has_active_inline_completion() {
12214                    self.update_visible_inline_completion(cx);
12215                }
12216                if let Some(buffer) = buffer_edited {
12217                    let buffer_id = buffer.read(cx).remote_id();
12218                    if !self.registered_buffers.contains_key(&buffer_id) {
12219                        if let Some(lsp_store) = self.lsp_store(cx) {
12220                            lsp_store.update(cx, |lsp_store, cx| {
12221                                self.registered_buffers.insert(
12222                                    buffer_id,
12223                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12224                                );
12225                            })
12226                        }
12227                    }
12228                }
12229                cx.emit(EditorEvent::BufferEdited);
12230                cx.emit(SearchEvent::MatchesInvalidated);
12231                if *singleton_buffer_edited {
12232                    if let Some(project) = &self.project {
12233                        let project = project.read(cx);
12234                        #[allow(clippy::mutable_key_type)]
12235                        let languages_affected = multibuffer
12236                            .read(cx)
12237                            .all_buffers()
12238                            .into_iter()
12239                            .filter_map(|buffer| {
12240                                let buffer = buffer.read(cx);
12241                                let language = buffer.language()?;
12242                                if project.is_local()
12243                                    && project
12244                                        .language_servers_for_local_buffer(buffer, cx)
12245                                        .count()
12246                                        == 0
12247                                {
12248                                    None
12249                                } else {
12250                                    Some(language)
12251                                }
12252                            })
12253                            .cloned()
12254                            .collect::<HashSet<_>>();
12255                        if !languages_affected.is_empty() {
12256                            self.refresh_inlay_hints(
12257                                InlayHintRefreshReason::BufferEdited(languages_affected),
12258                                cx,
12259                            );
12260                        }
12261                    }
12262                }
12263
12264                let Some(project) = &self.project else { return };
12265                let (telemetry, is_via_ssh) = {
12266                    let project = project.read(cx);
12267                    let telemetry = project.client().telemetry().clone();
12268                    let is_via_ssh = project.is_via_ssh();
12269                    (telemetry, is_via_ssh)
12270                };
12271                refresh_linked_ranges(self, cx);
12272                telemetry.log_edit_event("editor", is_via_ssh);
12273            }
12274            multi_buffer::Event::ExcerptsAdded {
12275                buffer,
12276                predecessor,
12277                excerpts,
12278            } => {
12279                self.tasks_update_task = Some(self.refresh_runnables(cx));
12280                let buffer_id = buffer.read(cx).remote_id();
12281                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12282                    if let Some(project) = &self.project {
12283                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12284                    }
12285                }
12286                cx.emit(EditorEvent::ExcerptsAdded {
12287                    buffer: buffer.clone(),
12288                    predecessor: *predecessor,
12289                    excerpts: excerpts.clone(),
12290                });
12291                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12292            }
12293            multi_buffer::Event::ExcerptsRemoved { ids } => {
12294                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12295                let buffer = self.buffer.read(cx);
12296                self.registered_buffers
12297                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12298                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12299            }
12300            multi_buffer::Event::ExcerptsEdited { ids } => {
12301                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12302            }
12303            multi_buffer::Event::ExcerptsExpanded { ids } => {
12304                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12305            }
12306            multi_buffer::Event::Reparsed(buffer_id) => {
12307                self.tasks_update_task = Some(self.refresh_runnables(cx));
12308
12309                cx.emit(EditorEvent::Reparsed(*buffer_id));
12310            }
12311            multi_buffer::Event::LanguageChanged(buffer_id) => {
12312                linked_editing_ranges::refresh_linked_ranges(self, cx);
12313                cx.emit(EditorEvent::Reparsed(*buffer_id));
12314                cx.notify();
12315            }
12316            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12317            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12318            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12319                cx.emit(EditorEvent::TitleChanged)
12320            }
12321            // multi_buffer::Event::DiffBaseChanged => {
12322            //     self.scrollbar_marker_state.dirty = true;
12323            //     cx.emit(EditorEvent::DiffBaseChanged);
12324            //     cx.notify();
12325            // }
12326            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12327            multi_buffer::Event::DiagnosticsUpdated => {
12328                self.refresh_active_diagnostics(cx);
12329                self.scrollbar_marker_state.dirty = true;
12330                cx.notify();
12331            }
12332            _ => {}
12333        };
12334    }
12335
12336    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12337        cx.notify();
12338    }
12339
12340    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12341        self.tasks_update_task = Some(self.refresh_runnables(cx));
12342        self.refresh_inline_completion(true, false, cx);
12343        self.refresh_inlay_hints(
12344            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12345                self.selections.newest_anchor().head(),
12346                &self.buffer.read(cx).snapshot(cx),
12347                cx,
12348            )),
12349            cx,
12350        );
12351
12352        let old_cursor_shape = self.cursor_shape;
12353
12354        {
12355            let editor_settings = EditorSettings::get_global(cx);
12356            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12357            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12358            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12359        }
12360
12361        if old_cursor_shape != self.cursor_shape {
12362            cx.emit(EditorEvent::CursorShapeChanged);
12363        }
12364
12365        let project_settings = ProjectSettings::get_global(cx);
12366        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12367
12368        if self.mode == EditorMode::Full {
12369            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12370            if self.git_blame_inline_enabled != inline_blame_enabled {
12371                self.toggle_git_blame_inline_internal(false, cx);
12372            }
12373        }
12374
12375        cx.notify();
12376    }
12377
12378    pub fn set_searchable(&mut self, searchable: bool) {
12379        self.searchable = searchable;
12380    }
12381
12382    pub fn searchable(&self) -> bool {
12383        self.searchable
12384    }
12385
12386    fn open_proposed_changes_editor(
12387        &mut self,
12388        _: &OpenProposedChangesEditor,
12389        cx: &mut ViewContext<Self>,
12390    ) {
12391        let Some(workspace) = self.workspace() else {
12392            cx.propagate();
12393            return;
12394        };
12395
12396        let selections = self.selections.all::<usize>(cx);
12397        let buffer = self.buffer.read(cx);
12398        let mut new_selections_by_buffer = HashMap::default();
12399        for selection in selections {
12400            for (buffer, range, _) in
12401                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12402            {
12403                let mut range = range.to_point(buffer.read(cx));
12404                range.start.column = 0;
12405                range.end.column = buffer.read(cx).line_len(range.end.row);
12406                new_selections_by_buffer
12407                    .entry(buffer)
12408                    .or_insert(Vec::new())
12409                    .push(range)
12410            }
12411        }
12412
12413        let proposed_changes_buffers = new_selections_by_buffer
12414            .into_iter()
12415            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12416            .collect::<Vec<_>>();
12417        let proposed_changes_editor = cx.new_view(|cx| {
12418            ProposedChangesEditor::new(
12419                "Proposed changes",
12420                proposed_changes_buffers,
12421                self.project.clone(),
12422                cx,
12423            )
12424        });
12425
12426        cx.window_context().defer(move |cx| {
12427            workspace.update(cx, |workspace, cx| {
12428                workspace.active_pane().update(cx, |pane, cx| {
12429                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12430                });
12431            });
12432        });
12433    }
12434
12435    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12436        self.open_excerpts_common(None, true, cx)
12437    }
12438
12439    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12440        self.open_excerpts_common(None, false, cx)
12441    }
12442
12443    fn open_excerpts_common(
12444        &mut self,
12445        jump_data: Option<JumpData>,
12446        split: bool,
12447        cx: &mut ViewContext<Self>,
12448    ) {
12449        let Some(workspace) = self.workspace() else {
12450            cx.propagate();
12451            return;
12452        };
12453
12454        if self.buffer.read(cx).is_singleton() {
12455            cx.propagate();
12456            return;
12457        }
12458
12459        let mut new_selections_by_buffer = HashMap::default();
12460        match &jump_data {
12461            Some(jump_data) => {
12462                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12463                if let Some(buffer) = multi_buffer_snapshot
12464                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12465                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12466                {
12467                    let buffer_snapshot = buffer.read(cx).snapshot();
12468                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12469                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12470                    } else {
12471                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12472                    };
12473                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12474                    new_selections_by_buffer.insert(
12475                        buffer,
12476                        (
12477                            vec![jump_to_offset..jump_to_offset],
12478                            Some(jump_data.line_offset_from_top),
12479                        ),
12480                    );
12481                }
12482            }
12483            None => {
12484                let selections = self.selections.all::<usize>(cx);
12485                let buffer = self.buffer.read(cx);
12486                for selection in selections {
12487                    for (mut buffer_handle, mut range, _) in
12488                        buffer.range_to_buffer_ranges(selection.range(), cx)
12489                    {
12490                        // When editing branch buffers, jump to the corresponding location
12491                        // in their base buffer.
12492                        let buffer = buffer_handle.read(cx);
12493                        if let Some(base_buffer) = buffer.base_buffer() {
12494                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12495                            buffer_handle = base_buffer;
12496                        }
12497
12498                        if selection.reversed {
12499                            mem::swap(&mut range.start, &mut range.end);
12500                        }
12501                        new_selections_by_buffer
12502                            .entry(buffer_handle)
12503                            .or_insert((Vec::new(), None))
12504                            .0
12505                            .push(range)
12506                    }
12507                }
12508            }
12509        }
12510
12511        if new_selections_by_buffer.is_empty() {
12512            return;
12513        }
12514
12515        // We defer the pane interaction because we ourselves are a workspace item
12516        // and activating a new item causes the pane to call a method on us reentrantly,
12517        // which panics if we're on the stack.
12518        cx.window_context().defer(move |cx| {
12519            workspace.update(cx, |workspace, cx| {
12520                let pane = if split {
12521                    workspace.adjacent_pane(cx)
12522                } else {
12523                    workspace.active_pane().clone()
12524                };
12525
12526                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12527                    let editor = buffer
12528                        .read(cx)
12529                        .file()
12530                        .is_none()
12531                        .then(|| {
12532                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12533                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12534                            // Instead, we try to activate the existing editor in the pane first.
12535                            let (editor, pane_item_index) =
12536                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12537                                    let editor = item.downcast::<Editor>()?;
12538                                    let singleton_buffer =
12539                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12540                                    if singleton_buffer == buffer {
12541                                        Some((editor, i))
12542                                    } else {
12543                                        None
12544                                    }
12545                                })?;
12546                            pane.update(cx, |pane, cx| {
12547                                pane.activate_item(pane_item_index, true, true, cx)
12548                            });
12549                            Some(editor)
12550                        })
12551                        .flatten()
12552                        .unwrap_or_else(|| {
12553                            workspace.open_project_item::<Self>(
12554                                pane.clone(),
12555                                buffer,
12556                                true,
12557                                true,
12558                                cx,
12559                            )
12560                        });
12561
12562                    editor.update(cx, |editor, cx| {
12563                        let autoscroll = match scroll_offset {
12564                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12565                            None => Autoscroll::newest(),
12566                        };
12567                        let nav_history = editor.nav_history.take();
12568                        editor.change_selections(Some(autoscroll), cx, |s| {
12569                            s.select_ranges(ranges);
12570                        });
12571                        editor.nav_history = nav_history;
12572                    });
12573                }
12574            })
12575        });
12576    }
12577
12578    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12579        let snapshot = self.buffer.read(cx).read(cx);
12580        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12581        Some(
12582            ranges
12583                .iter()
12584                .map(move |range| {
12585                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12586                })
12587                .collect(),
12588        )
12589    }
12590
12591    fn selection_replacement_ranges(
12592        &self,
12593        range: Range<OffsetUtf16>,
12594        cx: &mut AppContext,
12595    ) -> Vec<Range<OffsetUtf16>> {
12596        let selections = self.selections.all::<OffsetUtf16>(cx);
12597        let newest_selection = selections
12598            .iter()
12599            .max_by_key(|selection| selection.id)
12600            .unwrap();
12601        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12602        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12603        let snapshot = self.buffer.read(cx).read(cx);
12604        selections
12605            .into_iter()
12606            .map(|mut selection| {
12607                selection.start.0 =
12608                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12609                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12610                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12611                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12612            })
12613            .collect()
12614    }
12615
12616    fn report_editor_event(
12617        &self,
12618        event_type: &'static str,
12619        file_extension: Option<String>,
12620        cx: &AppContext,
12621    ) {
12622        if cfg!(any(test, feature = "test-support")) {
12623            return;
12624        }
12625
12626        let Some(project) = &self.project else { return };
12627
12628        // If None, we are in a file without an extension
12629        let file = self
12630            .buffer
12631            .read(cx)
12632            .as_singleton()
12633            .and_then(|b| b.read(cx).file());
12634        let file_extension = file_extension.or(file
12635            .as_ref()
12636            .and_then(|file| Path::new(file.file_name(cx)).extension())
12637            .and_then(|e| e.to_str())
12638            .map(|a| a.to_string()));
12639
12640        let vim_mode = cx
12641            .global::<SettingsStore>()
12642            .raw_user_settings()
12643            .get("vim_mode")
12644            == Some(&serde_json::Value::Bool(true));
12645
12646        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12647            == language::language_settings::InlineCompletionProvider::Copilot;
12648        let copilot_enabled_for_language = self
12649            .buffer
12650            .read(cx)
12651            .settings_at(0, cx)
12652            .show_inline_completions;
12653
12654        let project = project.read(cx);
12655        telemetry::event!(
12656            event_type,
12657            file_extension,
12658            vim_mode,
12659            copilot_enabled,
12660            copilot_enabled_for_language,
12661            is_via_ssh = project.is_via_ssh(),
12662        );
12663    }
12664
12665    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12666    /// with each line being an array of {text, highlight} objects.
12667    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12668        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12669            return;
12670        };
12671
12672        #[derive(Serialize)]
12673        struct Chunk<'a> {
12674            text: String,
12675            highlight: Option<&'a str>,
12676        }
12677
12678        let snapshot = buffer.read(cx).snapshot();
12679        let range = self
12680            .selected_text_range(false, cx)
12681            .and_then(|selection| {
12682                if selection.range.is_empty() {
12683                    None
12684                } else {
12685                    Some(selection.range)
12686                }
12687            })
12688            .unwrap_or_else(|| 0..snapshot.len());
12689
12690        let chunks = snapshot.chunks(range, true);
12691        let mut lines = Vec::new();
12692        let mut line: VecDeque<Chunk> = VecDeque::new();
12693
12694        let Some(style) = self.style.as_ref() else {
12695            return;
12696        };
12697
12698        for chunk in chunks {
12699            let highlight = chunk
12700                .syntax_highlight_id
12701                .and_then(|id| id.name(&style.syntax));
12702            let mut chunk_lines = chunk.text.split('\n').peekable();
12703            while let Some(text) = chunk_lines.next() {
12704                let mut merged_with_last_token = false;
12705                if let Some(last_token) = line.back_mut() {
12706                    if last_token.highlight == highlight {
12707                        last_token.text.push_str(text);
12708                        merged_with_last_token = true;
12709                    }
12710                }
12711
12712                if !merged_with_last_token {
12713                    line.push_back(Chunk {
12714                        text: text.into(),
12715                        highlight,
12716                    });
12717                }
12718
12719                if chunk_lines.peek().is_some() {
12720                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12721                        line.pop_front();
12722                    }
12723                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12724                        line.pop_back();
12725                    }
12726
12727                    lines.push(mem::take(&mut line));
12728                }
12729            }
12730        }
12731
12732        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12733            return;
12734        };
12735        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12736    }
12737
12738    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12739        self.request_autoscroll(Autoscroll::newest(), cx);
12740        let position = self.selections.newest_display(cx).start;
12741        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12742    }
12743
12744    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12745        &self.inlay_hint_cache
12746    }
12747
12748    pub fn replay_insert_event(
12749        &mut self,
12750        text: &str,
12751        relative_utf16_range: Option<Range<isize>>,
12752        cx: &mut ViewContext<Self>,
12753    ) {
12754        if !self.input_enabled {
12755            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12756            return;
12757        }
12758        if let Some(relative_utf16_range) = relative_utf16_range {
12759            let selections = self.selections.all::<OffsetUtf16>(cx);
12760            self.change_selections(None, cx, |s| {
12761                let new_ranges = selections.into_iter().map(|range| {
12762                    let start = OffsetUtf16(
12763                        range
12764                            .head()
12765                            .0
12766                            .saturating_add_signed(relative_utf16_range.start),
12767                    );
12768                    let end = OffsetUtf16(
12769                        range
12770                            .head()
12771                            .0
12772                            .saturating_add_signed(relative_utf16_range.end),
12773                    );
12774                    start..end
12775                });
12776                s.select_ranges(new_ranges);
12777            });
12778        }
12779
12780        self.handle_input(text, cx);
12781    }
12782
12783    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12784        let Some(provider) = self.semantics_provider.as_ref() else {
12785            return false;
12786        };
12787
12788        let mut supports = false;
12789        self.buffer().read(cx).for_each_buffer(|buffer| {
12790            supports |= provider.supports_inlay_hints(buffer, cx);
12791        });
12792        supports
12793    }
12794
12795    pub fn focus(&self, cx: &mut WindowContext) {
12796        cx.focus(&self.focus_handle)
12797    }
12798
12799    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12800        self.focus_handle.is_focused(cx)
12801    }
12802
12803    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12804        cx.emit(EditorEvent::Focused);
12805
12806        if let Some(descendant) = self
12807            .last_focused_descendant
12808            .take()
12809            .and_then(|descendant| descendant.upgrade())
12810        {
12811            cx.focus(&descendant);
12812        } else {
12813            if let Some(blame) = self.blame.as_ref() {
12814                blame.update(cx, GitBlame::focus)
12815            }
12816
12817            self.blink_manager.update(cx, BlinkManager::enable);
12818            self.show_cursor_names(cx);
12819            self.buffer.update(cx, |buffer, cx| {
12820                buffer.finalize_last_transaction(cx);
12821                if self.leader_peer_id.is_none() {
12822                    buffer.set_active_selections(
12823                        &self.selections.disjoint_anchors(),
12824                        self.selections.line_mode,
12825                        self.cursor_shape,
12826                        cx,
12827                    );
12828                }
12829            });
12830        }
12831    }
12832
12833    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12834        cx.emit(EditorEvent::FocusedIn)
12835    }
12836
12837    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12838        if event.blurred != self.focus_handle {
12839            self.last_focused_descendant = Some(event.blurred);
12840        }
12841    }
12842
12843    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12844        self.blink_manager.update(cx, BlinkManager::disable);
12845        self.buffer
12846            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12847
12848        if let Some(blame) = self.blame.as_ref() {
12849            blame.update(cx, GitBlame::blur)
12850        }
12851        if !self.hover_state.focused(cx) {
12852            hide_hover(self, cx);
12853        }
12854
12855        self.hide_context_menu(cx);
12856        cx.emit(EditorEvent::Blurred);
12857        cx.notify();
12858    }
12859
12860    pub fn register_action<A: Action>(
12861        &mut self,
12862        listener: impl Fn(&A, &mut WindowContext) + 'static,
12863    ) -> Subscription {
12864        let id = self.next_editor_action_id.post_inc();
12865        let listener = Arc::new(listener);
12866        self.editor_actions.borrow_mut().insert(
12867            id,
12868            Box::new(move |cx| {
12869                let cx = cx.window_context();
12870                let listener = listener.clone();
12871                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12872                    let action = action.downcast_ref().unwrap();
12873                    if phase == DispatchPhase::Bubble {
12874                        listener(action, cx)
12875                    }
12876                })
12877            }),
12878        );
12879
12880        let editor_actions = self.editor_actions.clone();
12881        Subscription::new(move || {
12882            editor_actions.borrow_mut().remove(&id);
12883        })
12884    }
12885
12886    pub fn file_header_size(&self) -> u32 {
12887        FILE_HEADER_HEIGHT
12888    }
12889
12890    pub fn revert(
12891        &mut self,
12892        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12893        cx: &mut ViewContext<Self>,
12894    ) {
12895        self.buffer().update(cx, |multi_buffer, cx| {
12896            for (buffer_id, changes) in revert_changes {
12897                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12898                    buffer.update(cx, |buffer, cx| {
12899                        buffer.edit(
12900                            changes.into_iter().map(|(range, text)| {
12901                                (range, text.to_string().map(Arc::<str>::from))
12902                            }),
12903                            None,
12904                            cx,
12905                        );
12906                    });
12907                }
12908            }
12909        });
12910        self.change_selections(None, cx, |selections| selections.refresh());
12911    }
12912
12913    pub fn to_pixel_point(
12914        &mut self,
12915        source: multi_buffer::Anchor,
12916        editor_snapshot: &EditorSnapshot,
12917        cx: &mut ViewContext<Self>,
12918    ) -> Option<gpui::Point<Pixels>> {
12919        let source_point = source.to_display_point(editor_snapshot);
12920        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12921    }
12922
12923    pub fn display_to_pixel_point(
12924        &self,
12925        source: DisplayPoint,
12926        editor_snapshot: &EditorSnapshot,
12927        cx: &WindowContext,
12928    ) -> Option<gpui::Point<Pixels>> {
12929        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12930        let text_layout_details = self.text_layout_details(cx);
12931        let scroll_top = text_layout_details
12932            .scroll_anchor
12933            .scroll_position(editor_snapshot)
12934            .y;
12935
12936        if source.row().as_f32() < scroll_top.floor() {
12937            return None;
12938        }
12939        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12940        let source_y = line_height * (source.row().as_f32() - scroll_top);
12941        Some(gpui::Point::new(source_x, source_y))
12942    }
12943
12944    pub fn has_active_completions_menu(&self) -> bool {
12945        self.context_menu.borrow().as_ref().map_or(false, |menu| {
12946            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12947        })
12948    }
12949
12950    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12951        self.addons
12952            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12953    }
12954
12955    pub fn unregister_addon<T: Addon>(&mut self) {
12956        self.addons.remove(&std::any::TypeId::of::<T>());
12957    }
12958
12959    pub fn addon<T: Addon>(&self) -> Option<&T> {
12960        let type_id = std::any::TypeId::of::<T>();
12961        self.addons
12962            .get(&type_id)
12963            .and_then(|item| item.to_any().downcast_ref::<T>())
12964    }
12965
12966    pub fn add_change_set(
12967        &mut self,
12968        change_set: Model<BufferChangeSet>,
12969        cx: &mut ViewContext<Self>,
12970    ) {
12971        self.diff_map.add_change_set(change_set, cx);
12972    }
12973
12974    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12975        let text_layout_details = self.text_layout_details(cx);
12976        let style = &text_layout_details.editor_style;
12977        let font_id = cx.text_system().resolve_font(&style.text.font());
12978        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12979        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12980
12981        let em_width = cx
12982            .text_system()
12983            .typographic_bounds(font_id, font_size, 'm')
12984            .unwrap()
12985            .size
12986            .width;
12987
12988        gpui::Point::new(em_width, line_height)
12989    }
12990}
12991
12992fn get_unstaged_changes_for_buffers(
12993    project: &Model<Project>,
12994    buffers: impl IntoIterator<Item = Model<Buffer>>,
12995    cx: &mut ViewContext<Editor>,
12996) {
12997    let mut tasks = Vec::new();
12998    project.update(cx, |project, cx| {
12999        for buffer in buffers {
13000            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13001        }
13002    });
13003    cx.spawn(|this, mut cx| async move {
13004        let change_sets = futures::future::join_all(tasks).await;
13005        this.update(&mut cx, |this, cx| {
13006            for change_set in change_sets {
13007                if let Some(change_set) = change_set.log_err() {
13008                    this.diff_map.add_change_set(change_set, cx);
13009                }
13010            }
13011        })
13012        .ok();
13013    })
13014    .detach();
13015}
13016
13017fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13018    let tab_size = tab_size.get() as usize;
13019    let mut width = offset;
13020
13021    for ch in text.chars() {
13022        width += if ch == '\t' {
13023            tab_size - (width % tab_size)
13024        } else {
13025            1
13026        };
13027    }
13028
13029    width - offset
13030}
13031
13032#[cfg(test)]
13033mod tests {
13034    use super::*;
13035
13036    #[test]
13037    fn test_string_size_with_expanded_tabs() {
13038        let nz = |val| NonZeroU32::new(val).unwrap();
13039        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13040        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13041        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13042        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13043        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13044        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13045        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13046        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13047    }
13048}
13049
13050/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13051struct WordBreakingTokenizer<'a> {
13052    input: &'a str,
13053}
13054
13055impl<'a> WordBreakingTokenizer<'a> {
13056    fn new(input: &'a str) -> Self {
13057        Self { input }
13058    }
13059}
13060
13061fn is_char_ideographic(ch: char) -> bool {
13062    use unicode_script::Script::*;
13063    use unicode_script::UnicodeScript;
13064    matches!(ch.script(), Han | Tangut | Yi)
13065}
13066
13067fn is_grapheme_ideographic(text: &str) -> bool {
13068    text.chars().any(is_char_ideographic)
13069}
13070
13071fn is_grapheme_whitespace(text: &str) -> bool {
13072    text.chars().any(|x| x.is_whitespace())
13073}
13074
13075fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13076    text.chars().next().map_or(false, |ch| {
13077        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13078    })
13079}
13080
13081#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13082struct WordBreakToken<'a> {
13083    token: &'a str,
13084    grapheme_len: usize,
13085    is_whitespace: bool,
13086}
13087
13088impl<'a> Iterator for WordBreakingTokenizer<'a> {
13089    /// Yields a span, the count of graphemes in the token, and whether it was
13090    /// whitespace. Note that it also breaks at word boundaries.
13091    type Item = WordBreakToken<'a>;
13092
13093    fn next(&mut self) -> Option<Self::Item> {
13094        use unicode_segmentation::UnicodeSegmentation;
13095        if self.input.is_empty() {
13096            return None;
13097        }
13098
13099        let mut iter = self.input.graphemes(true).peekable();
13100        let mut offset = 0;
13101        let mut graphemes = 0;
13102        if let Some(first_grapheme) = iter.next() {
13103            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13104            offset += first_grapheme.len();
13105            graphemes += 1;
13106            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13107                if let Some(grapheme) = iter.peek().copied() {
13108                    if should_stay_with_preceding_ideograph(grapheme) {
13109                        offset += grapheme.len();
13110                        graphemes += 1;
13111                    }
13112                }
13113            } else {
13114                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13115                let mut next_word_bound = words.peek().copied();
13116                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13117                    next_word_bound = words.next();
13118                }
13119                while let Some(grapheme) = iter.peek().copied() {
13120                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13121                        break;
13122                    };
13123                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13124                        break;
13125                    };
13126                    offset += grapheme.len();
13127                    graphemes += 1;
13128                    iter.next();
13129                }
13130            }
13131            let token = &self.input[..offset];
13132            self.input = &self.input[offset..];
13133            if is_whitespace {
13134                Some(WordBreakToken {
13135                    token: " ",
13136                    grapheme_len: 1,
13137                    is_whitespace: true,
13138                })
13139            } else {
13140                Some(WordBreakToken {
13141                    token,
13142                    grapheme_len: graphemes,
13143                    is_whitespace: false,
13144                })
13145            }
13146        } else {
13147            None
13148        }
13149    }
13150}
13151
13152#[test]
13153fn test_word_breaking_tokenizer() {
13154    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13155        ("", &[]),
13156        ("  ", &[(" ", 1, true)]),
13157        ("Ʒ", &[("Ʒ", 1, false)]),
13158        ("Ǽ", &[("Ǽ", 1, false)]),
13159        ("", &[("", 1, false)]),
13160        ("⋑⋑", &[("⋑⋑", 2, false)]),
13161        (
13162            "原理,进而",
13163            &[
13164                ("", 1, false),
13165                ("理,", 2, false),
13166                ("", 1, false),
13167                ("", 1, false),
13168            ],
13169        ),
13170        (
13171            "hello world",
13172            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13173        ),
13174        (
13175            "hello, world",
13176            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13177        ),
13178        (
13179            "  hello world",
13180            &[
13181                (" ", 1, true),
13182                ("hello", 5, false),
13183                (" ", 1, true),
13184                ("world", 5, false),
13185            ],
13186        ),
13187        (
13188            "这是什么 \n 钢笔",
13189            &[
13190                ("", 1, false),
13191                ("", 1, false),
13192                ("", 1, false),
13193                ("", 1, false),
13194                (" ", 1, true),
13195                ("", 1, false),
13196                ("", 1, false),
13197            ],
13198        ),
13199        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13200    ];
13201
13202    for (input, result) in tests {
13203        assert_eq!(
13204            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13205            result
13206                .iter()
13207                .copied()
13208                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13209                    token,
13210                    grapheme_len,
13211                    is_whitespace,
13212                })
13213                .collect::<Vec<_>>()
13214        );
13215    }
13216}
13217
13218fn wrap_with_prefix(
13219    line_prefix: String,
13220    unwrapped_text: String,
13221    wrap_column: usize,
13222    tab_size: NonZeroU32,
13223) -> String {
13224    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13225    let mut wrapped_text = String::new();
13226    let mut current_line = line_prefix.clone();
13227
13228    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13229    let mut current_line_len = line_prefix_len;
13230    for WordBreakToken {
13231        token,
13232        grapheme_len,
13233        is_whitespace,
13234    } in tokenizer
13235    {
13236        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13237            wrapped_text.push_str(current_line.trim_end());
13238            wrapped_text.push('\n');
13239            current_line.truncate(line_prefix.len());
13240            current_line_len = line_prefix_len;
13241            if !is_whitespace {
13242                current_line.push_str(token);
13243                current_line_len += grapheme_len;
13244            }
13245        } else if !is_whitespace {
13246            current_line.push_str(token);
13247            current_line_len += grapheme_len;
13248        } else if current_line_len != line_prefix_len {
13249            current_line.push(' ');
13250            current_line_len += 1;
13251        }
13252    }
13253
13254    if !current_line.is_empty() {
13255        wrapped_text.push_str(&current_line);
13256    }
13257    wrapped_text
13258}
13259
13260#[test]
13261fn test_wrap_with_prefix() {
13262    assert_eq!(
13263        wrap_with_prefix(
13264            "# ".to_string(),
13265            "abcdefg".to_string(),
13266            4,
13267            NonZeroU32::new(4).unwrap()
13268        ),
13269        "# abcdefg"
13270    );
13271    assert_eq!(
13272        wrap_with_prefix(
13273            "".to_string(),
13274            "\thello world".to_string(),
13275            8,
13276            NonZeroU32::new(4).unwrap()
13277        ),
13278        "hello\nworld"
13279    );
13280    assert_eq!(
13281        wrap_with_prefix(
13282            "// ".to_string(),
13283            "xx \nyy zz aa bb cc".to_string(),
13284            12,
13285            NonZeroU32::new(4).unwrap()
13286        ),
13287        "// xx yy zz\n// aa bb cc"
13288    );
13289    assert_eq!(
13290        wrap_with_prefix(
13291            String::new(),
13292            "这是什么 \n 钢笔".to_string(),
13293            3,
13294            NonZeroU32::new(4).unwrap()
13295        ),
13296        "这是什\n么 钢\n"
13297    );
13298}
13299
13300fn hunks_for_selections(
13301    snapshot: &EditorSnapshot,
13302    selections: &[Selection<Point>],
13303) -> Vec<MultiBufferDiffHunk> {
13304    hunks_for_ranges(
13305        selections.iter().map(|selection| selection.range()),
13306        snapshot,
13307    )
13308}
13309
13310pub fn hunks_for_ranges(
13311    ranges: impl Iterator<Item = Range<Point>>,
13312    snapshot: &EditorSnapshot,
13313) -> Vec<MultiBufferDiffHunk> {
13314    let mut hunks = Vec::new();
13315    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13316        HashMap::default();
13317    for query_range in ranges {
13318        let query_rows =
13319            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13320        for hunk in snapshot.diff_map.diff_hunks_in_range(
13321            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13322            &snapshot.buffer_snapshot,
13323        ) {
13324            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13325            // when the caret is just above or just below the deleted hunk.
13326            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13327            let related_to_selection = if allow_adjacent {
13328                hunk.row_range.overlaps(&query_rows)
13329                    || hunk.row_range.start == query_rows.end
13330                    || hunk.row_range.end == query_rows.start
13331            } else {
13332                hunk.row_range.overlaps(&query_rows)
13333            };
13334            if related_to_selection {
13335                if !processed_buffer_rows
13336                    .entry(hunk.buffer_id)
13337                    .or_default()
13338                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13339                {
13340                    continue;
13341                }
13342                hunks.push(hunk);
13343            }
13344        }
13345    }
13346
13347    hunks
13348}
13349
13350pub trait CollaborationHub {
13351    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13352    fn user_participant_indices<'a>(
13353        &self,
13354        cx: &'a AppContext,
13355    ) -> &'a HashMap<u64, ParticipantIndex>;
13356    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13357}
13358
13359impl CollaborationHub for Model<Project> {
13360    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13361        self.read(cx).collaborators()
13362    }
13363
13364    fn user_participant_indices<'a>(
13365        &self,
13366        cx: &'a AppContext,
13367    ) -> &'a HashMap<u64, ParticipantIndex> {
13368        self.read(cx).user_store().read(cx).participant_indices()
13369    }
13370
13371    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13372        let this = self.read(cx);
13373        let user_ids = this.collaborators().values().map(|c| c.user_id);
13374        this.user_store().read_with(cx, |user_store, cx| {
13375            user_store.participant_names(user_ids, cx)
13376        })
13377    }
13378}
13379
13380pub trait SemanticsProvider {
13381    fn hover(
13382        &self,
13383        buffer: &Model<Buffer>,
13384        position: text::Anchor,
13385        cx: &mut AppContext,
13386    ) -> Option<Task<Vec<project::Hover>>>;
13387
13388    fn inlay_hints(
13389        &self,
13390        buffer_handle: Model<Buffer>,
13391        range: Range<text::Anchor>,
13392        cx: &mut AppContext,
13393    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13394
13395    fn resolve_inlay_hint(
13396        &self,
13397        hint: InlayHint,
13398        buffer_handle: Model<Buffer>,
13399        server_id: LanguageServerId,
13400        cx: &mut AppContext,
13401    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13402
13403    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13404
13405    fn document_highlights(
13406        &self,
13407        buffer: &Model<Buffer>,
13408        position: text::Anchor,
13409        cx: &mut AppContext,
13410    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13411
13412    fn definitions(
13413        &self,
13414        buffer: &Model<Buffer>,
13415        position: text::Anchor,
13416        kind: GotoDefinitionKind,
13417        cx: &mut AppContext,
13418    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13419
13420    fn range_for_rename(
13421        &self,
13422        buffer: &Model<Buffer>,
13423        position: text::Anchor,
13424        cx: &mut AppContext,
13425    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13426
13427    fn perform_rename(
13428        &self,
13429        buffer: &Model<Buffer>,
13430        position: text::Anchor,
13431        new_name: String,
13432        cx: &mut AppContext,
13433    ) -> Option<Task<Result<ProjectTransaction>>>;
13434}
13435
13436pub trait CompletionProvider {
13437    fn completions(
13438        &self,
13439        buffer: &Model<Buffer>,
13440        buffer_position: text::Anchor,
13441        trigger: CompletionContext,
13442        cx: &mut ViewContext<Editor>,
13443    ) -> Task<Result<Vec<Completion>>>;
13444
13445    fn resolve_completions(
13446        &self,
13447        buffer: Model<Buffer>,
13448        completion_indices: Vec<usize>,
13449        completions: Rc<RefCell<Box<[Completion]>>>,
13450        cx: &mut ViewContext<Editor>,
13451    ) -> Task<Result<bool>>;
13452
13453    fn apply_additional_edits_for_completion(
13454        &self,
13455        _buffer: Model<Buffer>,
13456        _completions: Rc<RefCell<Box<[Completion]>>>,
13457        _completion_index: usize,
13458        _push_to_history: bool,
13459        _cx: &mut ViewContext<Editor>,
13460    ) -> Task<Result<Option<language::Transaction>>> {
13461        Task::ready(Ok(None))
13462    }
13463
13464    fn is_completion_trigger(
13465        &self,
13466        buffer: &Model<Buffer>,
13467        position: language::Anchor,
13468        text: &str,
13469        trigger_in_words: bool,
13470        cx: &mut ViewContext<Editor>,
13471    ) -> bool;
13472
13473    fn sort_completions(&self) -> bool {
13474        true
13475    }
13476}
13477
13478pub trait CodeActionProvider {
13479    fn code_actions(
13480        &self,
13481        buffer: &Model<Buffer>,
13482        range: Range<text::Anchor>,
13483        cx: &mut WindowContext,
13484    ) -> Task<Result<Vec<CodeAction>>>;
13485
13486    fn apply_code_action(
13487        &self,
13488        buffer_handle: Model<Buffer>,
13489        action: CodeAction,
13490        excerpt_id: ExcerptId,
13491        push_to_history: bool,
13492        cx: &mut WindowContext,
13493    ) -> Task<Result<ProjectTransaction>>;
13494}
13495
13496impl CodeActionProvider for Model<Project> {
13497    fn code_actions(
13498        &self,
13499        buffer: &Model<Buffer>,
13500        range: Range<text::Anchor>,
13501        cx: &mut WindowContext,
13502    ) -> Task<Result<Vec<CodeAction>>> {
13503        self.update(cx, |project, cx| {
13504            project.code_actions(buffer, range, None, cx)
13505        })
13506    }
13507
13508    fn apply_code_action(
13509        &self,
13510        buffer_handle: Model<Buffer>,
13511        action: CodeAction,
13512        _excerpt_id: ExcerptId,
13513        push_to_history: bool,
13514        cx: &mut WindowContext,
13515    ) -> Task<Result<ProjectTransaction>> {
13516        self.update(cx, |project, cx| {
13517            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13518        })
13519    }
13520}
13521
13522fn snippet_completions(
13523    project: &Project,
13524    buffer: &Model<Buffer>,
13525    buffer_position: text::Anchor,
13526    cx: &mut AppContext,
13527) -> Task<Result<Vec<Completion>>> {
13528    let language = buffer.read(cx).language_at(buffer_position);
13529    let language_name = language.as_ref().map(|language| language.lsp_id());
13530    let snippet_store = project.snippets().read(cx);
13531    let snippets = snippet_store.snippets_for(language_name, cx);
13532
13533    if snippets.is_empty() {
13534        return Task::ready(Ok(vec![]));
13535    }
13536    let snapshot = buffer.read(cx).text_snapshot();
13537    let chars: String = snapshot
13538        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13539        .collect();
13540
13541    let scope = language.map(|language| language.default_scope());
13542    let executor = cx.background_executor().clone();
13543
13544    cx.background_executor().spawn(async move {
13545        let classifier = CharClassifier::new(scope).for_completion(true);
13546        let mut last_word = chars
13547            .chars()
13548            .take_while(|c| classifier.is_word(*c))
13549            .collect::<String>();
13550        last_word = last_word.chars().rev().collect();
13551
13552        if last_word.is_empty() {
13553            return Ok(vec![]);
13554        }
13555
13556        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13557        let to_lsp = |point: &text::Anchor| {
13558            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13559            point_to_lsp(end)
13560        };
13561        let lsp_end = to_lsp(&buffer_position);
13562
13563        let candidates = snippets
13564            .iter()
13565            .enumerate()
13566            .flat_map(|(ix, snippet)| {
13567                snippet
13568                    .prefix
13569                    .iter()
13570                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13571            })
13572            .collect::<Vec<StringMatchCandidate>>();
13573
13574        let mut matches = fuzzy::match_strings(
13575            &candidates,
13576            &last_word,
13577            last_word.chars().any(|c| c.is_uppercase()),
13578            100,
13579            &Default::default(),
13580            executor,
13581        )
13582        .await;
13583
13584        // Remove all candidates where the query's start does not match the start of any word in the candidate
13585        if let Some(query_start) = last_word.chars().next() {
13586            matches.retain(|string_match| {
13587                split_words(&string_match.string).any(|word| {
13588                    // Check that the first codepoint of the word as lowercase matches the first
13589                    // codepoint of the query as lowercase
13590                    word.chars()
13591                        .flat_map(|codepoint| codepoint.to_lowercase())
13592                        .zip(query_start.to_lowercase())
13593                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13594                })
13595            });
13596        }
13597
13598        let matched_strings = matches
13599            .into_iter()
13600            .map(|m| m.string)
13601            .collect::<HashSet<_>>();
13602
13603        let result: Vec<Completion> = snippets
13604            .into_iter()
13605            .filter_map(|snippet| {
13606                let matching_prefix = snippet
13607                    .prefix
13608                    .iter()
13609                    .find(|prefix| matched_strings.contains(*prefix))?;
13610                let start = as_offset - last_word.len();
13611                let start = snapshot.anchor_before(start);
13612                let range = start..buffer_position;
13613                let lsp_start = to_lsp(&start);
13614                let lsp_range = lsp::Range {
13615                    start: lsp_start,
13616                    end: lsp_end,
13617                };
13618                Some(Completion {
13619                    old_range: range,
13620                    new_text: snippet.body.clone(),
13621                    resolved: false,
13622                    label: CodeLabel {
13623                        text: matching_prefix.clone(),
13624                        runs: vec![],
13625                        filter_range: 0..matching_prefix.len(),
13626                    },
13627                    server_id: LanguageServerId(usize::MAX),
13628                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13629                    lsp_completion: lsp::CompletionItem {
13630                        label: snippet.prefix.first().unwrap().clone(),
13631                        kind: Some(CompletionItemKind::SNIPPET),
13632                        label_details: snippet.description.as_ref().map(|description| {
13633                            lsp::CompletionItemLabelDetails {
13634                                detail: Some(description.clone()),
13635                                description: None,
13636                            }
13637                        }),
13638                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13639                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13640                            lsp::InsertReplaceEdit {
13641                                new_text: snippet.body.clone(),
13642                                insert: lsp_range,
13643                                replace: lsp_range,
13644                            },
13645                        )),
13646                        filter_text: Some(snippet.body.clone()),
13647                        sort_text: Some(char::MAX.to_string()),
13648                        ..Default::default()
13649                    },
13650                    confirm: None,
13651                })
13652            })
13653            .collect();
13654
13655        Ok(result)
13656    })
13657}
13658
13659impl CompletionProvider for Model<Project> {
13660    fn completions(
13661        &self,
13662        buffer: &Model<Buffer>,
13663        buffer_position: text::Anchor,
13664        options: CompletionContext,
13665        cx: &mut ViewContext<Editor>,
13666    ) -> Task<Result<Vec<Completion>>> {
13667        self.update(cx, |project, cx| {
13668            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13669            let project_completions = project.completions(buffer, buffer_position, options, cx);
13670            cx.background_executor().spawn(async move {
13671                let mut completions = project_completions.await?;
13672                let snippets_completions = snippets.await?;
13673                completions.extend(snippets_completions);
13674                Ok(completions)
13675            })
13676        })
13677    }
13678
13679    fn resolve_completions(
13680        &self,
13681        buffer: Model<Buffer>,
13682        completion_indices: Vec<usize>,
13683        completions: Rc<RefCell<Box<[Completion]>>>,
13684        cx: &mut ViewContext<Editor>,
13685    ) -> Task<Result<bool>> {
13686        self.update(cx, |project, cx| {
13687            project.lsp_store().update(cx, |lsp_store, cx| {
13688                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13689            })
13690        })
13691    }
13692
13693    fn apply_additional_edits_for_completion(
13694        &self,
13695        buffer: Model<Buffer>,
13696        completions: Rc<RefCell<Box<[Completion]>>>,
13697        completion_index: usize,
13698        push_to_history: bool,
13699        cx: &mut ViewContext<Editor>,
13700    ) -> Task<Result<Option<language::Transaction>>> {
13701        self.update(cx, |project, cx| {
13702            project.lsp_store().update(cx, |lsp_store, cx| {
13703                lsp_store.apply_additional_edits_for_completion(
13704                    buffer,
13705                    completions,
13706                    completion_index,
13707                    push_to_history,
13708                    cx,
13709                )
13710            })
13711        })
13712    }
13713
13714    fn is_completion_trigger(
13715        &self,
13716        buffer: &Model<Buffer>,
13717        position: language::Anchor,
13718        text: &str,
13719        trigger_in_words: bool,
13720        cx: &mut ViewContext<Editor>,
13721    ) -> bool {
13722        let mut chars = text.chars();
13723        let char = if let Some(char) = chars.next() {
13724            char
13725        } else {
13726            return false;
13727        };
13728        if chars.next().is_some() {
13729            return false;
13730        }
13731
13732        let buffer = buffer.read(cx);
13733        let snapshot = buffer.snapshot();
13734        if !snapshot.settings_at(position, cx).show_completions_on_input {
13735            return false;
13736        }
13737        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13738        if trigger_in_words && classifier.is_word(char) {
13739            return true;
13740        }
13741
13742        buffer.completion_triggers().contains(text)
13743    }
13744}
13745
13746impl SemanticsProvider for Model<Project> {
13747    fn hover(
13748        &self,
13749        buffer: &Model<Buffer>,
13750        position: text::Anchor,
13751        cx: &mut AppContext,
13752    ) -> Option<Task<Vec<project::Hover>>> {
13753        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13754    }
13755
13756    fn document_highlights(
13757        &self,
13758        buffer: &Model<Buffer>,
13759        position: text::Anchor,
13760        cx: &mut AppContext,
13761    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13762        Some(self.update(cx, |project, cx| {
13763            project.document_highlights(buffer, position, cx)
13764        }))
13765    }
13766
13767    fn definitions(
13768        &self,
13769        buffer: &Model<Buffer>,
13770        position: text::Anchor,
13771        kind: GotoDefinitionKind,
13772        cx: &mut AppContext,
13773    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13774        Some(self.update(cx, |project, cx| match kind {
13775            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13776            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13777            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13778            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13779        }))
13780    }
13781
13782    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13783        // TODO: make this work for remote projects
13784        self.read(cx)
13785            .language_servers_for_local_buffer(buffer.read(cx), cx)
13786            .any(
13787                |(_, server)| match server.capabilities().inlay_hint_provider {
13788                    Some(lsp::OneOf::Left(enabled)) => enabled,
13789                    Some(lsp::OneOf::Right(_)) => true,
13790                    None => false,
13791                },
13792            )
13793    }
13794
13795    fn inlay_hints(
13796        &self,
13797        buffer_handle: Model<Buffer>,
13798        range: Range<text::Anchor>,
13799        cx: &mut AppContext,
13800    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13801        Some(self.update(cx, |project, cx| {
13802            project.inlay_hints(buffer_handle, range, cx)
13803        }))
13804    }
13805
13806    fn resolve_inlay_hint(
13807        &self,
13808        hint: InlayHint,
13809        buffer_handle: Model<Buffer>,
13810        server_id: LanguageServerId,
13811        cx: &mut AppContext,
13812    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13813        Some(self.update(cx, |project, cx| {
13814            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13815        }))
13816    }
13817
13818    fn range_for_rename(
13819        &self,
13820        buffer: &Model<Buffer>,
13821        position: text::Anchor,
13822        cx: &mut AppContext,
13823    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13824        Some(self.update(cx, |project, cx| {
13825            project.prepare_rename(buffer.clone(), position, cx)
13826        }))
13827    }
13828
13829    fn perform_rename(
13830        &self,
13831        buffer: &Model<Buffer>,
13832        position: text::Anchor,
13833        new_name: String,
13834        cx: &mut AppContext,
13835    ) -> Option<Task<Result<ProjectTransaction>>> {
13836        Some(self.update(cx, |project, cx| {
13837            project.perform_rename(buffer.clone(), position, new_name, cx)
13838        }))
13839    }
13840}
13841
13842fn inlay_hint_settings(
13843    location: Anchor,
13844    snapshot: &MultiBufferSnapshot,
13845    cx: &mut ViewContext<'_, Editor>,
13846) -> InlayHintSettings {
13847    let file = snapshot.file_at(location);
13848    let language = snapshot.language_at(location).map(|l| l.name());
13849    language_settings(language, file, cx).inlay_hints
13850}
13851
13852fn consume_contiguous_rows(
13853    contiguous_row_selections: &mut Vec<Selection<Point>>,
13854    selection: &Selection<Point>,
13855    display_map: &DisplaySnapshot,
13856    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13857) -> (MultiBufferRow, MultiBufferRow) {
13858    contiguous_row_selections.push(selection.clone());
13859    let start_row = MultiBufferRow(selection.start.row);
13860    let mut end_row = ending_row(selection, display_map);
13861
13862    while let Some(next_selection) = selections.peek() {
13863        if next_selection.start.row <= end_row.0 {
13864            end_row = ending_row(next_selection, display_map);
13865            contiguous_row_selections.push(selections.next().unwrap().clone());
13866        } else {
13867            break;
13868        }
13869    }
13870    (start_row, end_row)
13871}
13872
13873fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13874    if next_selection.end.column > 0 || next_selection.is_empty() {
13875        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13876    } else {
13877        MultiBufferRow(next_selection.end.row)
13878    }
13879}
13880
13881impl EditorSnapshot {
13882    pub fn remote_selections_in_range<'a>(
13883        &'a self,
13884        range: &'a Range<Anchor>,
13885        collaboration_hub: &dyn CollaborationHub,
13886        cx: &'a AppContext,
13887    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13888        let participant_names = collaboration_hub.user_names(cx);
13889        let participant_indices = collaboration_hub.user_participant_indices(cx);
13890        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13891        let collaborators_by_replica_id = collaborators_by_peer_id
13892            .iter()
13893            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13894            .collect::<HashMap<_, _>>();
13895        self.buffer_snapshot
13896            .selections_in_range(range, false)
13897            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13898                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13899                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13900                let user_name = participant_names.get(&collaborator.user_id).cloned();
13901                Some(RemoteSelection {
13902                    replica_id,
13903                    selection,
13904                    cursor_shape,
13905                    line_mode,
13906                    participant_index,
13907                    peer_id: collaborator.peer_id,
13908                    user_name,
13909                })
13910            })
13911    }
13912
13913    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13914        self.display_snapshot.buffer_snapshot.language_at(position)
13915    }
13916
13917    pub fn is_focused(&self) -> bool {
13918        self.is_focused
13919    }
13920
13921    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13922        self.placeholder_text.as_ref()
13923    }
13924
13925    pub fn scroll_position(&self) -> gpui::Point<f32> {
13926        self.scroll_anchor.scroll_position(&self.display_snapshot)
13927    }
13928
13929    fn gutter_dimensions(
13930        &self,
13931        font_id: FontId,
13932        font_size: Pixels,
13933        em_width: Pixels,
13934        em_advance: Pixels,
13935        max_line_number_width: Pixels,
13936        cx: &AppContext,
13937    ) -> GutterDimensions {
13938        if !self.show_gutter {
13939            return GutterDimensions::default();
13940        }
13941        let descent = cx.text_system().descent(font_id, font_size);
13942
13943        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13944            matches!(
13945                ProjectSettings::get_global(cx).git.git_gutter,
13946                Some(GitGutterSetting::TrackedFiles)
13947            )
13948        });
13949        let gutter_settings = EditorSettings::get_global(cx).gutter;
13950        let show_line_numbers = self
13951            .show_line_numbers
13952            .unwrap_or(gutter_settings.line_numbers);
13953        let line_gutter_width = if show_line_numbers {
13954            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13955            let min_width_for_number_on_gutter = em_advance * 4.0;
13956            max_line_number_width.max(min_width_for_number_on_gutter)
13957        } else {
13958            0.0.into()
13959        };
13960
13961        let show_code_actions = self
13962            .show_code_actions
13963            .unwrap_or(gutter_settings.code_actions);
13964
13965        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13966
13967        let git_blame_entries_width =
13968            self.git_blame_gutter_max_author_length
13969                .map(|max_author_length| {
13970                    // Length of the author name, but also space for the commit hash,
13971                    // the spacing and the timestamp.
13972                    let max_char_count = max_author_length
13973                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13974                        + 7 // length of commit sha
13975                        + 14 // length of max relative timestamp ("60 minutes ago")
13976                        + 4; // gaps and margins
13977
13978                    em_advance * max_char_count
13979                });
13980
13981        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13982        left_padding += if show_code_actions || show_runnables {
13983            em_width * 3.0
13984        } else if show_git_gutter && show_line_numbers {
13985            em_width * 2.0
13986        } else if show_git_gutter || show_line_numbers {
13987            em_width
13988        } else {
13989            px(0.)
13990        };
13991
13992        let right_padding = if gutter_settings.folds && show_line_numbers {
13993            em_width * 4.0
13994        } else if gutter_settings.folds {
13995            em_width * 3.0
13996        } else if show_line_numbers {
13997            em_width
13998        } else {
13999            px(0.)
14000        };
14001
14002        GutterDimensions {
14003            left_padding,
14004            right_padding,
14005            width: line_gutter_width + left_padding + right_padding,
14006            margin: -descent,
14007            git_blame_entries_width,
14008        }
14009    }
14010
14011    pub fn render_crease_toggle(
14012        &self,
14013        buffer_row: MultiBufferRow,
14014        row_contains_cursor: bool,
14015        editor: View<Editor>,
14016        cx: &mut WindowContext,
14017    ) -> Option<AnyElement> {
14018        let folded = self.is_line_folded(buffer_row);
14019        let mut is_foldable = false;
14020
14021        if let Some(crease) = self
14022            .crease_snapshot
14023            .query_row(buffer_row, &self.buffer_snapshot)
14024        {
14025            is_foldable = true;
14026            match crease {
14027                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14028                    if let Some(render_toggle) = render_toggle {
14029                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14030                            if folded {
14031                                editor.update(cx, |editor, cx| {
14032                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14033                                });
14034                            } else {
14035                                editor.update(cx, |editor, cx| {
14036                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14037                                });
14038                            }
14039                        });
14040                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14041                    }
14042                }
14043            }
14044        }
14045
14046        is_foldable |= self.starts_indent(buffer_row);
14047
14048        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14049            Some(
14050                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14051                    .toggle_state(folded)
14052                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14053                        if folded {
14054                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14055                        } else {
14056                            this.fold_at(&FoldAt { buffer_row }, cx);
14057                        }
14058                    }))
14059                    .into_any_element(),
14060            )
14061        } else {
14062            None
14063        }
14064    }
14065
14066    pub fn render_crease_trailer(
14067        &self,
14068        buffer_row: MultiBufferRow,
14069        cx: &mut WindowContext,
14070    ) -> Option<AnyElement> {
14071        let folded = self.is_line_folded(buffer_row);
14072        if let Crease::Inline { render_trailer, .. } = self
14073            .crease_snapshot
14074            .query_row(buffer_row, &self.buffer_snapshot)?
14075        {
14076            let render_trailer = render_trailer.as_ref()?;
14077            Some(render_trailer(buffer_row, folded, cx))
14078        } else {
14079            None
14080        }
14081    }
14082}
14083
14084impl Deref for EditorSnapshot {
14085    type Target = DisplaySnapshot;
14086
14087    fn deref(&self) -> &Self::Target {
14088        &self.display_snapshot
14089    }
14090}
14091
14092#[derive(Clone, Debug, PartialEq, Eq)]
14093pub enum EditorEvent {
14094    InputIgnored {
14095        text: Arc<str>,
14096    },
14097    InputHandled {
14098        utf16_range_to_replace: Option<Range<isize>>,
14099        text: Arc<str>,
14100    },
14101    ExcerptsAdded {
14102        buffer: Model<Buffer>,
14103        predecessor: ExcerptId,
14104        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14105    },
14106    ExcerptsRemoved {
14107        ids: Vec<ExcerptId>,
14108    },
14109    BufferFoldToggled {
14110        ids: Vec<ExcerptId>,
14111        folded: bool,
14112    },
14113    ExcerptsEdited {
14114        ids: Vec<ExcerptId>,
14115    },
14116    ExcerptsExpanded {
14117        ids: Vec<ExcerptId>,
14118    },
14119    BufferEdited,
14120    Edited {
14121        transaction_id: clock::Lamport,
14122    },
14123    Reparsed(BufferId),
14124    Focused,
14125    FocusedIn,
14126    Blurred,
14127    DirtyChanged,
14128    Saved,
14129    TitleChanged,
14130    DiffBaseChanged,
14131    SelectionsChanged {
14132        local: bool,
14133    },
14134    ScrollPositionChanged {
14135        local: bool,
14136        autoscroll: bool,
14137    },
14138    Closed,
14139    TransactionUndone {
14140        transaction_id: clock::Lamport,
14141    },
14142    TransactionBegun {
14143        transaction_id: clock::Lamport,
14144    },
14145    Reloaded,
14146    CursorShapeChanged,
14147}
14148
14149impl EventEmitter<EditorEvent> for Editor {}
14150
14151impl FocusableView for Editor {
14152    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14153        self.focus_handle.clone()
14154    }
14155}
14156
14157impl Render for Editor {
14158    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14159        let settings = ThemeSettings::get_global(cx);
14160
14161        let mut text_style = match self.mode {
14162            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14163                color: cx.theme().colors().editor_foreground,
14164                font_family: settings.ui_font.family.clone(),
14165                font_features: settings.ui_font.features.clone(),
14166                font_fallbacks: settings.ui_font.fallbacks.clone(),
14167                font_size: rems(0.875).into(),
14168                font_weight: settings.ui_font.weight,
14169                line_height: relative(settings.buffer_line_height.value()),
14170                ..Default::default()
14171            },
14172            EditorMode::Full => TextStyle {
14173                color: cx.theme().colors().editor_foreground,
14174                font_family: settings.buffer_font.family.clone(),
14175                font_features: settings.buffer_font.features.clone(),
14176                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14177                font_size: settings.buffer_font_size(cx).into(),
14178                font_weight: settings.buffer_font.weight,
14179                line_height: relative(settings.buffer_line_height.value()),
14180                ..Default::default()
14181            },
14182        };
14183        if let Some(text_style_refinement) = &self.text_style_refinement {
14184            text_style.refine(text_style_refinement)
14185        }
14186
14187        let background = match self.mode {
14188            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14189            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14190            EditorMode::Full => cx.theme().colors().editor_background,
14191        };
14192
14193        EditorElement::new(
14194            cx.view(),
14195            EditorStyle {
14196                background,
14197                local_player: cx.theme().players().local(),
14198                text: text_style,
14199                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14200                syntax: cx.theme().syntax().clone(),
14201                status: cx.theme().status().clone(),
14202                inlay_hints_style: make_inlay_hints_style(cx),
14203                inline_completion_styles: make_suggestion_styles(cx),
14204                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14205            },
14206        )
14207    }
14208}
14209
14210impl ViewInputHandler for Editor {
14211    fn text_for_range(
14212        &mut self,
14213        range_utf16: Range<usize>,
14214        adjusted_range: &mut Option<Range<usize>>,
14215        cx: &mut ViewContext<Self>,
14216    ) -> Option<String> {
14217        let snapshot = self.buffer.read(cx).read(cx);
14218        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14219        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14220        if (start.0..end.0) != range_utf16 {
14221            adjusted_range.replace(start.0..end.0);
14222        }
14223        Some(snapshot.text_for_range(start..end).collect())
14224    }
14225
14226    fn selected_text_range(
14227        &mut self,
14228        ignore_disabled_input: bool,
14229        cx: &mut ViewContext<Self>,
14230    ) -> Option<UTF16Selection> {
14231        // Prevent the IME menu from appearing when holding down an alphabetic key
14232        // while input is disabled.
14233        if !ignore_disabled_input && !self.input_enabled {
14234            return None;
14235        }
14236
14237        let selection = self.selections.newest::<OffsetUtf16>(cx);
14238        let range = selection.range();
14239
14240        Some(UTF16Selection {
14241            range: range.start.0..range.end.0,
14242            reversed: selection.reversed,
14243        })
14244    }
14245
14246    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14247        let snapshot = self.buffer.read(cx).read(cx);
14248        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14249        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14250    }
14251
14252    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14253        self.clear_highlights::<InputComposition>(cx);
14254        self.ime_transaction.take();
14255    }
14256
14257    fn replace_text_in_range(
14258        &mut self,
14259        range_utf16: Option<Range<usize>>,
14260        text: &str,
14261        cx: &mut ViewContext<Self>,
14262    ) {
14263        if !self.input_enabled {
14264            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14265            return;
14266        }
14267
14268        self.transact(cx, |this, cx| {
14269            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14270                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14271                Some(this.selection_replacement_ranges(range_utf16, cx))
14272            } else {
14273                this.marked_text_ranges(cx)
14274            };
14275
14276            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14277                let newest_selection_id = this.selections.newest_anchor().id;
14278                this.selections
14279                    .all::<OffsetUtf16>(cx)
14280                    .iter()
14281                    .zip(ranges_to_replace.iter())
14282                    .find_map(|(selection, range)| {
14283                        if selection.id == newest_selection_id {
14284                            Some(
14285                                (range.start.0 as isize - selection.head().0 as isize)
14286                                    ..(range.end.0 as isize - selection.head().0 as isize),
14287                            )
14288                        } else {
14289                            None
14290                        }
14291                    })
14292            });
14293
14294            cx.emit(EditorEvent::InputHandled {
14295                utf16_range_to_replace: range_to_replace,
14296                text: text.into(),
14297            });
14298
14299            if let Some(new_selected_ranges) = new_selected_ranges {
14300                this.change_selections(None, cx, |selections| {
14301                    selections.select_ranges(new_selected_ranges)
14302                });
14303                this.backspace(&Default::default(), cx);
14304            }
14305
14306            this.handle_input(text, cx);
14307        });
14308
14309        if let Some(transaction) = self.ime_transaction {
14310            self.buffer.update(cx, |buffer, cx| {
14311                buffer.group_until_transaction(transaction, cx);
14312            });
14313        }
14314
14315        self.unmark_text(cx);
14316    }
14317
14318    fn replace_and_mark_text_in_range(
14319        &mut self,
14320        range_utf16: Option<Range<usize>>,
14321        text: &str,
14322        new_selected_range_utf16: Option<Range<usize>>,
14323        cx: &mut ViewContext<Self>,
14324    ) {
14325        if !self.input_enabled {
14326            return;
14327        }
14328
14329        let transaction = self.transact(cx, |this, cx| {
14330            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14331                let snapshot = this.buffer.read(cx).read(cx);
14332                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14333                    for marked_range in &mut marked_ranges {
14334                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14335                        marked_range.start.0 += relative_range_utf16.start;
14336                        marked_range.start =
14337                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14338                        marked_range.end =
14339                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14340                    }
14341                }
14342                Some(marked_ranges)
14343            } else if let Some(range_utf16) = range_utf16 {
14344                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14345                Some(this.selection_replacement_ranges(range_utf16, cx))
14346            } else {
14347                None
14348            };
14349
14350            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14351                let newest_selection_id = this.selections.newest_anchor().id;
14352                this.selections
14353                    .all::<OffsetUtf16>(cx)
14354                    .iter()
14355                    .zip(ranges_to_replace.iter())
14356                    .find_map(|(selection, range)| {
14357                        if selection.id == newest_selection_id {
14358                            Some(
14359                                (range.start.0 as isize - selection.head().0 as isize)
14360                                    ..(range.end.0 as isize - selection.head().0 as isize),
14361                            )
14362                        } else {
14363                            None
14364                        }
14365                    })
14366            });
14367
14368            cx.emit(EditorEvent::InputHandled {
14369                utf16_range_to_replace: range_to_replace,
14370                text: text.into(),
14371            });
14372
14373            if let Some(ranges) = ranges_to_replace {
14374                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14375            }
14376
14377            let marked_ranges = {
14378                let snapshot = this.buffer.read(cx).read(cx);
14379                this.selections
14380                    .disjoint_anchors()
14381                    .iter()
14382                    .map(|selection| {
14383                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14384                    })
14385                    .collect::<Vec<_>>()
14386            };
14387
14388            if text.is_empty() {
14389                this.unmark_text(cx);
14390            } else {
14391                this.highlight_text::<InputComposition>(
14392                    marked_ranges.clone(),
14393                    HighlightStyle {
14394                        underline: Some(UnderlineStyle {
14395                            thickness: px(1.),
14396                            color: None,
14397                            wavy: false,
14398                        }),
14399                        ..Default::default()
14400                    },
14401                    cx,
14402                );
14403            }
14404
14405            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14406            let use_autoclose = this.use_autoclose;
14407            let use_auto_surround = this.use_auto_surround;
14408            this.set_use_autoclose(false);
14409            this.set_use_auto_surround(false);
14410            this.handle_input(text, cx);
14411            this.set_use_autoclose(use_autoclose);
14412            this.set_use_auto_surround(use_auto_surround);
14413
14414            if let Some(new_selected_range) = new_selected_range_utf16 {
14415                let snapshot = this.buffer.read(cx).read(cx);
14416                let new_selected_ranges = marked_ranges
14417                    .into_iter()
14418                    .map(|marked_range| {
14419                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14420                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14421                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14422                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14423                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14424                    })
14425                    .collect::<Vec<_>>();
14426
14427                drop(snapshot);
14428                this.change_selections(None, cx, |selections| {
14429                    selections.select_ranges(new_selected_ranges)
14430                });
14431            }
14432        });
14433
14434        self.ime_transaction = self.ime_transaction.or(transaction);
14435        if let Some(transaction) = self.ime_transaction {
14436            self.buffer.update(cx, |buffer, cx| {
14437                buffer.group_until_transaction(transaction, cx);
14438            });
14439        }
14440
14441        if self.text_highlights::<InputComposition>(cx).is_none() {
14442            self.ime_transaction.take();
14443        }
14444    }
14445
14446    fn bounds_for_range(
14447        &mut self,
14448        range_utf16: Range<usize>,
14449        element_bounds: gpui::Bounds<Pixels>,
14450        cx: &mut ViewContext<Self>,
14451    ) -> Option<gpui::Bounds<Pixels>> {
14452        let text_layout_details = self.text_layout_details(cx);
14453        let gpui::Point {
14454            x: em_width,
14455            y: line_height,
14456        } = self.character_size(cx);
14457
14458        let snapshot = self.snapshot(cx);
14459        let scroll_position = snapshot.scroll_position();
14460        let scroll_left = scroll_position.x * em_width;
14461
14462        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14463        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14464            + self.gutter_dimensions.width
14465            + self.gutter_dimensions.margin;
14466        let y = line_height * (start.row().as_f32() - scroll_position.y);
14467
14468        Some(Bounds {
14469            origin: element_bounds.origin + point(x, y),
14470            size: size(em_width, line_height),
14471        })
14472    }
14473}
14474
14475trait SelectionExt {
14476    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14477    fn spanned_rows(
14478        &self,
14479        include_end_if_at_line_start: bool,
14480        map: &DisplaySnapshot,
14481    ) -> Range<MultiBufferRow>;
14482}
14483
14484impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14485    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14486        let start = self
14487            .start
14488            .to_point(&map.buffer_snapshot)
14489            .to_display_point(map);
14490        let end = self
14491            .end
14492            .to_point(&map.buffer_snapshot)
14493            .to_display_point(map);
14494        if self.reversed {
14495            end..start
14496        } else {
14497            start..end
14498        }
14499    }
14500
14501    fn spanned_rows(
14502        &self,
14503        include_end_if_at_line_start: bool,
14504        map: &DisplaySnapshot,
14505    ) -> Range<MultiBufferRow> {
14506        let start = self.start.to_point(&map.buffer_snapshot);
14507        let mut end = self.end.to_point(&map.buffer_snapshot);
14508        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14509            end.row -= 1;
14510        }
14511
14512        let buffer_start = map.prev_line_boundary(start).0;
14513        let buffer_end = map.next_line_boundary(end).0;
14514        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14515    }
14516}
14517
14518impl<T: InvalidationRegion> InvalidationStack<T> {
14519    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14520    where
14521        S: Clone + ToOffset,
14522    {
14523        while let Some(region) = self.last() {
14524            let all_selections_inside_invalidation_ranges =
14525                if selections.len() == region.ranges().len() {
14526                    selections
14527                        .iter()
14528                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14529                        .all(|(selection, invalidation_range)| {
14530                            let head = selection.head().to_offset(buffer);
14531                            invalidation_range.start <= head && invalidation_range.end >= head
14532                        })
14533                } else {
14534                    false
14535                };
14536
14537            if all_selections_inside_invalidation_ranges {
14538                break;
14539            } else {
14540                self.pop();
14541            }
14542        }
14543    }
14544}
14545
14546impl<T> Default for InvalidationStack<T> {
14547    fn default() -> Self {
14548        Self(Default::default())
14549    }
14550}
14551
14552impl<T> Deref for InvalidationStack<T> {
14553    type Target = Vec<T>;
14554
14555    fn deref(&self) -> &Self::Target {
14556        &self.0
14557    }
14558}
14559
14560impl<T> DerefMut for InvalidationStack<T> {
14561    fn deref_mut(&mut self) -> &mut Self::Target {
14562        &mut self.0
14563    }
14564}
14565
14566impl InvalidationRegion for SnippetState {
14567    fn ranges(&self) -> &[Range<Anchor>] {
14568        &self.ranges[self.active_index]
14569    }
14570}
14571
14572pub fn diagnostic_block_renderer(
14573    diagnostic: Diagnostic,
14574    max_message_rows: Option<u8>,
14575    allow_closing: bool,
14576    _is_valid: bool,
14577) -> RenderBlock {
14578    let (text_without_backticks, code_ranges) =
14579        highlight_diagnostic_message(&diagnostic, max_message_rows);
14580
14581    Arc::new(move |cx: &mut BlockContext| {
14582        let group_id: SharedString = cx.block_id.to_string().into();
14583
14584        let mut text_style = cx.text_style().clone();
14585        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14586        let theme_settings = ThemeSettings::get_global(cx);
14587        text_style.font_family = theme_settings.buffer_font.family.clone();
14588        text_style.font_style = theme_settings.buffer_font.style;
14589        text_style.font_features = theme_settings.buffer_font.features.clone();
14590        text_style.font_weight = theme_settings.buffer_font.weight;
14591
14592        let multi_line_diagnostic = diagnostic.message.contains('\n');
14593
14594        let buttons = |diagnostic: &Diagnostic| {
14595            if multi_line_diagnostic {
14596                v_flex()
14597            } else {
14598                h_flex()
14599            }
14600            .when(allow_closing, |div| {
14601                div.children(diagnostic.is_primary.then(|| {
14602                    IconButton::new("close-block", IconName::XCircle)
14603                        .icon_color(Color::Muted)
14604                        .size(ButtonSize::Compact)
14605                        .style(ButtonStyle::Transparent)
14606                        .visible_on_hover(group_id.clone())
14607                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14608                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14609                }))
14610            })
14611            .child(
14612                IconButton::new("copy-block", IconName::Copy)
14613                    .icon_color(Color::Muted)
14614                    .size(ButtonSize::Compact)
14615                    .style(ButtonStyle::Transparent)
14616                    .visible_on_hover(group_id.clone())
14617                    .on_click({
14618                        let message = diagnostic.message.clone();
14619                        move |_click, cx| {
14620                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14621                        }
14622                    })
14623                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14624            )
14625        };
14626
14627        let icon_size = buttons(&diagnostic)
14628            .into_any_element()
14629            .layout_as_root(AvailableSpace::min_size(), cx);
14630
14631        h_flex()
14632            .id(cx.block_id)
14633            .group(group_id.clone())
14634            .relative()
14635            .size_full()
14636            .block_mouse_down()
14637            .pl(cx.gutter_dimensions.width)
14638            .w(cx.max_width - cx.gutter_dimensions.full_width())
14639            .child(
14640                div()
14641                    .flex()
14642                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14643                    .flex_shrink(),
14644            )
14645            .child(buttons(&diagnostic))
14646            .child(div().flex().flex_shrink_0().child(
14647                StyledText::new(text_without_backticks.clone()).with_highlights(
14648                    &text_style,
14649                    code_ranges.iter().map(|range| {
14650                        (
14651                            range.clone(),
14652                            HighlightStyle {
14653                                font_weight: Some(FontWeight::BOLD),
14654                                ..Default::default()
14655                            },
14656                        )
14657                    }),
14658                ),
14659            ))
14660            .into_any_element()
14661    })
14662}
14663
14664fn inline_completion_edit_text(
14665    editor_snapshot: &EditorSnapshot,
14666    edits: &Vec<(Range<Anchor>, String)>,
14667    include_deletions: bool,
14668    cx: &WindowContext,
14669) -> InlineCompletionText {
14670    let edit_start = edits
14671        .first()
14672        .unwrap()
14673        .0
14674        .start
14675        .to_display_point(editor_snapshot);
14676
14677    let mut text = String::new();
14678    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14679    let mut highlights = Vec::new();
14680    for (old_range, new_text) in edits {
14681        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14682        text.extend(
14683            editor_snapshot
14684                .buffer_snapshot
14685                .chunks(offset..old_offset_range.start, false)
14686                .map(|chunk| chunk.text),
14687        );
14688        offset = old_offset_range.end;
14689
14690        let start = text.len();
14691        let color = if include_deletions && new_text.is_empty() {
14692            text.extend(
14693                editor_snapshot
14694                    .buffer_snapshot
14695                    .chunks(old_offset_range.start..offset, false)
14696                    .map(|chunk| chunk.text),
14697            );
14698            cx.theme().status().deleted_background
14699        } else {
14700            text.push_str(new_text);
14701            cx.theme().status().created_background
14702        };
14703        let end = text.len();
14704
14705        highlights.push((
14706            start..end,
14707            HighlightStyle {
14708                background_color: Some(color),
14709                ..Default::default()
14710            },
14711        ));
14712    }
14713
14714    let edit_end = edits
14715        .last()
14716        .unwrap()
14717        .0
14718        .end
14719        .to_display_point(editor_snapshot);
14720    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14721        .to_offset(editor_snapshot, Bias::Right);
14722    text.extend(
14723        editor_snapshot
14724            .buffer_snapshot
14725            .chunks(offset..end_of_line, false)
14726            .map(|chunk| chunk.text),
14727    );
14728
14729    InlineCompletionText::Edit {
14730        text: text.into(),
14731        highlights,
14732    }
14733}
14734
14735pub fn highlight_diagnostic_message(
14736    diagnostic: &Diagnostic,
14737    mut max_message_rows: Option<u8>,
14738) -> (SharedString, Vec<Range<usize>>) {
14739    let mut text_without_backticks = String::new();
14740    let mut code_ranges = Vec::new();
14741
14742    if let Some(source) = &diagnostic.source {
14743        text_without_backticks.push_str(source);
14744        code_ranges.push(0..source.len());
14745        text_without_backticks.push_str(": ");
14746    }
14747
14748    let mut prev_offset = 0;
14749    let mut in_code_block = false;
14750    let has_row_limit = max_message_rows.is_some();
14751    let mut newline_indices = diagnostic
14752        .message
14753        .match_indices('\n')
14754        .filter(|_| has_row_limit)
14755        .map(|(ix, _)| ix)
14756        .fuse()
14757        .peekable();
14758
14759    for (quote_ix, _) in diagnostic
14760        .message
14761        .match_indices('`')
14762        .chain([(diagnostic.message.len(), "")])
14763    {
14764        let mut first_newline_ix = None;
14765        let mut last_newline_ix = None;
14766        while let Some(newline_ix) = newline_indices.peek() {
14767            if *newline_ix < quote_ix {
14768                if first_newline_ix.is_none() {
14769                    first_newline_ix = Some(*newline_ix);
14770                }
14771                last_newline_ix = Some(*newline_ix);
14772
14773                if let Some(rows_left) = &mut max_message_rows {
14774                    if *rows_left == 0 {
14775                        break;
14776                    } else {
14777                        *rows_left -= 1;
14778                    }
14779                }
14780                let _ = newline_indices.next();
14781            } else {
14782                break;
14783            }
14784        }
14785        let prev_len = text_without_backticks.len();
14786        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14787        text_without_backticks.push_str(new_text);
14788        if in_code_block {
14789            code_ranges.push(prev_len..text_without_backticks.len());
14790        }
14791        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14792        in_code_block = !in_code_block;
14793        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14794            text_without_backticks.push_str("...");
14795            break;
14796        }
14797    }
14798
14799    (text_without_backticks.into(), code_ranges)
14800}
14801
14802fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14803    match severity {
14804        DiagnosticSeverity::ERROR => colors.error,
14805        DiagnosticSeverity::WARNING => colors.warning,
14806        DiagnosticSeverity::INFORMATION => colors.info,
14807        DiagnosticSeverity::HINT => colors.info,
14808        _ => colors.ignored,
14809    }
14810}
14811
14812pub fn styled_runs_for_code_label<'a>(
14813    label: &'a CodeLabel,
14814    syntax_theme: &'a theme::SyntaxTheme,
14815) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14816    let fade_out = HighlightStyle {
14817        fade_out: Some(0.35),
14818        ..Default::default()
14819    };
14820
14821    let mut prev_end = label.filter_range.end;
14822    label
14823        .runs
14824        .iter()
14825        .enumerate()
14826        .flat_map(move |(ix, (range, highlight_id))| {
14827            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14828                style
14829            } else {
14830                return Default::default();
14831            };
14832            let mut muted_style = style;
14833            muted_style.highlight(fade_out);
14834
14835            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14836            if range.start >= label.filter_range.end {
14837                if range.start > prev_end {
14838                    runs.push((prev_end..range.start, fade_out));
14839                }
14840                runs.push((range.clone(), muted_style));
14841            } else if range.end <= label.filter_range.end {
14842                runs.push((range.clone(), style));
14843            } else {
14844                runs.push((range.start..label.filter_range.end, style));
14845                runs.push((label.filter_range.end..range.end, muted_style));
14846            }
14847            prev_end = cmp::max(prev_end, range.end);
14848
14849            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14850                runs.push((prev_end..label.text.len(), fade_out));
14851            }
14852
14853            runs
14854        })
14855}
14856
14857pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14858    let mut prev_index = 0;
14859    let mut prev_codepoint: Option<char> = None;
14860    text.char_indices()
14861        .chain([(text.len(), '\0')])
14862        .filter_map(move |(index, codepoint)| {
14863            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14864            let is_boundary = index == text.len()
14865                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14866                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14867            if is_boundary {
14868                let chunk = &text[prev_index..index];
14869                prev_index = index;
14870                Some(chunk)
14871            } else {
14872                None
14873            }
14874        })
14875}
14876
14877pub trait RangeToAnchorExt: Sized {
14878    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14879
14880    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14881        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14882        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14883    }
14884}
14885
14886impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14887    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14888        let start_offset = self.start.to_offset(snapshot);
14889        let end_offset = self.end.to_offset(snapshot);
14890        if start_offset == end_offset {
14891            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14892        } else {
14893            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14894        }
14895    }
14896}
14897
14898pub trait RowExt {
14899    fn as_f32(&self) -> f32;
14900
14901    fn next_row(&self) -> Self;
14902
14903    fn previous_row(&self) -> Self;
14904
14905    fn minus(&self, other: Self) -> u32;
14906}
14907
14908impl RowExt for DisplayRow {
14909    fn as_f32(&self) -> f32 {
14910        self.0 as f32
14911    }
14912
14913    fn next_row(&self) -> Self {
14914        Self(self.0 + 1)
14915    }
14916
14917    fn previous_row(&self) -> Self {
14918        Self(self.0.saturating_sub(1))
14919    }
14920
14921    fn minus(&self, other: Self) -> u32 {
14922        self.0 - other.0
14923    }
14924}
14925
14926impl RowExt for MultiBufferRow {
14927    fn as_f32(&self) -> f32 {
14928        self.0 as f32
14929    }
14930
14931    fn next_row(&self) -> Self {
14932        Self(self.0 + 1)
14933    }
14934
14935    fn previous_row(&self) -> Self {
14936        Self(self.0.saturating_sub(1))
14937    }
14938
14939    fn minus(&self, other: Self) -> u32 {
14940        self.0 - other.0
14941    }
14942}
14943
14944trait RowRangeExt {
14945    type Row;
14946
14947    fn len(&self) -> usize;
14948
14949    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14950}
14951
14952impl RowRangeExt for Range<MultiBufferRow> {
14953    type Row = MultiBufferRow;
14954
14955    fn len(&self) -> usize {
14956        (self.end.0 - self.start.0) as usize
14957    }
14958
14959    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14960        (self.start.0..self.end.0).map(MultiBufferRow)
14961    }
14962}
14963
14964impl RowRangeExt for Range<DisplayRow> {
14965    type Row = DisplayRow;
14966
14967    fn len(&self) -> usize {
14968        (self.end.0 - self.start.0) as usize
14969    }
14970
14971    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14972        (self.start.0..self.end.0).map(DisplayRow)
14973    }
14974}
14975
14976fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14977    if hunk.diff_base_byte_range.is_empty() {
14978        DiffHunkStatus::Added
14979    } else if hunk.row_range.is_empty() {
14980        DiffHunkStatus::Removed
14981    } else {
14982        DiffHunkStatus::Modified
14983    }
14984}
14985
14986/// If select range has more than one line, we
14987/// just point the cursor to range.start.
14988fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14989    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14990        range
14991    } else {
14992        range.start..range.start
14993    }
14994}
14995
14996pub struct KillRing(ClipboardItem);
14997impl Global for KillRing {}
14998
14999const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);