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, DiagnosticEntry, Documentation, IndentKind, IndentSize, Language,
  103    OffsetRangeExt, 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 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)]
  995enum JumpData {
  996    MultiBufferRow {
  997        row: MultiBufferRow,
  998        line_offset_from_top: u32,
  999    },
 1000    MultiBufferPoint {
 1001        excerpt_id: ExcerptId,
 1002        position: Point,
 1003        anchor: text::Anchor,
 1004        line_offset_from_top: u32,
 1005    },
 1006}
 1007
 1008impl Editor {
 1009    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1010        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1011        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1012        Self::new(
 1013            EditorMode::SingleLine { auto_width: false },
 1014            buffer,
 1015            None,
 1016            false,
 1017            cx,
 1018        )
 1019    }
 1020
 1021    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1022        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1023        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1024        Self::new(EditorMode::Full, buffer, None, false, cx)
 1025    }
 1026
 1027    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1028        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1029        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1030        Self::new(
 1031            EditorMode::SingleLine { auto_width: true },
 1032            buffer,
 1033            None,
 1034            false,
 1035            cx,
 1036        )
 1037    }
 1038
 1039    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1040        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1041        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1042        Self::new(
 1043            EditorMode::AutoHeight { max_lines },
 1044            buffer,
 1045            None,
 1046            false,
 1047            cx,
 1048        )
 1049    }
 1050
 1051    pub fn for_buffer(
 1052        buffer: Model<Buffer>,
 1053        project: Option<Model<Project>>,
 1054        cx: &mut ViewContext<Self>,
 1055    ) -> Self {
 1056        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1057        Self::new(EditorMode::Full, buffer, project, false, cx)
 1058    }
 1059
 1060    pub fn for_multibuffer(
 1061        buffer: Model<MultiBuffer>,
 1062        project: Option<Model<Project>>,
 1063        show_excerpt_controls: bool,
 1064        cx: &mut ViewContext<Self>,
 1065    ) -> Self {
 1066        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1067    }
 1068
 1069    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1070        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1071        let mut clone = Self::new(
 1072            self.mode,
 1073            self.buffer.clone(),
 1074            self.project.clone(),
 1075            show_excerpt_controls,
 1076            cx,
 1077        );
 1078        self.display_map.update(cx, |display_map, cx| {
 1079            let snapshot = display_map.snapshot(cx);
 1080            clone.display_map.update(cx, |display_map, cx| {
 1081                display_map.set_state(&snapshot, cx);
 1082            });
 1083        });
 1084        clone.selections.clone_state(&self.selections);
 1085        clone.scroll_manager.clone_state(&self.scroll_manager);
 1086        clone.searchable = self.searchable;
 1087        clone
 1088    }
 1089
 1090    pub fn new(
 1091        mode: EditorMode,
 1092        buffer: Model<MultiBuffer>,
 1093        project: Option<Model<Project>>,
 1094        show_excerpt_controls: bool,
 1095        cx: &mut ViewContext<Self>,
 1096    ) -> Self {
 1097        let style = cx.text_style();
 1098        let font_size = style.font_size.to_pixels(cx.rem_size());
 1099        let editor = cx.view().downgrade();
 1100        let fold_placeholder = FoldPlaceholder {
 1101            constrain_width: true,
 1102            render: Arc::new(move |fold_id, fold_range, cx| {
 1103                let editor = editor.clone();
 1104                div()
 1105                    .id(fold_id)
 1106                    .bg(cx.theme().colors().ghost_element_background)
 1107                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1108                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1109                    .rounded_sm()
 1110                    .size_full()
 1111                    .cursor_pointer()
 1112                    .child("")
 1113                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1114                    .on_click(move |_, cx| {
 1115                        editor
 1116                            .update(cx, |editor, cx| {
 1117                                editor.unfold_ranges(
 1118                                    &[fold_range.start..fold_range.end],
 1119                                    true,
 1120                                    false,
 1121                                    cx,
 1122                                );
 1123                                cx.stop_propagation();
 1124                            })
 1125                            .ok();
 1126                    })
 1127                    .into_any()
 1128            }),
 1129            merge_adjacent: true,
 1130            ..Default::default()
 1131        };
 1132        let display_map = cx.new_model(|cx| {
 1133            DisplayMap::new(
 1134                buffer.clone(),
 1135                style.font(),
 1136                font_size,
 1137                None,
 1138                show_excerpt_controls,
 1139                FILE_HEADER_HEIGHT,
 1140                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1141                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1142                fold_placeholder,
 1143                cx,
 1144            )
 1145        });
 1146
 1147        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1148
 1149        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1150
 1151        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1152            .then(|| language_settings::SoftWrap::None);
 1153
 1154        let mut project_subscriptions = Vec::new();
 1155        if mode == EditorMode::Full {
 1156            if let Some(project) = project.as_ref() {
 1157                if buffer.read(cx).is_singleton() {
 1158                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1159                        cx.emit(EditorEvent::TitleChanged);
 1160                    }));
 1161                }
 1162                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1163                    if let project::Event::RefreshInlayHints = event {
 1164                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1165                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1166                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1167                            let focus_handle = editor.focus_handle(cx);
 1168                            if focus_handle.is_focused(cx) {
 1169                                let snapshot = buffer.read(cx).snapshot();
 1170                                for (range, snippet) in snippet_edits {
 1171                                    let editor_range =
 1172                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1173                                    editor
 1174                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1175                                        .ok();
 1176                                }
 1177                            }
 1178                        }
 1179                    }
 1180                }));
 1181                if let Some(task_inventory) = project
 1182                    .read(cx)
 1183                    .task_store()
 1184                    .read(cx)
 1185                    .task_inventory()
 1186                    .cloned()
 1187                {
 1188                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1189                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1190                    }));
 1191                }
 1192            }
 1193        }
 1194
 1195        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1196
 1197        let inlay_hint_settings =
 1198            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1199        let focus_handle = cx.focus_handle();
 1200        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1201        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1202            .detach();
 1203        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1204            .detach();
 1205        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1206
 1207        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1208            Some(false)
 1209        } else {
 1210            None
 1211        };
 1212
 1213        let mut code_action_providers = Vec::new();
 1214        if let Some(project) = project.clone() {
 1215            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1216            code_action_providers.push(Rc::new(project) as Rc<_>);
 1217        }
 1218
 1219        let mut this = Self {
 1220            focus_handle,
 1221            show_cursor_when_unfocused: false,
 1222            last_focused_descendant: None,
 1223            buffer: buffer.clone(),
 1224            display_map: display_map.clone(),
 1225            selections,
 1226            scroll_manager: ScrollManager::new(cx),
 1227            columnar_selection_tail: None,
 1228            add_selections_state: None,
 1229            select_next_state: None,
 1230            select_prev_state: None,
 1231            selection_history: Default::default(),
 1232            autoclose_regions: Default::default(),
 1233            snippet_stack: Default::default(),
 1234            select_larger_syntax_node_stack: Vec::new(),
 1235            ime_transaction: Default::default(),
 1236            active_diagnostics: None,
 1237            soft_wrap_mode_override,
 1238            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1239            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1240            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1241            project,
 1242            blink_manager: blink_manager.clone(),
 1243            show_local_selections: true,
 1244            show_scrollbars: true,
 1245            mode,
 1246            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1247            show_gutter: mode == EditorMode::Full,
 1248            show_line_numbers: None,
 1249            use_relative_line_numbers: None,
 1250            show_git_diff_gutter: None,
 1251            show_code_actions: None,
 1252            show_runnables: None,
 1253            show_wrap_guides: None,
 1254            show_indent_guides,
 1255            placeholder_text: None,
 1256            highlight_order: 0,
 1257            highlighted_rows: HashMap::default(),
 1258            background_highlights: Default::default(),
 1259            gutter_highlights: TreeMap::default(),
 1260            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1261            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1262            nav_history: None,
 1263            context_menu: RefCell::new(None),
 1264            mouse_context_menu: None,
 1265            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1266            completion_tasks: Default::default(),
 1267            signature_help_state: SignatureHelpState::default(),
 1268            auto_signature_help: None,
 1269            find_all_references_task_sources: Vec::new(),
 1270            next_completion_id: 0,
 1271            next_inlay_id: 0,
 1272            code_action_providers,
 1273            available_code_actions: Default::default(),
 1274            code_actions_task: Default::default(),
 1275            document_highlights_task: Default::default(),
 1276            linked_editing_range_task: Default::default(),
 1277            pending_rename: Default::default(),
 1278            searchable: true,
 1279            cursor_shape: EditorSettings::get_global(cx)
 1280                .cursor_shape
 1281                .unwrap_or_default(),
 1282            current_line_highlight: None,
 1283            autoindent_mode: Some(AutoindentMode::EachLine),
 1284            collapse_matches: false,
 1285            workspace: None,
 1286            input_enabled: true,
 1287            use_modal_editing: mode == EditorMode::Full,
 1288            read_only: false,
 1289            use_autoclose: true,
 1290            use_auto_surround: true,
 1291            auto_replace_emoji_shortcode: false,
 1292            leader_peer_id: None,
 1293            remote_id: None,
 1294            hover_state: Default::default(),
 1295            hovered_link_state: Default::default(),
 1296            inline_completion_provider: None,
 1297            active_inline_completion: None,
 1298            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1299            diff_map: DiffMap::default(),
 1300            gutter_hovered: false,
 1301            pixel_position_of_newest_cursor: None,
 1302            last_bounds: None,
 1303            expect_bounds_change: None,
 1304            gutter_dimensions: GutterDimensions::default(),
 1305            style: None,
 1306            show_cursor_names: false,
 1307            hovered_cursors: Default::default(),
 1308            next_editor_action_id: EditorActionId::default(),
 1309            editor_actions: Rc::default(),
 1310            show_inline_completions_override: None,
 1311            enable_inline_completions: true,
 1312            custom_context_menu: None,
 1313            show_git_blame_gutter: false,
 1314            show_git_blame_inline: false,
 1315            show_selection_menu: None,
 1316            show_git_blame_inline_delay_task: None,
 1317            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1318            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1319                .session
 1320                .restore_unsaved_buffers,
 1321            blame: None,
 1322            blame_subscription: None,
 1323            tasks: Default::default(),
 1324            _subscriptions: vec![
 1325                cx.observe(&buffer, Self::on_buffer_changed),
 1326                cx.subscribe(&buffer, Self::on_buffer_event),
 1327                cx.observe(&display_map, Self::on_display_map_changed),
 1328                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1329                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1330                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1331                cx.observe_window_activation(|editor, cx| {
 1332                    let active = cx.is_window_active();
 1333                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1334                        if active {
 1335                            blink_manager.enable(cx);
 1336                        } else {
 1337                            blink_manager.disable(cx);
 1338                        }
 1339                    });
 1340                }),
 1341            ],
 1342            tasks_update_task: None,
 1343            linked_edit_ranges: Default::default(),
 1344            previous_search_ranges: None,
 1345            breadcrumb_header: None,
 1346            focused_block: None,
 1347            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1348            addons: HashMap::default(),
 1349            registered_buffers: HashMap::default(),
 1350            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1351            toggle_fold_multiple_buffers: Task::ready(()),
 1352            text_style_refinement: None,
 1353        };
 1354        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1355        this._subscriptions.extend(project_subscriptions);
 1356
 1357        this.end_selection(cx);
 1358        this.scroll_manager.show_scrollbar(cx);
 1359
 1360        if mode == EditorMode::Full {
 1361            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1362            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1363
 1364            if this.git_blame_inline_enabled {
 1365                this.git_blame_inline_enabled = true;
 1366                this.start_git_blame_inline(false, cx);
 1367            }
 1368
 1369            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1370                if let Some(project) = this.project.as_ref() {
 1371                    let lsp_store = project.read(cx).lsp_store();
 1372                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1373                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1374                    });
 1375                    this.registered_buffers
 1376                        .insert(buffer.read(cx).remote_id(), handle);
 1377                }
 1378            }
 1379        }
 1380
 1381        this.report_editor_event("Editor Opened", None, cx);
 1382        this
 1383    }
 1384
 1385    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1386        self.mouse_context_menu
 1387            .as_ref()
 1388            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1389    }
 1390
 1391    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1392        let mut key_context = KeyContext::new_with_defaults();
 1393        key_context.add("Editor");
 1394        let mode = match self.mode {
 1395            EditorMode::SingleLine { .. } => "single_line",
 1396            EditorMode::AutoHeight { .. } => "auto_height",
 1397            EditorMode::Full => "full",
 1398        };
 1399
 1400        if EditorSettings::jupyter_enabled(cx) {
 1401            key_context.add("jupyter");
 1402        }
 1403
 1404        key_context.set("mode", mode);
 1405        if self.pending_rename.is_some() {
 1406            key_context.add("renaming");
 1407        }
 1408        match self.context_menu.borrow().as_ref() {
 1409            Some(CodeContextMenu::Completions(_)) => {
 1410                key_context.add("menu");
 1411                key_context.add("showing_completions")
 1412            }
 1413            Some(CodeContextMenu::CodeActions(_)) => {
 1414                key_context.add("menu");
 1415                key_context.add("showing_code_actions")
 1416            }
 1417            None => {}
 1418        }
 1419
 1420        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1421        if !self.focus_handle(cx).contains_focused(cx)
 1422            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1423        {
 1424            for addon in self.addons.values() {
 1425                addon.extend_key_context(&mut key_context, cx)
 1426            }
 1427        }
 1428
 1429        if let Some(extension) = self
 1430            .buffer
 1431            .read(cx)
 1432            .as_singleton()
 1433            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1434        {
 1435            key_context.set("extension", extension.to_string());
 1436        }
 1437
 1438        if self.has_active_inline_completion() {
 1439            key_context.add("copilot_suggestion");
 1440            key_context.add("inline_completion");
 1441        }
 1442
 1443        if !self
 1444            .selections
 1445            .disjoint
 1446            .iter()
 1447            .all(|selection| selection.start == selection.end)
 1448        {
 1449            key_context.add("selection");
 1450        }
 1451
 1452        key_context
 1453    }
 1454
 1455    pub fn new_file(
 1456        workspace: &mut Workspace,
 1457        _: &workspace::NewFile,
 1458        cx: &mut ViewContext<Workspace>,
 1459    ) {
 1460        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1461            "Failed to create buffer",
 1462            cx,
 1463            |e, _| match e.error_code() {
 1464                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1465                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1466                e.error_tag("required").unwrap_or("the latest version")
 1467            )),
 1468                _ => None,
 1469            },
 1470        );
 1471    }
 1472
 1473    pub fn new_in_workspace(
 1474        workspace: &mut Workspace,
 1475        cx: &mut ViewContext<Workspace>,
 1476    ) -> Task<Result<View<Editor>>> {
 1477        let project = workspace.project().clone();
 1478        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1479
 1480        cx.spawn(|workspace, mut cx| async move {
 1481            let buffer = create.await?;
 1482            workspace.update(&mut cx, |workspace, cx| {
 1483                let editor =
 1484                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1485                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1486                editor
 1487            })
 1488        })
 1489    }
 1490
 1491    fn new_file_vertical(
 1492        workspace: &mut Workspace,
 1493        _: &workspace::NewFileSplitVertical,
 1494        cx: &mut ViewContext<Workspace>,
 1495    ) {
 1496        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1497    }
 1498
 1499    fn new_file_horizontal(
 1500        workspace: &mut Workspace,
 1501        _: &workspace::NewFileSplitHorizontal,
 1502        cx: &mut ViewContext<Workspace>,
 1503    ) {
 1504        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1505    }
 1506
 1507    fn new_file_in_direction(
 1508        workspace: &mut Workspace,
 1509        direction: SplitDirection,
 1510        cx: &mut ViewContext<Workspace>,
 1511    ) {
 1512        let project = workspace.project().clone();
 1513        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1514
 1515        cx.spawn(|workspace, mut cx| async move {
 1516            let buffer = create.await?;
 1517            workspace.update(&mut cx, move |workspace, cx| {
 1518                workspace.split_item(
 1519                    direction,
 1520                    Box::new(
 1521                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1522                    ),
 1523                    cx,
 1524                )
 1525            })?;
 1526            anyhow::Ok(())
 1527        })
 1528        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1529            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1530                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1531                e.error_tag("required").unwrap_or("the latest version")
 1532            )),
 1533            _ => None,
 1534        });
 1535    }
 1536
 1537    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1538        self.leader_peer_id
 1539    }
 1540
 1541    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1542        &self.buffer
 1543    }
 1544
 1545    pub fn workspace(&self) -> Option<View<Workspace>> {
 1546        self.workspace.as_ref()?.0.upgrade()
 1547    }
 1548
 1549    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1550        self.buffer().read(cx).title(cx)
 1551    }
 1552
 1553    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1554        let git_blame_gutter_max_author_length = self
 1555            .render_git_blame_gutter(cx)
 1556            .then(|| {
 1557                if let Some(blame) = self.blame.as_ref() {
 1558                    let max_author_length =
 1559                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1560                    Some(max_author_length)
 1561                } else {
 1562                    None
 1563                }
 1564            })
 1565            .flatten();
 1566
 1567        EditorSnapshot {
 1568            mode: self.mode,
 1569            show_gutter: self.show_gutter,
 1570            show_line_numbers: self.show_line_numbers,
 1571            show_git_diff_gutter: self.show_git_diff_gutter,
 1572            show_code_actions: self.show_code_actions,
 1573            show_runnables: self.show_runnables,
 1574            git_blame_gutter_max_author_length,
 1575            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1576            scroll_anchor: self.scroll_manager.anchor(),
 1577            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1578            placeholder_text: self.placeholder_text.clone(),
 1579            diff_map: self.diff_map.snapshot(),
 1580            is_focused: self.focus_handle.is_focused(cx),
 1581            current_line_highlight: self
 1582                .current_line_highlight
 1583                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1584            gutter_hovered: self.gutter_hovered,
 1585        }
 1586    }
 1587
 1588    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1589        self.buffer.read(cx).language_at(point, cx)
 1590    }
 1591
 1592    pub fn file_at<T: ToOffset>(
 1593        &self,
 1594        point: T,
 1595        cx: &AppContext,
 1596    ) -> Option<Arc<dyn language::File>> {
 1597        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1598    }
 1599
 1600    pub fn active_excerpt(
 1601        &self,
 1602        cx: &AppContext,
 1603    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1604        self.buffer
 1605            .read(cx)
 1606            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1607    }
 1608
 1609    pub fn mode(&self) -> EditorMode {
 1610        self.mode
 1611    }
 1612
 1613    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1614        self.collaboration_hub.as_deref()
 1615    }
 1616
 1617    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1618        self.collaboration_hub = Some(hub);
 1619    }
 1620
 1621    pub fn set_custom_context_menu(
 1622        &mut self,
 1623        f: impl 'static
 1624            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1625    ) {
 1626        self.custom_context_menu = Some(Box::new(f))
 1627    }
 1628
 1629    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1630        self.completion_provider = provider;
 1631    }
 1632
 1633    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1634        self.semantics_provider.clone()
 1635    }
 1636
 1637    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1638        self.semantics_provider = provider;
 1639    }
 1640
 1641    pub fn set_inline_completion_provider<T>(
 1642        &mut self,
 1643        provider: Option<Model<T>>,
 1644        cx: &mut ViewContext<Self>,
 1645    ) where
 1646        T: InlineCompletionProvider,
 1647    {
 1648        self.inline_completion_provider =
 1649            provider.map(|provider| RegisteredInlineCompletionProvider {
 1650                _subscription: cx.observe(&provider, |this, _, cx| {
 1651                    if this.focus_handle.is_focused(cx) {
 1652                        this.update_visible_inline_completion(cx);
 1653                    }
 1654                }),
 1655                provider: Arc::new(provider),
 1656            });
 1657        self.refresh_inline_completion(false, false, cx);
 1658    }
 1659
 1660    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1661        self.placeholder_text.as_deref()
 1662    }
 1663
 1664    pub fn set_placeholder_text(
 1665        &mut self,
 1666        placeholder_text: impl Into<Arc<str>>,
 1667        cx: &mut ViewContext<Self>,
 1668    ) {
 1669        let placeholder_text = Some(placeholder_text.into());
 1670        if self.placeholder_text != placeholder_text {
 1671            self.placeholder_text = placeholder_text;
 1672            cx.notify();
 1673        }
 1674    }
 1675
 1676    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1677        self.cursor_shape = cursor_shape;
 1678
 1679        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1680        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1681
 1682        cx.notify();
 1683    }
 1684
 1685    pub fn set_current_line_highlight(
 1686        &mut self,
 1687        current_line_highlight: Option<CurrentLineHighlight>,
 1688    ) {
 1689        self.current_line_highlight = current_line_highlight;
 1690    }
 1691
 1692    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1693        self.collapse_matches = collapse_matches;
 1694    }
 1695
 1696    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1697        let buffers = self.buffer.read(cx).all_buffers();
 1698        let Some(lsp_store) = self.lsp_store(cx) else {
 1699            return;
 1700        };
 1701        lsp_store.update(cx, |lsp_store, cx| {
 1702            for buffer in buffers {
 1703                self.registered_buffers
 1704                    .entry(buffer.read(cx).remote_id())
 1705                    .or_insert_with(|| {
 1706                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1707                    });
 1708            }
 1709        })
 1710    }
 1711
 1712    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1713        if self.collapse_matches {
 1714            return range.start..range.start;
 1715        }
 1716        range.clone()
 1717    }
 1718
 1719    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1720        if self.display_map.read(cx).clip_at_line_ends != clip {
 1721            self.display_map
 1722                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1723        }
 1724    }
 1725
 1726    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1727        self.input_enabled = input_enabled;
 1728    }
 1729
 1730    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1731        self.enable_inline_completions = enabled;
 1732    }
 1733
 1734    pub fn set_autoindent(&mut self, autoindent: bool) {
 1735        if autoindent {
 1736            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1737        } else {
 1738            self.autoindent_mode = None;
 1739        }
 1740    }
 1741
 1742    pub fn read_only(&self, cx: &AppContext) -> bool {
 1743        self.read_only || self.buffer.read(cx).read_only()
 1744    }
 1745
 1746    pub fn set_read_only(&mut self, read_only: bool) {
 1747        self.read_only = read_only;
 1748    }
 1749
 1750    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1751        self.use_autoclose = autoclose;
 1752    }
 1753
 1754    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1755        self.use_auto_surround = auto_surround;
 1756    }
 1757
 1758    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1759        self.auto_replace_emoji_shortcode = auto_replace;
 1760    }
 1761
 1762    pub fn toggle_inline_completions(
 1763        &mut self,
 1764        _: &ToggleInlineCompletions,
 1765        cx: &mut ViewContext<Self>,
 1766    ) {
 1767        if self.show_inline_completions_override.is_some() {
 1768            self.set_show_inline_completions(None, cx);
 1769        } else {
 1770            let cursor = self.selections.newest_anchor().head();
 1771            if let Some((buffer, cursor_buffer_position)) =
 1772                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1773            {
 1774                let show_inline_completions =
 1775                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1776                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1777            }
 1778        }
 1779    }
 1780
 1781    pub fn set_show_inline_completions(
 1782        &mut self,
 1783        show_inline_completions: Option<bool>,
 1784        cx: &mut ViewContext<Self>,
 1785    ) {
 1786        self.show_inline_completions_override = show_inline_completions;
 1787        self.refresh_inline_completion(false, true, cx);
 1788    }
 1789
 1790    fn should_show_inline_completions(
 1791        &self,
 1792        buffer: &Model<Buffer>,
 1793        buffer_position: language::Anchor,
 1794        cx: &AppContext,
 1795    ) -> bool {
 1796        if !self.snippet_stack.is_empty() {
 1797            return false;
 1798        }
 1799
 1800        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1801            return false;
 1802        }
 1803
 1804        if let Some(provider) = self.inline_completion_provider() {
 1805            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1806                show_inline_completions
 1807            } else {
 1808                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1809            }
 1810        } else {
 1811            false
 1812        }
 1813    }
 1814
 1815    fn inline_completions_disabled_in_scope(
 1816        &self,
 1817        buffer: &Model<Buffer>,
 1818        buffer_position: language::Anchor,
 1819        cx: &AppContext,
 1820    ) -> bool {
 1821        let snapshot = buffer.read(cx).snapshot();
 1822        let settings = snapshot.settings_at(buffer_position, cx);
 1823
 1824        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1825            return false;
 1826        };
 1827
 1828        scope.override_name().map_or(false, |scope_name| {
 1829            settings
 1830                .inline_completions_disabled_in
 1831                .iter()
 1832                .any(|s| s == scope_name)
 1833        })
 1834    }
 1835
 1836    pub fn set_use_modal_editing(&mut self, to: bool) {
 1837        self.use_modal_editing = to;
 1838    }
 1839
 1840    pub fn use_modal_editing(&self) -> bool {
 1841        self.use_modal_editing
 1842    }
 1843
 1844    fn selections_did_change(
 1845        &mut self,
 1846        local: bool,
 1847        old_cursor_position: &Anchor,
 1848        show_completions: bool,
 1849        cx: &mut ViewContext<Self>,
 1850    ) {
 1851        cx.invalidate_character_coordinates();
 1852
 1853        // Copy selections to primary selection buffer
 1854        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1855        if local {
 1856            let selections = self.selections.all::<usize>(cx);
 1857            let buffer_handle = self.buffer.read(cx).read(cx);
 1858
 1859            let mut text = String::new();
 1860            for (index, selection) in selections.iter().enumerate() {
 1861                let text_for_selection = buffer_handle
 1862                    .text_for_range(selection.start..selection.end)
 1863                    .collect::<String>();
 1864
 1865                text.push_str(&text_for_selection);
 1866                if index != selections.len() - 1 {
 1867                    text.push('\n');
 1868                }
 1869            }
 1870
 1871            if !text.is_empty() {
 1872                cx.write_to_primary(ClipboardItem::new_string(text));
 1873            }
 1874        }
 1875
 1876        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1877            self.buffer.update(cx, |buffer, cx| {
 1878                buffer.set_active_selections(
 1879                    &self.selections.disjoint_anchors(),
 1880                    self.selections.line_mode,
 1881                    self.cursor_shape,
 1882                    cx,
 1883                )
 1884            });
 1885        }
 1886        let display_map = self
 1887            .display_map
 1888            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1889        let buffer = &display_map.buffer_snapshot;
 1890        self.add_selections_state = None;
 1891        self.select_next_state = None;
 1892        self.select_prev_state = None;
 1893        self.select_larger_syntax_node_stack.clear();
 1894        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1895        self.snippet_stack
 1896            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1897        self.take_rename(false, cx);
 1898
 1899        let new_cursor_position = self.selections.newest_anchor().head();
 1900
 1901        self.push_to_nav_history(
 1902            *old_cursor_position,
 1903            Some(new_cursor_position.to_point(buffer)),
 1904            cx,
 1905        );
 1906
 1907        if local {
 1908            let new_cursor_position = self.selections.newest_anchor().head();
 1909            let mut context_menu = self.context_menu.borrow_mut();
 1910            let completion_menu = match context_menu.as_ref() {
 1911                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1912                _ => {
 1913                    *context_menu = None;
 1914                    None
 1915                }
 1916            };
 1917
 1918            if let Some(completion_menu) = completion_menu {
 1919                let cursor_position = new_cursor_position.to_offset(buffer);
 1920                let (word_range, kind) =
 1921                    buffer.surrounding_word(completion_menu.initial_position, true);
 1922                if kind == Some(CharKind::Word)
 1923                    && word_range.to_inclusive().contains(&cursor_position)
 1924                {
 1925                    let mut completion_menu = completion_menu.clone();
 1926                    drop(context_menu);
 1927
 1928                    let query = Self::completion_query(buffer, cursor_position);
 1929                    cx.spawn(move |this, mut cx| async move {
 1930                        completion_menu
 1931                            .filter(query.as_deref(), cx.background_executor().clone())
 1932                            .await;
 1933
 1934                        this.update(&mut cx, |this, cx| {
 1935                            let mut context_menu = this.context_menu.borrow_mut();
 1936                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1937                            else {
 1938                                return;
 1939                            };
 1940
 1941                            if menu.id > completion_menu.id {
 1942                                return;
 1943                            }
 1944
 1945                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1946                            drop(context_menu);
 1947                            cx.notify();
 1948                        })
 1949                    })
 1950                    .detach();
 1951
 1952                    if show_completions {
 1953                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1954                    }
 1955                } else {
 1956                    drop(context_menu);
 1957                    self.hide_context_menu(cx);
 1958                }
 1959            } else {
 1960                drop(context_menu);
 1961            }
 1962
 1963            hide_hover(self, cx);
 1964
 1965            if old_cursor_position.to_display_point(&display_map).row()
 1966                != new_cursor_position.to_display_point(&display_map).row()
 1967            {
 1968                self.available_code_actions.take();
 1969            }
 1970            self.refresh_code_actions(cx);
 1971            self.refresh_document_highlights(cx);
 1972            refresh_matching_bracket_highlights(self, cx);
 1973            self.update_visible_inline_completion(cx);
 1974            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1975            if self.git_blame_inline_enabled {
 1976                self.start_inline_blame_timer(cx);
 1977            }
 1978        }
 1979
 1980        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1981        cx.emit(EditorEvent::SelectionsChanged { local });
 1982
 1983        if self.selections.disjoint_anchors().len() == 1 {
 1984            cx.emit(SearchEvent::ActiveMatchChanged)
 1985        }
 1986        cx.notify();
 1987    }
 1988
 1989    pub fn change_selections<R>(
 1990        &mut self,
 1991        autoscroll: Option<Autoscroll>,
 1992        cx: &mut ViewContext<Self>,
 1993        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1994    ) -> R {
 1995        self.change_selections_inner(autoscroll, true, cx, change)
 1996    }
 1997
 1998    pub fn change_selections_inner<R>(
 1999        &mut self,
 2000        autoscroll: Option<Autoscroll>,
 2001        request_completions: bool,
 2002        cx: &mut ViewContext<Self>,
 2003        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2004    ) -> R {
 2005        let old_cursor_position = self.selections.newest_anchor().head();
 2006        self.push_to_selection_history();
 2007
 2008        let (changed, result) = self.selections.change_with(cx, change);
 2009
 2010        if changed {
 2011            if let Some(autoscroll) = autoscroll {
 2012                self.request_autoscroll(autoscroll, cx);
 2013            }
 2014            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2015
 2016            if self.should_open_signature_help_automatically(
 2017                &old_cursor_position,
 2018                self.signature_help_state.backspace_pressed(),
 2019                cx,
 2020            ) {
 2021                self.show_signature_help(&ShowSignatureHelp, cx);
 2022            }
 2023            self.signature_help_state.set_backspace_pressed(false);
 2024        }
 2025
 2026        result
 2027    }
 2028
 2029    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2030    where
 2031        I: IntoIterator<Item = (Range<S>, T)>,
 2032        S: ToOffset,
 2033        T: Into<Arc<str>>,
 2034    {
 2035        if self.read_only(cx) {
 2036            return;
 2037        }
 2038
 2039        self.buffer
 2040            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2041    }
 2042
 2043    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2044    where
 2045        I: IntoIterator<Item = (Range<S>, T)>,
 2046        S: ToOffset,
 2047        T: Into<Arc<str>>,
 2048    {
 2049        if self.read_only(cx) {
 2050            return;
 2051        }
 2052
 2053        self.buffer.update(cx, |buffer, cx| {
 2054            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2055        });
 2056    }
 2057
 2058    pub fn edit_with_block_indent<I, S, T>(
 2059        &mut self,
 2060        edits: I,
 2061        original_indent_columns: Vec<u32>,
 2062        cx: &mut ViewContext<Self>,
 2063    ) where
 2064        I: IntoIterator<Item = (Range<S>, T)>,
 2065        S: ToOffset,
 2066        T: Into<Arc<str>>,
 2067    {
 2068        if self.read_only(cx) {
 2069            return;
 2070        }
 2071
 2072        self.buffer.update(cx, |buffer, cx| {
 2073            buffer.edit(
 2074                edits,
 2075                Some(AutoindentMode::Block {
 2076                    original_indent_columns,
 2077                }),
 2078                cx,
 2079            )
 2080        });
 2081    }
 2082
 2083    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2084        self.hide_context_menu(cx);
 2085
 2086        match phase {
 2087            SelectPhase::Begin {
 2088                position,
 2089                add,
 2090                click_count,
 2091            } => self.begin_selection(position, add, click_count, cx),
 2092            SelectPhase::BeginColumnar {
 2093                position,
 2094                goal_column,
 2095                reset,
 2096            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2097            SelectPhase::Extend {
 2098                position,
 2099                click_count,
 2100            } => self.extend_selection(position, click_count, cx),
 2101            SelectPhase::Update {
 2102                position,
 2103                goal_column,
 2104                scroll_delta,
 2105            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2106            SelectPhase::End => self.end_selection(cx),
 2107        }
 2108    }
 2109
 2110    fn extend_selection(
 2111        &mut self,
 2112        position: DisplayPoint,
 2113        click_count: usize,
 2114        cx: &mut ViewContext<Self>,
 2115    ) {
 2116        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2117        let tail = self.selections.newest::<usize>(cx).tail();
 2118        self.begin_selection(position, false, click_count, cx);
 2119
 2120        let position = position.to_offset(&display_map, Bias::Left);
 2121        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2122
 2123        let mut pending_selection = self
 2124            .selections
 2125            .pending_anchor()
 2126            .expect("extend_selection not called with pending selection");
 2127        if position >= tail {
 2128            pending_selection.start = tail_anchor;
 2129        } else {
 2130            pending_selection.end = tail_anchor;
 2131            pending_selection.reversed = true;
 2132        }
 2133
 2134        let mut pending_mode = self.selections.pending_mode().unwrap();
 2135        match &mut pending_mode {
 2136            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2137            _ => {}
 2138        }
 2139
 2140        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2141            s.set_pending(pending_selection, pending_mode)
 2142        });
 2143    }
 2144
 2145    fn begin_selection(
 2146        &mut self,
 2147        position: DisplayPoint,
 2148        add: bool,
 2149        click_count: usize,
 2150        cx: &mut ViewContext<Self>,
 2151    ) {
 2152        if !self.focus_handle.is_focused(cx) {
 2153            self.last_focused_descendant = None;
 2154            cx.focus(&self.focus_handle);
 2155        }
 2156
 2157        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2158        let buffer = &display_map.buffer_snapshot;
 2159        let newest_selection = self.selections.newest_anchor().clone();
 2160        let position = display_map.clip_point(position, Bias::Left);
 2161
 2162        let start;
 2163        let end;
 2164        let mode;
 2165        let mut auto_scroll;
 2166        match click_count {
 2167            1 => {
 2168                start = buffer.anchor_before(position.to_point(&display_map));
 2169                end = start;
 2170                mode = SelectMode::Character;
 2171                auto_scroll = true;
 2172            }
 2173            2 => {
 2174                let range = movement::surrounding_word(&display_map, position);
 2175                start = buffer.anchor_before(range.start.to_point(&display_map));
 2176                end = buffer.anchor_before(range.end.to_point(&display_map));
 2177                mode = SelectMode::Word(start..end);
 2178                auto_scroll = true;
 2179            }
 2180            3 => {
 2181                let position = display_map
 2182                    .clip_point(position, Bias::Left)
 2183                    .to_point(&display_map);
 2184                let line_start = display_map.prev_line_boundary(position).0;
 2185                let next_line_start = buffer.clip_point(
 2186                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2187                    Bias::Left,
 2188                );
 2189                start = buffer.anchor_before(line_start);
 2190                end = buffer.anchor_before(next_line_start);
 2191                mode = SelectMode::Line(start..end);
 2192                auto_scroll = true;
 2193            }
 2194            _ => {
 2195                start = buffer.anchor_before(0);
 2196                end = buffer.anchor_before(buffer.len());
 2197                mode = SelectMode::All;
 2198                auto_scroll = false;
 2199            }
 2200        }
 2201        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2202
 2203        let point_to_delete: Option<usize> = {
 2204            let selected_points: Vec<Selection<Point>> =
 2205                self.selections.disjoint_in_range(start..end, cx);
 2206
 2207            if !add || click_count > 1 {
 2208                None
 2209            } else if !selected_points.is_empty() {
 2210                Some(selected_points[0].id)
 2211            } else {
 2212                let clicked_point_already_selected =
 2213                    self.selections.disjoint.iter().find(|selection| {
 2214                        selection.start.to_point(buffer) == start.to_point(buffer)
 2215                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2216                    });
 2217
 2218                clicked_point_already_selected.map(|selection| selection.id)
 2219            }
 2220        };
 2221
 2222        let selections_count = self.selections.count();
 2223
 2224        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2225            if let Some(point_to_delete) = point_to_delete {
 2226                s.delete(point_to_delete);
 2227
 2228                if selections_count == 1 {
 2229                    s.set_pending_anchor_range(start..end, mode);
 2230                }
 2231            } else {
 2232                if !add {
 2233                    s.clear_disjoint();
 2234                } else if click_count > 1 {
 2235                    s.delete(newest_selection.id)
 2236                }
 2237
 2238                s.set_pending_anchor_range(start..end, mode);
 2239            }
 2240        });
 2241    }
 2242
 2243    fn begin_columnar_selection(
 2244        &mut self,
 2245        position: DisplayPoint,
 2246        goal_column: u32,
 2247        reset: bool,
 2248        cx: &mut ViewContext<Self>,
 2249    ) {
 2250        if !self.focus_handle.is_focused(cx) {
 2251            self.last_focused_descendant = None;
 2252            cx.focus(&self.focus_handle);
 2253        }
 2254
 2255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2256
 2257        if reset {
 2258            let pointer_position = display_map
 2259                .buffer_snapshot
 2260                .anchor_before(position.to_point(&display_map));
 2261
 2262            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2263                s.clear_disjoint();
 2264                s.set_pending_anchor_range(
 2265                    pointer_position..pointer_position,
 2266                    SelectMode::Character,
 2267                );
 2268            });
 2269        }
 2270
 2271        let tail = self.selections.newest::<Point>(cx).tail();
 2272        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2273
 2274        if !reset {
 2275            self.select_columns(
 2276                tail.to_display_point(&display_map),
 2277                position,
 2278                goal_column,
 2279                &display_map,
 2280                cx,
 2281            );
 2282        }
 2283    }
 2284
 2285    fn update_selection(
 2286        &mut self,
 2287        position: DisplayPoint,
 2288        goal_column: u32,
 2289        scroll_delta: gpui::Point<f32>,
 2290        cx: &mut ViewContext<Self>,
 2291    ) {
 2292        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2293
 2294        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2295            let tail = tail.to_display_point(&display_map);
 2296            self.select_columns(tail, position, goal_column, &display_map, cx);
 2297        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2298            let buffer = self.buffer.read(cx).snapshot(cx);
 2299            let head;
 2300            let tail;
 2301            let mode = self.selections.pending_mode().unwrap();
 2302            match &mode {
 2303                SelectMode::Character => {
 2304                    head = position.to_point(&display_map);
 2305                    tail = pending.tail().to_point(&buffer);
 2306                }
 2307                SelectMode::Word(original_range) => {
 2308                    let original_display_range = original_range.start.to_display_point(&display_map)
 2309                        ..original_range.end.to_display_point(&display_map);
 2310                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2311                        ..original_display_range.end.to_point(&display_map);
 2312                    if movement::is_inside_word(&display_map, position)
 2313                        || original_display_range.contains(&position)
 2314                    {
 2315                        let word_range = movement::surrounding_word(&display_map, position);
 2316                        if word_range.start < original_display_range.start {
 2317                            head = word_range.start.to_point(&display_map);
 2318                        } else {
 2319                            head = word_range.end.to_point(&display_map);
 2320                        }
 2321                    } else {
 2322                        head = position.to_point(&display_map);
 2323                    }
 2324
 2325                    if head <= original_buffer_range.start {
 2326                        tail = original_buffer_range.end;
 2327                    } else {
 2328                        tail = original_buffer_range.start;
 2329                    }
 2330                }
 2331                SelectMode::Line(original_range) => {
 2332                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2333
 2334                    let position = display_map
 2335                        .clip_point(position, Bias::Left)
 2336                        .to_point(&display_map);
 2337                    let line_start = display_map.prev_line_boundary(position).0;
 2338                    let next_line_start = buffer.clip_point(
 2339                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2340                        Bias::Left,
 2341                    );
 2342
 2343                    if line_start < original_range.start {
 2344                        head = line_start
 2345                    } else {
 2346                        head = next_line_start
 2347                    }
 2348
 2349                    if head <= original_range.start {
 2350                        tail = original_range.end;
 2351                    } else {
 2352                        tail = original_range.start;
 2353                    }
 2354                }
 2355                SelectMode::All => {
 2356                    return;
 2357                }
 2358            };
 2359
 2360            if head < tail {
 2361                pending.start = buffer.anchor_before(head);
 2362                pending.end = buffer.anchor_before(tail);
 2363                pending.reversed = true;
 2364            } else {
 2365                pending.start = buffer.anchor_before(tail);
 2366                pending.end = buffer.anchor_before(head);
 2367                pending.reversed = false;
 2368            }
 2369
 2370            self.change_selections(None, cx, |s| {
 2371                s.set_pending(pending, mode);
 2372            });
 2373        } else {
 2374            log::error!("update_selection dispatched with no pending selection");
 2375            return;
 2376        }
 2377
 2378        self.apply_scroll_delta(scroll_delta, cx);
 2379        cx.notify();
 2380    }
 2381
 2382    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2383        self.columnar_selection_tail.take();
 2384        if self.selections.pending_anchor().is_some() {
 2385            let selections = self.selections.all::<usize>(cx);
 2386            self.change_selections(None, cx, |s| {
 2387                s.select(selections);
 2388                s.clear_pending();
 2389            });
 2390        }
 2391    }
 2392
 2393    fn select_columns(
 2394        &mut self,
 2395        tail: DisplayPoint,
 2396        head: DisplayPoint,
 2397        goal_column: u32,
 2398        display_map: &DisplaySnapshot,
 2399        cx: &mut ViewContext<Self>,
 2400    ) {
 2401        let start_row = cmp::min(tail.row(), head.row());
 2402        let end_row = cmp::max(tail.row(), head.row());
 2403        let start_column = cmp::min(tail.column(), goal_column);
 2404        let end_column = cmp::max(tail.column(), goal_column);
 2405        let reversed = start_column < tail.column();
 2406
 2407        let selection_ranges = (start_row.0..=end_row.0)
 2408            .map(DisplayRow)
 2409            .filter_map(|row| {
 2410                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2411                    let start = display_map
 2412                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2413                        .to_point(display_map);
 2414                    let end = display_map
 2415                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2416                        .to_point(display_map);
 2417                    if reversed {
 2418                        Some(end..start)
 2419                    } else {
 2420                        Some(start..end)
 2421                    }
 2422                } else {
 2423                    None
 2424                }
 2425            })
 2426            .collect::<Vec<_>>();
 2427
 2428        self.change_selections(None, cx, |s| {
 2429            s.select_ranges(selection_ranges);
 2430        });
 2431        cx.notify();
 2432    }
 2433
 2434    pub fn has_pending_nonempty_selection(&self) -> bool {
 2435        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2436            Some(Selection { start, end, .. }) => start != end,
 2437            None => false,
 2438        };
 2439
 2440        pending_nonempty_selection
 2441            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2442    }
 2443
 2444    pub fn has_pending_selection(&self) -> bool {
 2445        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2446    }
 2447
 2448    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2449        if self.clear_expanded_diff_hunks(cx) {
 2450            cx.notify();
 2451            return;
 2452        }
 2453        if self.dismiss_menus_and_popups(true, cx) {
 2454            return;
 2455        }
 2456
 2457        if self.mode == EditorMode::Full
 2458            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2459        {
 2460            return;
 2461        }
 2462
 2463        cx.propagate();
 2464    }
 2465
 2466    pub fn dismiss_menus_and_popups(
 2467        &mut self,
 2468        should_report_inline_completion_event: bool,
 2469        cx: &mut ViewContext<Self>,
 2470    ) -> bool {
 2471        if self.take_rename(false, cx).is_some() {
 2472            return true;
 2473        }
 2474
 2475        if hide_hover(self, cx) {
 2476            return true;
 2477        }
 2478
 2479        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2480            return true;
 2481        }
 2482
 2483        if self.hide_context_menu(cx).is_some() {
 2484            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2485                self.update_visible_inline_completion(cx);
 2486            }
 2487            return true;
 2488        }
 2489
 2490        if self.mouse_context_menu.take().is_some() {
 2491            return true;
 2492        }
 2493
 2494        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2495            return true;
 2496        }
 2497
 2498        if self.snippet_stack.pop().is_some() {
 2499            return true;
 2500        }
 2501
 2502        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2503            self.dismiss_diagnostics(cx);
 2504            return true;
 2505        }
 2506
 2507        false
 2508    }
 2509
 2510    fn linked_editing_ranges_for(
 2511        &self,
 2512        selection: Range<text::Anchor>,
 2513        cx: &AppContext,
 2514    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2515        if self.linked_edit_ranges.is_empty() {
 2516            return None;
 2517        }
 2518        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2519            selection.end.buffer_id.and_then(|end_buffer_id| {
 2520                if selection.start.buffer_id != Some(end_buffer_id) {
 2521                    return None;
 2522                }
 2523                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2524                let snapshot = buffer.read(cx).snapshot();
 2525                self.linked_edit_ranges
 2526                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2527                    .map(|ranges| (ranges, snapshot, buffer))
 2528            })?;
 2529        use text::ToOffset as TO;
 2530        // find offset from the start of current range to current cursor position
 2531        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2532
 2533        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2534        let start_difference = start_offset - start_byte_offset;
 2535        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2536        let end_difference = end_offset - start_byte_offset;
 2537        // Current range has associated linked ranges.
 2538        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2539        for range in linked_ranges.iter() {
 2540            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2541            let end_offset = start_offset + end_difference;
 2542            let start_offset = start_offset + start_difference;
 2543            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2544                continue;
 2545            }
 2546            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2547                if s.start.buffer_id != selection.start.buffer_id
 2548                    || s.end.buffer_id != selection.end.buffer_id
 2549                {
 2550                    return false;
 2551                }
 2552                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2553                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2554            }) {
 2555                continue;
 2556            }
 2557            let start = buffer_snapshot.anchor_after(start_offset);
 2558            let end = buffer_snapshot.anchor_after(end_offset);
 2559            linked_edits
 2560                .entry(buffer.clone())
 2561                .or_default()
 2562                .push(start..end);
 2563        }
 2564        Some(linked_edits)
 2565    }
 2566
 2567    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2568        let text: Arc<str> = text.into();
 2569
 2570        if self.read_only(cx) {
 2571            return;
 2572        }
 2573
 2574        let selections = self.selections.all_adjusted(cx);
 2575        let mut bracket_inserted = false;
 2576        let mut edits = Vec::new();
 2577        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2578        let mut new_selections = Vec::with_capacity(selections.len());
 2579        let mut new_autoclose_regions = Vec::new();
 2580        let snapshot = self.buffer.read(cx).read(cx);
 2581
 2582        for (selection, autoclose_region) in
 2583            self.selections_with_autoclose_regions(selections, &snapshot)
 2584        {
 2585            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2586                // Determine if the inserted text matches the opening or closing
 2587                // bracket of any of this language's bracket pairs.
 2588                let mut bracket_pair = None;
 2589                let mut is_bracket_pair_start = false;
 2590                let mut is_bracket_pair_end = false;
 2591                if !text.is_empty() {
 2592                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2593                    //  and they are removing the character that triggered IME popup.
 2594                    for (pair, enabled) in scope.brackets() {
 2595                        if !pair.close && !pair.surround {
 2596                            continue;
 2597                        }
 2598
 2599                        if enabled && pair.start.ends_with(text.as_ref()) {
 2600                            let prefix_len = pair.start.len() - text.len();
 2601                            let preceding_text_matches_prefix = prefix_len == 0
 2602                                || (selection.start.column >= (prefix_len as u32)
 2603                                    && snapshot.contains_str_at(
 2604                                        Point::new(
 2605                                            selection.start.row,
 2606                                            selection.start.column - (prefix_len as u32),
 2607                                        ),
 2608                                        &pair.start[..prefix_len],
 2609                                    ));
 2610                            if preceding_text_matches_prefix {
 2611                                bracket_pair = Some(pair.clone());
 2612                                is_bracket_pair_start = true;
 2613                                break;
 2614                            }
 2615                        }
 2616                        if pair.end.as_str() == text.as_ref() {
 2617                            bracket_pair = Some(pair.clone());
 2618                            is_bracket_pair_end = true;
 2619                            break;
 2620                        }
 2621                    }
 2622                }
 2623
 2624                if let Some(bracket_pair) = bracket_pair {
 2625                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2626                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2627                    let auto_surround =
 2628                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2629                    if selection.is_empty() {
 2630                        if is_bracket_pair_start {
 2631                            // If the inserted text is a suffix of an opening bracket and the
 2632                            // selection is preceded by the rest of the opening bracket, then
 2633                            // insert the closing bracket.
 2634                            let following_text_allows_autoclose = snapshot
 2635                                .chars_at(selection.start)
 2636                                .next()
 2637                                .map_or(true, |c| scope.should_autoclose_before(c));
 2638
 2639                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2640                                && bracket_pair.start.len() == 1
 2641                            {
 2642                                let target = bracket_pair.start.chars().next().unwrap();
 2643                                let current_line_count = snapshot
 2644                                    .reversed_chars_at(selection.start)
 2645                                    .take_while(|&c| c != '\n')
 2646                                    .filter(|&c| c == target)
 2647                                    .count();
 2648                                current_line_count % 2 == 1
 2649                            } else {
 2650                                false
 2651                            };
 2652
 2653                            if autoclose
 2654                                && bracket_pair.close
 2655                                && following_text_allows_autoclose
 2656                                && !is_closing_quote
 2657                            {
 2658                                let anchor = snapshot.anchor_before(selection.end);
 2659                                new_selections.push((selection.map(|_| anchor), text.len()));
 2660                                new_autoclose_regions.push((
 2661                                    anchor,
 2662                                    text.len(),
 2663                                    selection.id,
 2664                                    bracket_pair.clone(),
 2665                                ));
 2666                                edits.push((
 2667                                    selection.range(),
 2668                                    format!("{}{}", text, bracket_pair.end).into(),
 2669                                ));
 2670                                bracket_inserted = true;
 2671                                continue;
 2672                            }
 2673                        }
 2674
 2675                        if let Some(region) = autoclose_region {
 2676                            // If the selection is followed by an auto-inserted closing bracket,
 2677                            // then don't insert that closing bracket again; just move the selection
 2678                            // past the closing bracket.
 2679                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2680                                && text.as_ref() == region.pair.end.as_str();
 2681                            if should_skip {
 2682                                let anchor = snapshot.anchor_after(selection.end);
 2683                                new_selections
 2684                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2685                                continue;
 2686                            }
 2687                        }
 2688
 2689                        let always_treat_brackets_as_autoclosed = snapshot
 2690                            .settings_at(selection.start, cx)
 2691                            .always_treat_brackets_as_autoclosed;
 2692                        if always_treat_brackets_as_autoclosed
 2693                            && is_bracket_pair_end
 2694                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2695                        {
 2696                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2697                            // and the inserted text is a closing bracket and the selection is followed
 2698                            // by the closing bracket then move the selection past the closing bracket.
 2699                            let anchor = snapshot.anchor_after(selection.end);
 2700                            new_selections.push((selection.map(|_| anchor), text.len()));
 2701                            continue;
 2702                        }
 2703                    }
 2704                    // If an opening bracket is 1 character long and is typed while
 2705                    // text is selected, then surround that text with the bracket pair.
 2706                    else if auto_surround
 2707                        && bracket_pair.surround
 2708                        && is_bracket_pair_start
 2709                        && bracket_pair.start.chars().count() == 1
 2710                    {
 2711                        edits.push((selection.start..selection.start, text.clone()));
 2712                        edits.push((
 2713                            selection.end..selection.end,
 2714                            bracket_pair.end.as_str().into(),
 2715                        ));
 2716                        bracket_inserted = true;
 2717                        new_selections.push((
 2718                            Selection {
 2719                                id: selection.id,
 2720                                start: snapshot.anchor_after(selection.start),
 2721                                end: snapshot.anchor_before(selection.end),
 2722                                reversed: selection.reversed,
 2723                                goal: selection.goal,
 2724                            },
 2725                            0,
 2726                        ));
 2727                        continue;
 2728                    }
 2729                }
 2730            }
 2731
 2732            if self.auto_replace_emoji_shortcode
 2733                && selection.is_empty()
 2734                && text.as_ref().ends_with(':')
 2735            {
 2736                if let Some(possible_emoji_short_code) =
 2737                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2738                {
 2739                    if !possible_emoji_short_code.is_empty() {
 2740                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2741                            let emoji_shortcode_start = Point::new(
 2742                                selection.start.row,
 2743                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2744                            );
 2745
 2746                            // Remove shortcode from buffer
 2747                            edits.push((
 2748                                emoji_shortcode_start..selection.start,
 2749                                "".to_string().into(),
 2750                            ));
 2751                            new_selections.push((
 2752                                Selection {
 2753                                    id: selection.id,
 2754                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2755                                    end: snapshot.anchor_before(selection.start),
 2756                                    reversed: selection.reversed,
 2757                                    goal: selection.goal,
 2758                                },
 2759                                0,
 2760                            ));
 2761
 2762                            // Insert emoji
 2763                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2764                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2765                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2766
 2767                            continue;
 2768                        }
 2769                    }
 2770                }
 2771            }
 2772
 2773            // If not handling any auto-close operation, then just replace the selected
 2774            // text with the given input and move the selection to the end of the
 2775            // newly inserted text.
 2776            let anchor = snapshot.anchor_after(selection.end);
 2777            if !self.linked_edit_ranges.is_empty() {
 2778                let start_anchor = snapshot.anchor_before(selection.start);
 2779
 2780                let is_word_char = text.chars().next().map_or(true, |char| {
 2781                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2782                    classifier.is_word(char)
 2783                });
 2784
 2785                if is_word_char {
 2786                    if let Some(ranges) = self
 2787                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2788                    {
 2789                        for (buffer, edits) in ranges {
 2790                            linked_edits
 2791                                .entry(buffer.clone())
 2792                                .or_default()
 2793                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2794                        }
 2795                    }
 2796                }
 2797            }
 2798
 2799            new_selections.push((selection.map(|_| anchor), 0));
 2800            edits.push((selection.start..selection.end, text.clone()));
 2801        }
 2802
 2803        drop(snapshot);
 2804
 2805        self.transact(cx, |this, cx| {
 2806            this.buffer.update(cx, |buffer, cx| {
 2807                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2808            });
 2809            for (buffer, edits) in linked_edits {
 2810                buffer.update(cx, |buffer, cx| {
 2811                    let snapshot = buffer.snapshot();
 2812                    let edits = edits
 2813                        .into_iter()
 2814                        .map(|(range, text)| {
 2815                            use text::ToPoint as TP;
 2816                            let end_point = TP::to_point(&range.end, &snapshot);
 2817                            let start_point = TP::to_point(&range.start, &snapshot);
 2818                            (start_point..end_point, text)
 2819                        })
 2820                        .sorted_by_key(|(range, _)| range.start)
 2821                        .collect::<Vec<_>>();
 2822                    buffer.edit(edits, None, cx);
 2823                })
 2824            }
 2825            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2826            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2827            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2828            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2829                .zip(new_selection_deltas)
 2830                .map(|(selection, delta)| Selection {
 2831                    id: selection.id,
 2832                    start: selection.start + delta,
 2833                    end: selection.end + delta,
 2834                    reversed: selection.reversed,
 2835                    goal: SelectionGoal::None,
 2836                })
 2837                .collect::<Vec<_>>();
 2838
 2839            let mut i = 0;
 2840            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2841                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2842                let start = map.buffer_snapshot.anchor_before(position);
 2843                let end = map.buffer_snapshot.anchor_after(position);
 2844                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2845                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2846                        Ordering::Less => i += 1,
 2847                        Ordering::Greater => break,
 2848                        Ordering::Equal => {
 2849                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2850                                Ordering::Less => i += 1,
 2851                                Ordering::Equal => break,
 2852                                Ordering::Greater => break,
 2853                            }
 2854                        }
 2855                    }
 2856                }
 2857                this.autoclose_regions.insert(
 2858                    i,
 2859                    AutocloseRegion {
 2860                        selection_id,
 2861                        range: start..end,
 2862                        pair,
 2863                    },
 2864                );
 2865            }
 2866
 2867            let had_active_inline_completion = this.has_active_inline_completion();
 2868            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2869                s.select(new_selections)
 2870            });
 2871
 2872            if !bracket_inserted {
 2873                if let Some(on_type_format_task) =
 2874                    this.trigger_on_type_formatting(text.to_string(), cx)
 2875                {
 2876                    on_type_format_task.detach_and_log_err(cx);
 2877                }
 2878            }
 2879
 2880            let editor_settings = EditorSettings::get_global(cx);
 2881            if bracket_inserted
 2882                && (editor_settings.auto_signature_help
 2883                    || editor_settings.show_signature_help_after_edits)
 2884            {
 2885                this.show_signature_help(&ShowSignatureHelp, cx);
 2886            }
 2887
 2888            let trigger_in_words =
 2889                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2890            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2891            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2892            this.refresh_inline_completion(true, false, cx);
 2893        });
 2894    }
 2895
 2896    fn find_possible_emoji_shortcode_at_position(
 2897        snapshot: &MultiBufferSnapshot,
 2898        position: Point,
 2899    ) -> Option<String> {
 2900        let mut chars = Vec::new();
 2901        let mut found_colon = false;
 2902        for char in snapshot.reversed_chars_at(position).take(100) {
 2903            // Found a possible emoji shortcode in the middle of the buffer
 2904            if found_colon {
 2905                if char.is_whitespace() {
 2906                    chars.reverse();
 2907                    return Some(chars.iter().collect());
 2908                }
 2909                // If the previous character is not a whitespace, we are in the middle of a word
 2910                // and we only want to complete the shortcode if the word is made up of other emojis
 2911                let mut containing_word = String::new();
 2912                for ch in snapshot
 2913                    .reversed_chars_at(position)
 2914                    .skip(chars.len() + 1)
 2915                    .take(100)
 2916                {
 2917                    if ch.is_whitespace() {
 2918                        break;
 2919                    }
 2920                    containing_word.push(ch);
 2921                }
 2922                let containing_word = containing_word.chars().rev().collect::<String>();
 2923                if util::word_consists_of_emojis(containing_word.as_str()) {
 2924                    chars.reverse();
 2925                    return Some(chars.iter().collect());
 2926                }
 2927            }
 2928
 2929            if char.is_whitespace() || !char.is_ascii() {
 2930                return None;
 2931            }
 2932            if char == ':' {
 2933                found_colon = true;
 2934            } else {
 2935                chars.push(char);
 2936            }
 2937        }
 2938        // Found a possible emoji shortcode at the beginning of the buffer
 2939        chars.reverse();
 2940        Some(chars.iter().collect())
 2941    }
 2942
 2943    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2944        self.transact(cx, |this, cx| {
 2945            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2946                let selections = this.selections.all::<usize>(cx);
 2947                let multi_buffer = this.buffer.read(cx);
 2948                let buffer = multi_buffer.snapshot(cx);
 2949                selections
 2950                    .iter()
 2951                    .map(|selection| {
 2952                        let start_point = selection.start.to_point(&buffer);
 2953                        let mut indent =
 2954                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2955                        indent.len = cmp::min(indent.len, start_point.column);
 2956                        let start = selection.start;
 2957                        let end = selection.end;
 2958                        let selection_is_empty = start == end;
 2959                        let language_scope = buffer.language_scope_at(start);
 2960                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2961                            &language_scope
 2962                        {
 2963                            let leading_whitespace_len = buffer
 2964                                .reversed_chars_at(start)
 2965                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2966                                .map(|c| c.len_utf8())
 2967                                .sum::<usize>();
 2968
 2969                            let trailing_whitespace_len = buffer
 2970                                .chars_at(end)
 2971                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2972                                .map(|c| c.len_utf8())
 2973                                .sum::<usize>();
 2974
 2975                            let insert_extra_newline =
 2976                                language.brackets().any(|(pair, enabled)| {
 2977                                    let pair_start = pair.start.trim_end();
 2978                                    let pair_end = pair.end.trim_start();
 2979
 2980                                    enabled
 2981                                        && pair.newline
 2982                                        && buffer.contains_str_at(
 2983                                            end + trailing_whitespace_len,
 2984                                            pair_end,
 2985                                        )
 2986                                        && buffer.contains_str_at(
 2987                                            (start - leading_whitespace_len)
 2988                                                .saturating_sub(pair_start.len()),
 2989                                            pair_start,
 2990                                        )
 2991                                });
 2992
 2993                            // Comment extension on newline is allowed only for cursor selections
 2994                            let comment_delimiter = maybe!({
 2995                                if !selection_is_empty {
 2996                                    return None;
 2997                                }
 2998
 2999                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3000                                    return None;
 3001                                }
 3002
 3003                                let delimiters = language.line_comment_prefixes();
 3004                                let max_len_of_delimiter =
 3005                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3006                                let (snapshot, range) =
 3007                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3008
 3009                                let mut index_of_first_non_whitespace = 0;
 3010                                let comment_candidate = snapshot
 3011                                    .chars_for_range(range)
 3012                                    .skip_while(|c| {
 3013                                        let should_skip = c.is_whitespace();
 3014                                        if should_skip {
 3015                                            index_of_first_non_whitespace += 1;
 3016                                        }
 3017                                        should_skip
 3018                                    })
 3019                                    .take(max_len_of_delimiter)
 3020                                    .collect::<String>();
 3021                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3022                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3023                                })?;
 3024                                let cursor_is_placed_after_comment_marker =
 3025                                    index_of_first_non_whitespace + comment_prefix.len()
 3026                                        <= start_point.column as usize;
 3027                                if cursor_is_placed_after_comment_marker {
 3028                                    Some(comment_prefix.clone())
 3029                                } else {
 3030                                    None
 3031                                }
 3032                            });
 3033                            (comment_delimiter, insert_extra_newline)
 3034                        } else {
 3035                            (None, false)
 3036                        };
 3037
 3038                        let capacity_for_delimiter = comment_delimiter
 3039                            .as_deref()
 3040                            .map(str::len)
 3041                            .unwrap_or_default();
 3042                        let mut new_text =
 3043                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3044                        new_text.push('\n');
 3045                        new_text.extend(indent.chars());
 3046                        if let Some(delimiter) = &comment_delimiter {
 3047                            new_text.push_str(delimiter);
 3048                        }
 3049                        if insert_extra_newline {
 3050                            new_text = new_text.repeat(2);
 3051                        }
 3052
 3053                        let anchor = buffer.anchor_after(end);
 3054                        let new_selection = selection.map(|_| anchor);
 3055                        (
 3056                            (start..end, new_text),
 3057                            (insert_extra_newline, new_selection),
 3058                        )
 3059                    })
 3060                    .unzip()
 3061            };
 3062
 3063            this.edit_with_autoindent(edits, cx);
 3064            let buffer = this.buffer.read(cx).snapshot(cx);
 3065            let new_selections = selection_fixup_info
 3066                .into_iter()
 3067                .map(|(extra_newline_inserted, new_selection)| {
 3068                    let mut cursor = new_selection.end.to_point(&buffer);
 3069                    if extra_newline_inserted {
 3070                        cursor.row -= 1;
 3071                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3072                    }
 3073                    new_selection.map(|_| cursor)
 3074                })
 3075                .collect();
 3076
 3077            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3078            this.refresh_inline_completion(true, false, cx);
 3079        });
 3080    }
 3081
 3082    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3083        let buffer = self.buffer.read(cx);
 3084        let snapshot = buffer.snapshot(cx);
 3085
 3086        let mut edits = Vec::new();
 3087        let mut rows = Vec::new();
 3088
 3089        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3090            let cursor = selection.head();
 3091            let row = cursor.row;
 3092
 3093            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3094
 3095            let newline = "\n".to_string();
 3096            edits.push((start_of_line..start_of_line, newline));
 3097
 3098            rows.push(row + rows_inserted as u32);
 3099        }
 3100
 3101        self.transact(cx, |editor, cx| {
 3102            editor.edit(edits, cx);
 3103
 3104            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3105                let mut index = 0;
 3106                s.move_cursors_with(|map, _, _| {
 3107                    let row = rows[index];
 3108                    index += 1;
 3109
 3110                    let point = Point::new(row, 0);
 3111                    let boundary = map.next_line_boundary(point).1;
 3112                    let clipped = map.clip_point(boundary, Bias::Left);
 3113
 3114                    (clipped, SelectionGoal::None)
 3115                });
 3116            });
 3117
 3118            let mut indent_edits = Vec::new();
 3119            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3120            for row in rows {
 3121                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3122                for (row, indent) in indents {
 3123                    if indent.len == 0 {
 3124                        continue;
 3125                    }
 3126
 3127                    let text = match indent.kind {
 3128                        IndentKind::Space => " ".repeat(indent.len as usize),
 3129                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3130                    };
 3131                    let point = Point::new(row.0, 0);
 3132                    indent_edits.push((point..point, text));
 3133                }
 3134            }
 3135            editor.edit(indent_edits, cx);
 3136        });
 3137    }
 3138
 3139    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3140        let buffer = self.buffer.read(cx);
 3141        let snapshot = buffer.snapshot(cx);
 3142
 3143        let mut edits = Vec::new();
 3144        let mut rows = Vec::new();
 3145        let mut rows_inserted = 0;
 3146
 3147        for selection in self.selections.all_adjusted(cx) {
 3148            let cursor = selection.head();
 3149            let row = cursor.row;
 3150
 3151            let point = Point::new(row + 1, 0);
 3152            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3153
 3154            let newline = "\n".to_string();
 3155            edits.push((start_of_line..start_of_line, newline));
 3156
 3157            rows_inserted += 1;
 3158            rows.push(row + rows_inserted);
 3159        }
 3160
 3161        self.transact(cx, |editor, cx| {
 3162            editor.edit(edits, cx);
 3163
 3164            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3165                let mut index = 0;
 3166                s.move_cursors_with(|map, _, _| {
 3167                    let row = rows[index];
 3168                    index += 1;
 3169
 3170                    let point = Point::new(row, 0);
 3171                    let boundary = map.next_line_boundary(point).1;
 3172                    let clipped = map.clip_point(boundary, Bias::Left);
 3173
 3174                    (clipped, SelectionGoal::None)
 3175                });
 3176            });
 3177
 3178            let mut indent_edits = Vec::new();
 3179            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3180            for row in rows {
 3181                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3182                for (row, indent) in indents {
 3183                    if indent.len == 0 {
 3184                        continue;
 3185                    }
 3186
 3187                    let text = match indent.kind {
 3188                        IndentKind::Space => " ".repeat(indent.len as usize),
 3189                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3190                    };
 3191                    let point = Point::new(row.0, 0);
 3192                    indent_edits.push((point..point, text));
 3193                }
 3194            }
 3195            editor.edit(indent_edits, cx);
 3196        });
 3197    }
 3198
 3199    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3200        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3201            original_indent_columns: Vec::new(),
 3202        });
 3203        self.insert_with_autoindent_mode(text, autoindent, cx);
 3204    }
 3205
 3206    fn insert_with_autoindent_mode(
 3207        &mut self,
 3208        text: &str,
 3209        autoindent_mode: Option<AutoindentMode>,
 3210        cx: &mut ViewContext<Self>,
 3211    ) {
 3212        if self.read_only(cx) {
 3213            return;
 3214        }
 3215
 3216        let text: Arc<str> = text.into();
 3217        self.transact(cx, |this, cx| {
 3218            let old_selections = this.selections.all_adjusted(cx);
 3219            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3220                let anchors = {
 3221                    let snapshot = buffer.read(cx);
 3222                    old_selections
 3223                        .iter()
 3224                        .map(|s| {
 3225                            let anchor = snapshot.anchor_after(s.head());
 3226                            s.map(|_| anchor)
 3227                        })
 3228                        .collect::<Vec<_>>()
 3229                };
 3230                buffer.edit(
 3231                    old_selections
 3232                        .iter()
 3233                        .map(|s| (s.start..s.end, text.clone())),
 3234                    autoindent_mode,
 3235                    cx,
 3236                );
 3237                anchors
 3238            });
 3239
 3240            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3241                s.select_anchors(selection_anchors);
 3242            })
 3243        });
 3244    }
 3245
 3246    fn trigger_completion_on_input(
 3247        &mut self,
 3248        text: &str,
 3249        trigger_in_words: bool,
 3250        cx: &mut ViewContext<Self>,
 3251    ) {
 3252        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3253            self.show_completions(
 3254                &ShowCompletions {
 3255                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3256                },
 3257                cx,
 3258            );
 3259        } else {
 3260            self.hide_context_menu(cx);
 3261        }
 3262    }
 3263
 3264    fn is_completion_trigger(
 3265        &self,
 3266        text: &str,
 3267        trigger_in_words: bool,
 3268        cx: &mut ViewContext<Self>,
 3269    ) -> bool {
 3270        let position = self.selections.newest_anchor().head();
 3271        let multibuffer = self.buffer.read(cx);
 3272        let Some(buffer) = position
 3273            .buffer_id
 3274            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3275        else {
 3276            return false;
 3277        };
 3278
 3279        if let Some(completion_provider) = &self.completion_provider {
 3280            completion_provider.is_completion_trigger(
 3281                &buffer,
 3282                position.text_anchor,
 3283                text,
 3284                trigger_in_words,
 3285                cx,
 3286            )
 3287        } else {
 3288            false
 3289        }
 3290    }
 3291
 3292    /// If any empty selections is touching the start of its innermost containing autoclose
 3293    /// region, expand it to select the brackets.
 3294    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3295        let selections = self.selections.all::<usize>(cx);
 3296        let buffer = self.buffer.read(cx).read(cx);
 3297        let new_selections = self
 3298            .selections_with_autoclose_regions(selections, &buffer)
 3299            .map(|(mut selection, region)| {
 3300                if !selection.is_empty() {
 3301                    return selection;
 3302                }
 3303
 3304                if let Some(region) = region {
 3305                    let mut range = region.range.to_offset(&buffer);
 3306                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3307                        range.start -= region.pair.start.len();
 3308                        if buffer.contains_str_at(range.start, &region.pair.start)
 3309                            && buffer.contains_str_at(range.end, &region.pair.end)
 3310                        {
 3311                            range.end += region.pair.end.len();
 3312                            selection.start = range.start;
 3313                            selection.end = range.end;
 3314
 3315                            return selection;
 3316                        }
 3317                    }
 3318                }
 3319
 3320                let always_treat_brackets_as_autoclosed = buffer
 3321                    .settings_at(selection.start, cx)
 3322                    .always_treat_brackets_as_autoclosed;
 3323
 3324                if !always_treat_brackets_as_autoclosed {
 3325                    return selection;
 3326                }
 3327
 3328                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3329                    for (pair, enabled) in scope.brackets() {
 3330                        if !enabled || !pair.close {
 3331                            continue;
 3332                        }
 3333
 3334                        if buffer.contains_str_at(selection.start, &pair.end) {
 3335                            let pair_start_len = pair.start.len();
 3336                            if buffer.contains_str_at(
 3337                                selection.start.saturating_sub(pair_start_len),
 3338                                &pair.start,
 3339                            ) {
 3340                                selection.start -= pair_start_len;
 3341                                selection.end += pair.end.len();
 3342
 3343                                return selection;
 3344                            }
 3345                        }
 3346                    }
 3347                }
 3348
 3349                selection
 3350            })
 3351            .collect();
 3352
 3353        drop(buffer);
 3354        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3355    }
 3356
 3357    /// Iterate the given selections, and for each one, find the smallest surrounding
 3358    /// autoclose region. This uses the ordering of the selections and the autoclose
 3359    /// regions to avoid repeated comparisons.
 3360    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3361        &'a self,
 3362        selections: impl IntoIterator<Item = Selection<D>>,
 3363        buffer: &'a MultiBufferSnapshot,
 3364    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3365        let mut i = 0;
 3366        let mut regions = self.autoclose_regions.as_slice();
 3367        selections.into_iter().map(move |selection| {
 3368            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3369
 3370            let mut enclosing = None;
 3371            while let Some(pair_state) = regions.get(i) {
 3372                if pair_state.range.end.to_offset(buffer) < range.start {
 3373                    regions = &regions[i + 1..];
 3374                    i = 0;
 3375                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3376                    break;
 3377                } else {
 3378                    if pair_state.selection_id == selection.id {
 3379                        enclosing = Some(pair_state);
 3380                    }
 3381                    i += 1;
 3382                }
 3383            }
 3384
 3385            (selection, enclosing)
 3386        })
 3387    }
 3388
 3389    /// Remove any autoclose regions that no longer contain their selection.
 3390    fn invalidate_autoclose_regions(
 3391        &mut self,
 3392        mut selections: &[Selection<Anchor>],
 3393        buffer: &MultiBufferSnapshot,
 3394    ) {
 3395        self.autoclose_regions.retain(|state| {
 3396            let mut i = 0;
 3397            while let Some(selection) = selections.get(i) {
 3398                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3399                    selections = &selections[1..];
 3400                    continue;
 3401                }
 3402                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3403                    break;
 3404                }
 3405                if selection.id == state.selection_id {
 3406                    return true;
 3407                } else {
 3408                    i += 1;
 3409                }
 3410            }
 3411            false
 3412        });
 3413    }
 3414
 3415    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3416        let offset = position.to_offset(buffer);
 3417        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3418        if offset > word_range.start && kind == Some(CharKind::Word) {
 3419            Some(
 3420                buffer
 3421                    .text_for_range(word_range.start..offset)
 3422                    .collect::<String>(),
 3423            )
 3424        } else {
 3425            None
 3426        }
 3427    }
 3428
 3429    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3430        self.refresh_inlay_hints(
 3431            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3432            cx,
 3433        );
 3434    }
 3435
 3436    pub fn inlay_hints_enabled(&self) -> bool {
 3437        self.inlay_hint_cache.enabled
 3438    }
 3439
 3440    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3441        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3442            return;
 3443        }
 3444
 3445        let reason_description = reason.description();
 3446        let ignore_debounce = matches!(
 3447            reason,
 3448            InlayHintRefreshReason::SettingsChange(_)
 3449                | InlayHintRefreshReason::Toggle(_)
 3450                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3451        );
 3452        let (invalidate_cache, required_languages) = match reason {
 3453            InlayHintRefreshReason::Toggle(enabled) => {
 3454                self.inlay_hint_cache.enabled = enabled;
 3455                if enabled {
 3456                    (InvalidationStrategy::RefreshRequested, None)
 3457                } else {
 3458                    self.inlay_hint_cache.clear();
 3459                    self.splice_inlays(
 3460                        self.visible_inlay_hints(cx)
 3461                            .iter()
 3462                            .map(|inlay| inlay.id)
 3463                            .collect(),
 3464                        Vec::new(),
 3465                        cx,
 3466                    );
 3467                    return;
 3468                }
 3469            }
 3470            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3471                match self.inlay_hint_cache.update_settings(
 3472                    &self.buffer,
 3473                    new_settings,
 3474                    self.visible_inlay_hints(cx),
 3475                    cx,
 3476                ) {
 3477                    ControlFlow::Break(Some(InlaySplice {
 3478                        to_remove,
 3479                        to_insert,
 3480                    })) => {
 3481                        self.splice_inlays(to_remove, to_insert, cx);
 3482                        return;
 3483                    }
 3484                    ControlFlow::Break(None) => return,
 3485                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3486                }
 3487            }
 3488            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3489                if let Some(InlaySplice {
 3490                    to_remove,
 3491                    to_insert,
 3492                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3493                {
 3494                    self.splice_inlays(to_remove, to_insert, cx);
 3495                }
 3496                return;
 3497            }
 3498            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3499            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3500                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3501            }
 3502            InlayHintRefreshReason::RefreshRequested => {
 3503                (InvalidationStrategy::RefreshRequested, None)
 3504            }
 3505        };
 3506
 3507        if let Some(InlaySplice {
 3508            to_remove,
 3509            to_insert,
 3510        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3511            reason_description,
 3512            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3513            invalidate_cache,
 3514            ignore_debounce,
 3515            cx,
 3516        ) {
 3517            self.splice_inlays(to_remove, to_insert, cx);
 3518        }
 3519    }
 3520
 3521    fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
 3522        self.display_map
 3523            .read(cx)
 3524            .current_inlays()
 3525            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3526            .cloned()
 3527            .collect()
 3528    }
 3529
 3530    pub fn excerpts_for_inlay_hints_query(
 3531        &self,
 3532        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3533        cx: &mut ViewContext<Editor>,
 3534    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3535        let Some(project) = self.project.as_ref() else {
 3536            return HashMap::default();
 3537        };
 3538        let project = project.read(cx);
 3539        let multi_buffer = self.buffer().read(cx);
 3540        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3541        let multi_buffer_visible_start = self
 3542            .scroll_manager
 3543            .anchor()
 3544            .anchor
 3545            .to_point(&multi_buffer_snapshot);
 3546        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3547            multi_buffer_visible_start
 3548                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3549            Bias::Left,
 3550        );
 3551        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3552        multi_buffer_snapshot
 3553            .range_to_buffer_ranges(multi_buffer_visible_range)
 3554            .into_iter()
 3555            .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
 3556            .filter_map(|(excerpt, excerpt_visible_range)| {
 3557                let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
 3558                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3559                let worktree_entry = buffer_worktree
 3560                    .read(cx)
 3561                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3562                if worktree_entry.is_ignored {
 3563                    return None;
 3564                }
 3565
 3566                let language = excerpt.buffer().language()?;
 3567                if let Some(restrict_to_languages) = restrict_to_languages {
 3568                    if !restrict_to_languages.contains(language) {
 3569                        return None;
 3570                    }
 3571                }
 3572                Some((
 3573                    excerpt.id(),
 3574                    (
 3575                        multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
 3576                        excerpt.buffer().version().clone(),
 3577                        excerpt_visible_range,
 3578                    ),
 3579                ))
 3580            })
 3581            .collect()
 3582    }
 3583
 3584    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3585        TextLayoutDetails {
 3586            text_system: cx.text_system().clone(),
 3587            editor_style: self.style.clone().unwrap(),
 3588            rem_size: cx.rem_size(),
 3589            scroll_anchor: self.scroll_manager.anchor(),
 3590            visible_rows: self.visible_line_count(),
 3591            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3592        }
 3593    }
 3594
 3595    pub fn splice_inlays(
 3596        &self,
 3597        to_remove: Vec<InlayId>,
 3598        to_insert: Vec<Inlay>,
 3599        cx: &mut ViewContext<Self>,
 3600    ) {
 3601        self.display_map.update(cx, |display_map, cx| {
 3602            display_map.splice_inlays(to_remove, to_insert, cx)
 3603        });
 3604        cx.notify();
 3605    }
 3606
 3607    fn trigger_on_type_formatting(
 3608        &self,
 3609        input: String,
 3610        cx: &mut ViewContext<Self>,
 3611    ) -> Option<Task<Result<()>>> {
 3612        if input.len() != 1 {
 3613            return None;
 3614        }
 3615
 3616        let project = self.project.as_ref()?;
 3617        let position = self.selections.newest_anchor().head();
 3618        let (buffer, buffer_position) = self
 3619            .buffer
 3620            .read(cx)
 3621            .text_anchor_for_position(position, cx)?;
 3622
 3623        let settings = language_settings::language_settings(
 3624            buffer
 3625                .read(cx)
 3626                .language_at(buffer_position)
 3627                .map(|l| l.name()),
 3628            buffer.read(cx).file(),
 3629            cx,
 3630        );
 3631        if !settings.use_on_type_format {
 3632            return None;
 3633        }
 3634
 3635        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3636        // hence we do LSP request & edit on host side only — add formats to host's history.
 3637        let push_to_lsp_host_history = true;
 3638        // If this is not the host, append its history with new edits.
 3639        let push_to_client_history = project.read(cx).is_via_collab();
 3640
 3641        let on_type_formatting = project.update(cx, |project, cx| {
 3642            project.on_type_format(
 3643                buffer.clone(),
 3644                buffer_position,
 3645                input,
 3646                push_to_lsp_host_history,
 3647                cx,
 3648            )
 3649        });
 3650        Some(cx.spawn(|editor, mut cx| async move {
 3651            if let Some(transaction) = on_type_formatting.await? {
 3652                if push_to_client_history {
 3653                    buffer
 3654                        .update(&mut cx, |buffer, _| {
 3655                            buffer.push_transaction(transaction, Instant::now());
 3656                        })
 3657                        .ok();
 3658                }
 3659                editor.update(&mut cx, |editor, cx| {
 3660                    editor.refresh_document_highlights(cx);
 3661                })?;
 3662            }
 3663            Ok(())
 3664        }))
 3665    }
 3666
 3667    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3668        if self.pending_rename.is_some() {
 3669            return;
 3670        }
 3671
 3672        let Some(provider) = self.completion_provider.as_ref() else {
 3673            return;
 3674        };
 3675
 3676        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3677            return;
 3678        }
 3679
 3680        let position = self.selections.newest_anchor().head();
 3681        let (buffer, buffer_position) =
 3682            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3683                output
 3684            } else {
 3685                return;
 3686            };
 3687        let show_completion_documentation = buffer
 3688            .read(cx)
 3689            .snapshot()
 3690            .settings_at(buffer_position, cx)
 3691            .show_completion_documentation;
 3692
 3693        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3694
 3695        let trigger_kind = match &options.trigger {
 3696            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3697                CompletionTriggerKind::TRIGGER_CHARACTER
 3698            }
 3699            _ => CompletionTriggerKind::INVOKED,
 3700        };
 3701        let completion_context = CompletionContext {
 3702            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3703                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3704                    Some(String::from(trigger))
 3705                } else {
 3706                    None
 3707                }
 3708            }),
 3709            trigger_kind,
 3710        };
 3711        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3712        let sort_completions = provider.sort_completions();
 3713
 3714        let id = post_inc(&mut self.next_completion_id);
 3715        let task = cx.spawn(|editor, mut cx| {
 3716            async move {
 3717                editor.update(&mut cx, |this, _| {
 3718                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3719                })?;
 3720                let completions = completions.await.log_err();
 3721                let menu = if let Some(completions) = completions {
 3722                    let mut menu = CompletionsMenu::new(
 3723                        id,
 3724                        sort_completions,
 3725                        show_completion_documentation,
 3726                        position,
 3727                        buffer.clone(),
 3728                        completions.into(),
 3729                    );
 3730
 3731                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3732                        .await;
 3733
 3734                    menu.visible().then_some(menu)
 3735                } else {
 3736                    None
 3737                };
 3738
 3739                editor.update(&mut cx, |editor, cx| {
 3740                    match editor.context_menu.borrow().as_ref() {
 3741                        None => {}
 3742                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3743                            if prev_menu.id > id {
 3744                                return;
 3745                            }
 3746                        }
 3747                        _ => return,
 3748                    }
 3749
 3750                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3751                        let mut menu = menu.unwrap();
 3752                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3753
 3754                        if editor.show_inline_completions_in_menu(cx) {
 3755                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3756                                menu.show_inline_completion_hint(hint);
 3757                            }
 3758                        } else {
 3759                            editor.discard_inline_completion(false, cx);
 3760                        }
 3761
 3762                        *editor.context_menu.borrow_mut() =
 3763                            Some(CodeContextMenu::Completions(menu));
 3764
 3765                        cx.notify();
 3766                    } else if editor.completion_tasks.len() <= 1 {
 3767                        // If there are no more completion tasks and the last menu was
 3768                        // empty, we should hide it.
 3769                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3770                        // If it was already hidden and we don't show inline
 3771                        // completions in the menu, we should also show the
 3772                        // inline-completion when available.
 3773                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3774                            editor.update_visible_inline_completion(cx);
 3775                        }
 3776                    }
 3777                })?;
 3778
 3779                Ok::<_, anyhow::Error>(())
 3780            }
 3781            .log_err()
 3782        });
 3783
 3784        self.completion_tasks.push((id, task));
 3785    }
 3786
 3787    pub fn confirm_completion(
 3788        &mut self,
 3789        action: &ConfirmCompletion,
 3790        cx: &mut ViewContext<Self>,
 3791    ) -> Option<Task<Result<()>>> {
 3792        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3793    }
 3794
 3795    pub fn compose_completion(
 3796        &mut self,
 3797        action: &ComposeCompletion,
 3798        cx: &mut ViewContext<Self>,
 3799    ) -> Option<Task<Result<()>>> {
 3800        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3801    }
 3802
 3803    fn do_completion(
 3804        &mut self,
 3805        item_ix: Option<usize>,
 3806        intent: CompletionIntent,
 3807        cx: &mut ViewContext<Editor>,
 3808    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3809        use language::ToOffset as _;
 3810
 3811        let completions_menu =
 3812            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3813                menu
 3814            } else {
 3815                return None;
 3816            };
 3817
 3818        let mat = completions_menu
 3819            .entries
 3820            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3821
 3822        let mat = match mat {
 3823            CompletionEntry::InlineCompletionHint { .. } => {
 3824                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3825                cx.stop_propagation();
 3826                return Some(Task::ready(Ok(())));
 3827            }
 3828            CompletionEntry::Match(mat) => {
 3829                if self.show_inline_completions_in_menu(cx) {
 3830                    self.discard_inline_completion(true, cx);
 3831                }
 3832                mat
 3833            }
 3834        };
 3835
 3836        let buffer_handle = completions_menu.buffer;
 3837        let completion = completions_menu
 3838            .completions
 3839            .borrow()
 3840            .get(mat.candidate_id)?
 3841            .clone();
 3842        cx.stop_propagation();
 3843
 3844        let snippet;
 3845        let text;
 3846
 3847        if completion.is_snippet() {
 3848            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3849            text = snippet.as_ref().unwrap().text.clone();
 3850        } else {
 3851            snippet = None;
 3852            text = completion.new_text.clone();
 3853        };
 3854        let selections = self.selections.all::<usize>(cx);
 3855        let buffer = buffer_handle.read(cx);
 3856        let old_range = completion.old_range.to_offset(buffer);
 3857        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3858
 3859        let newest_selection = self.selections.newest_anchor();
 3860        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3861            return None;
 3862        }
 3863
 3864        let lookbehind = newest_selection
 3865            .start
 3866            .text_anchor
 3867            .to_offset(buffer)
 3868            .saturating_sub(old_range.start);
 3869        let lookahead = old_range
 3870            .end
 3871            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3872        let mut common_prefix_len = old_text
 3873            .bytes()
 3874            .zip(text.bytes())
 3875            .take_while(|(a, b)| a == b)
 3876            .count();
 3877
 3878        let snapshot = self.buffer.read(cx).snapshot(cx);
 3879        let mut range_to_replace: Option<Range<isize>> = None;
 3880        let mut ranges = Vec::new();
 3881        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3882        for selection in &selections {
 3883            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3884                let start = selection.start.saturating_sub(lookbehind);
 3885                let end = selection.end + lookahead;
 3886                if selection.id == newest_selection.id {
 3887                    range_to_replace = Some(
 3888                        ((start + common_prefix_len) as isize - selection.start as isize)
 3889                            ..(end as isize - selection.start as isize),
 3890                    );
 3891                }
 3892                ranges.push(start + common_prefix_len..end);
 3893            } else {
 3894                common_prefix_len = 0;
 3895                ranges.clear();
 3896                ranges.extend(selections.iter().map(|s| {
 3897                    if s.id == newest_selection.id {
 3898                        range_to_replace = Some(
 3899                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3900                                - selection.start as isize
 3901                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3902                                    - selection.start as isize,
 3903                        );
 3904                        old_range.clone()
 3905                    } else {
 3906                        s.start..s.end
 3907                    }
 3908                }));
 3909                break;
 3910            }
 3911            if !self.linked_edit_ranges.is_empty() {
 3912                let start_anchor = snapshot.anchor_before(selection.head());
 3913                let end_anchor = snapshot.anchor_after(selection.tail());
 3914                if let Some(ranges) = self
 3915                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3916                {
 3917                    for (buffer, edits) in ranges {
 3918                        linked_edits.entry(buffer.clone()).or_default().extend(
 3919                            edits
 3920                                .into_iter()
 3921                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3922                        );
 3923                    }
 3924                }
 3925            }
 3926        }
 3927        let text = &text[common_prefix_len..];
 3928
 3929        cx.emit(EditorEvent::InputHandled {
 3930            utf16_range_to_replace: range_to_replace,
 3931            text: text.into(),
 3932        });
 3933
 3934        self.transact(cx, |this, cx| {
 3935            if let Some(mut snippet) = snippet {
 3936                snippet.text = text.to_string();
 3937                for tabstop in snippet
 3938                    .tabstops
 3939                    .iter_mut()
 3940                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3941                {
 3942                    tabstop.start -= common_prefix_len as isize;
 3943                    tabstop.end -= common_prefix_len as isize;
 3944                }
 3945
 3946                this.insert_snippet(&ranges, snippet, cx).log_err();
 3947            } else {
 3948                this.buffer.update(cx, |buffer, cx| {
 3949                    buffer.edit(
 3950                        ranges.iter().map(|range| (range.clone(), text)),
 3951                        this.autoindent_mode.clone(),
 3952                        cx,
 3953                    );
 3954                });
 3955            }
 3956            for (buffer, edits) in linked_edits {
 3957                buffer.update(cx, |buffer, cx| {
 3958                    let snapshot = buffer.snapshot();
 3959                    let edits = edits
 3960                        .into_iter()
 3961                        .map(|(range, text)| {
 3962                            use text::ToPoint as TP;
 3963                            let end_point = TP::to_point(&range.end, &snapshot);
 3964                            let start_point = TP::to_point(&range.start, &snapshot);
 3965                            (start_point..end_point, text)
 3966                        })
 3967                        .sorted_by_key(|(range, _)| range.start)
 3968                        .collect::<Vec<_>>();
 3969                    buffer.edit(edits, None, cx);
 3970                })
 3971            }
 3972
 3973            this.refresh_inline_completion(true, false, cx);
 3974        });
 3975
 3976        let show_new_completions_on_confirm = completion
 3977            .confirm
 3978            .as_ref()
 3979            .map_or(false, |confirm| confirm(intent, cx));
 3980        if show_new_completions_on_confirm {
 3981            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3982        }
 3983
 3984        let provider = self.completion_provider.as_ref()?;
 3985        drop(completion);
 3986        let apply_edits = provider.apply_additional_edits_for_completion(
 3987            buffer_handle,
 3988            completions_menu.completions.clone(),
 3989            mat.candidate_id,
 3990            true,
 3991            cx,
 3992        );
 3993
 3994        let editor_settings = EditorSettings::get_global(cx);
 3995        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3996            // After the code completion is finished, users often want to know what signatures are needed.
 3997            // so we should automatically call signature_help
 3998            self.show_signature_help(&ShowSignatureHelp, cx);
 3999        }
 4000
 4001        Some(cx.foreground_executor().spawn(async move {
 4002            apply_edits.await?;
 4003            Ok(())
 4004        }))
 4005    }
 4006
 4007    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4008        let mut context_menu = self.context_menu.borrow_mut();
 4009        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4010            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4011                // Toggle if we're selecting the same one
 4012                *context_menu = None;
 4013                cx.notify();
 4014                return;
 4015            } else {
 4016                // Otherwise, clear it and start a new one
 4017                *context_menu = None;
 4018                cx.notify();
 4019            }
 4020        }
 4021        drop(context_menu);
 4022        let snapshot = self.snapshot(cx);
 4023        let deployed_from_indicator = action.deployed_from_indicator;
 4024        let mut task = self.code_actions_task.take();
 4025        let action = action.clone();
 4026        cx.spawn(|editor, mut cx| async move {
 4027            while let Some(prev_task) = task {
 4028                prev_task.await.log_err();
 4029                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4030            }
 4031
 4032            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4033                if editor.focus_handle.is_focused(cx) {
 4034                    let multibuffer_point = action
 4035                        .deployed_from_indicator
 4036                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4037                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4038                    let (buffer, buffer_row) = snapshot
 4039                        .buffer_snapshot
 4040                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4041                        .and_then(|(buffer_snapshot, range)| {
 4042                            editor
 4043                                .buffer
 4044                                .read(cx)
 4045                                .buffer(buffer_snapshot.remote_id())
 4046                                .map(|buffer| (buffer, range.start.row))
 4047                        })?;
 4048                    let (_, code_actions) = editor
 4049                        .available_code_actions
 4050                        .clone()
 4051                        .and_then(|(location, code_actions)| {
 4052                            let snapshot = location.buffer.read(cx).snapshot();
 4053                            let point_range = location.range.to_point(&snapshot);
 4054                            let point_range = point_range.start.row..=point_range.end.row;
 4055                            if point_range.contains(&buffer_row) {
 4056                                Some((location, code_actions))
 4057                            } else {
 4058                                None
 4059                            }
 4060                        })
 4061                        .unzip();
 4062                    let buffer_id = buffer.read(cx).remote_id();
 4063                    let tasks = editor
 4064                        .tasks
 4065                        .get(&(buffer_id, buffer_row))
 4066                        .map(|t| Arc::new(t.to_owned()));
 4067                    if tasks.is_none() && code_actions.is_none() {
 4068                        return None;
 4069                    }
 4070
 4071                    editor.completion_tasks.clear();
 4072                    editor.discard_inline_completion(false, cx);
 4073                    let task_context =
 4074                        tasks
 4075                            .as_ref()
 4076                            .zip(editor.project.clone())
 4077                            .map(|(tasks, project)| {
 4078                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4079                            });
 4080
 4081                    Some(cx.spawn(|editor, mut cx| async move {
 4082                        let task_context = match task_context {
 4083                            Some(task_context) => task_context.await,
 4084                            None => None,
 4085                        };
 4086                        let resolved_tasks =
 4087                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4088                                Rc::new(ResolvedTasks {
 4089                                    templates: tasks.resolve(&task_context).collect(),
 4090                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4091                                        multibuffer_point.row,
 4092                                        tasks.column,
 4093                                    )),
 4094                                })
 4095                            });
 4096                        let spawn_straight_away = resolved_tasks
 4097                            .as_ref()
 4098                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4099                            && code_actions
 4100                                .as_ref()
 4101                                .map_or(true, |actions| actions.is_empty());
 4102                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4103                            *editor.context_menu.borrow_mut() =
 4104                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4105                                    buffer,
 4106                                    actions: CodeActionContents {
 4107                                        tasks: resolved_tasks,
 4108                                        actions: code_actions,
 4109                                    },
 4110                                    selected_item: Default::default(),
 4111                                    scroll_handle: UniformListScrollHandle::default(),
 4112                                    deployed_from_indicator,
 4113                                }));
 4114                            if spawn_straight_away {
 4115                                if let Some(task) = editor.confirm_code_action(
 4116                                    &ConfirmCodeAction { item_ix: Some(0) },
 4117                                    cx,
 4118                                ) {
 4119                                    cx.notify();
 4120                                    return task;
 4121                                }
 4122                            }
 4123                            cx.notify();
 4124                            Task::ready(Ok(()))
 4125                        }) {
 4126                            task.await
 4127                        } else {
 4128                            Ok(())
 4129                        }
 4130                    }))
 4131                } else {
 4132                    Some(Task::ready(Ok(())))
 4133                }
 4134            })?;
 4135            if let Some(task) = spawned_test_task {
 4136                task.await?;
 4137            }
 4138
 4139            Ok::<_, anyhow::Error>(())
 4140        })
 4141        .detach_and_log_err(cx);
 4142    }
 4143
 4144    pub fn confirm_code_action(
 4145        &mut self,
 4146        action: &ConfirmCodeAction,
 4147        cx: &mut ViewContext<Self>,
 4148    ) -> Option<Task<Result<()>>> {
 4149        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4150            menu
 4151        } else {
 4152            return None;
 4153        };
 4154        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4155        let action = actions_menu.actions.get(action_ix)?;
 4156        let title = action.label();
 4157        let buffer = actions_menu.buffer;
 4158        let workspace = self.workspace()?;
 4159
 4160        match action {
 4161            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4162                workspace.update(cx, |workspace, cx| {
 4163                    workspace::tasks::schedule_resolved_task(
 4164                        workspace,
 4165                        task_source_kind,
 4166                        resolved_task,
 4167                        false,
 4168                        cx,
 4169                    );
 4170
 4171                    Some(Task::ready(Ok(())))
 4172                })
 4173            }
 4174            CodeActionsItem::CodeAction {
 4175                excerpt_id,
 4176                action,
 4177                provider,
 4178            } => {
 4179                let apply_code_action =
 4180                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4181                let workspace = workspace.downgrade();
 4182                Some(cx.spawn(|editor, cx| async move {
 4183                    let project_transaction = apply_code_action.await?;
 4184                    Self::open_project_transaction(
 4185                        &editor,
 4186                        workspace,
 4187                        project_transaction,
 4188                        title,
 4189                        cx,
 4190                    )
 4191                    .await
 4192                }))
 4193            }
 4194        }
 4195    }
 4196
 4197    pub async fn open_project_transaction(
 4198        this: &WeakView<Editor>,
 4199        workspace: WeakView<Workspace>,
 4200        transaction: ProjectTransaction,
 4201        title: String,
 4202        mut cx: AsyncWindowContext,
 4203    ) -> Result<()> {
 4204        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4205        cx.update(|cx| {
 4206            entries.sort_unstable_by_key(|(buffer, _)| {
 4207                buffer.read(cx).file().map(|f| f.path().clone())
 4208            });
 4209        })?;
 4210
 4211        // If the project transaction's edits are all contained within this editor, then
 4212        // avoid opening a new editor to display them.
 4213
 4214        if let Some((buffer, transaction)) = entries.first() {
 4215            if entries.len() == 1 {
 4216                let excerpt = this.update(&mut cx, |editor, cx| {
 4217                    editor
 4218                        .buffer()
 4219                        .read(cx)
 4220                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4221                })?;
 4222                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4223                    if excerpted_buffer == *buffer {
 4224                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4225                            let excerpt_range = excerpt_range.to_offset(buffer);
 4226                            buffer
 4227                                .edited_ranges_for_transaction::<usize>(transaction)
 4228                                .all(|range| {
 4229                                    excerpt_range.start <= range.start
 4230                                        && excerpt_range.end >= range.end
 4231                                })
 4232                        })?;
 4233
 4234                        if all_edits_within_excerpt {
 4235                            return Ok(());
 4236                        }
 4237                    }
 4238                }
 4239            }
 4240        } else {
 4241            return Ok(());
 4242        }
 4243
 4244        let mut ranges_to_highlight = Vec::new();
 4245        let excerpt_buffer = cx.new_model(|cx| {
 4246            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4247            for (buffer_handle, transaction) in &entries {
 4248                let buffer = buffer_handle.read(cx);
 4249                ranges_to_highlight.extend(
 4250                    multibuffer.push_excerpts_with_context_lines(
 4251                        buffer_handle.clone(),
 4252                        buffer
 4253                            .edited_ranges_for_transaction::<usize>(transaction)
 4254                            .collect(),
 4255                        DEFAULT_MULTIBUFFER_CONTEXT,
 4256                        cx,
 4257                    ),
 4258                );
 4259            }
 4260            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4261            multibuffer
 4262        })?;
 4263
 4264        workspace.update(&mut cx, |workspace, cx| {
 4265            let project = workspace.project().clone();
 4266            let editor =
 4267                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4268            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4269            editor.update(cx, |editor, cx| {
 4270                editor.highlight_background::<Self>(
 4271                    &ranges_to_highlight,
 4272                    |theme| theme.editor_highlighted_line_background,
 4273                    cx,
 4274                );
 4275            });
 4276        })?;
 4277
 4278        Ok(())
 4279    }
 4280
 4281    pub fn clear_code_action_providers(&mut self) {
 4282        self.code_action_providers.clear();
 4283        self.available_code_actions.take();
 4284    }
 4285
 4286    pub fn add_code_action_provider(
 4287        &mut self,
 4288        provider: Rc<dyn CodeActionProvider>,
 4289        cx: &mut ViewContext<Self>,
 4290    ) {
 4291        if self
 4292            .code_action_providers
 4293            .iter()
 4294            .any(|existing_provider| existing_provider.id() == provider.id())
 4295        {
 4296            return;
 4297        }
 4298
 4299        self.code_action_providers.push(provider);
 4300        self.refresh_code_actions(cx);
 4301    }
 4302
 4303    pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
 4304        self.code_action_providers
 4305            .retain(|provider| provider.id() != id);
 4306        self.refresh_code_actions(cx);
 4307    }
 4308
 4309    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4310        let buffer = self.buffer.read(cx);
 4311        let newest_selection = self.selections.newest_anchor().clone();
 4312        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4313        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4314        if start_buffer != end_buffer {
 4315            return None;
 4316        }
 4317
 4318        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4319            cx.background_executor()
 4320                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4321                .await;
 4322
 4323            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4324                let providers = this.code_action_providers.clone();
 4325                let tasks = this
 4326                    .code_action_providers
 4327                    .iter()
 4328                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4329                    .collect::<Vec<_>>();
 4330                (providers, tasks)
 4331            })?;
 4332
 4333            let mut actions = Vec::new();
 4334            for (provider, provider_actions) in
 4335                providers.into_iter().zip(future::join_all(tasks).await)
 4336            {
 4337                if let Some(provider_actions) = provider_actions.log_err() {
 4338                    actions.extend(provider_actions.into_iter().map(|action| {
 4339                        AvailableCodeAction {
 4340                            excerpt_id: newest_selection.start.excerpt_id,
 4341                            action,
 4342                            provider: provider.clone(),
 4343                        }
 4344                    }));
 4345                }
 4346            }
 4347
 4348            this.update(&mut cx, |this, cx| {
 4349                this.available_code_actions = if actions.is_empty() {
 4350                    None
 4351                } else {
 4352                    Some((
 4353                        Location {
 4354                            buffer: start_buffer,
 4355                            range: start..end,
 4356                        },
 4357                        actions.into(),
 4358                    ))
 4359                };
 4360                cx.notify();
 4361            })
 4362        }));
 4363        None
 4364    }
 4365
 4366    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4367        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4368            self.show_git_blame_inline = false;
 4369
 4370            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4371                cx.background_executor().timer(delay).await;
 4372
 4373                this.update(&mut cx, |this, cx| {
 4374                    this.show_git_blame_inline = true;
 4375                    cx.notify();
 4376                })
 4377                .log_err();
 4378            }));
 4379        }
 4380    }
 4381
 4382    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4383        if self.pending_rename.is_some() {
 4384            return None;
 4385        }
 4386
 4387        let provider = self.semantics_provider.clone()?;
 4388        let buffer = self.buffer.read(cx);
 4389        let newest_selection = self.selections.newest_anchor().clone();
 4390        let cursor_position = newest_selection.head();
 4391        let (cursor_buffer, cursor_buffer_position) =
 4392            buffer.text_anchor_for_position(cursor_position, cx)?;
 4393        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4394        if cursor_buffer != tail_buffer {
 4395            return None;
 4396        }
 4397        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4398        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4399            cx.background_executor()
 4400                .timer(Duration::from_millis(debounce))
 4401                .await;
 4402
 4403            let highlights = if let Some(highlights) = cx
 4404                .update(|cx| {
 4405                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4406                })
 4407                .ok()
 4408                .flatten()
 4409            {
 4410                highlights.await.log_err()
 4411            } else {
 4412                None
 4413            };
 4414
 4415            if let Some(highlights) = highlights {
 4416                this.update(&mut cx, |this, cx| {
 4417                    if this.pending_rename.is_some() {
 4418                        return;
 4419                    }
 4420
 4421                    let buffer_id = cursor_position.buffer_id;
 4422                    let buffer = this.buffer.read(cx);
 4423                    if !buffer
 4424                        .text_anchor_for_position(cursor_position, cx)
 4425                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4426                    {
 4427                        return;
 4428                    }
 4429
 4430                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4431                    let mut write_ranges = Vec::new();
 4432                    let mut read_ranges = Vec::new();
 4433                    for highlight in highlights {
 4434                        for (excerpt_id, excerpt_range) in
 4435                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4436                        {
 4437                            let start = highlight
 4438                                .range
 4439                                .start
 4440                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4441                            let end = highlight
 4442                                .range
 4443                                .end
 4444                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4445                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4446                                continue;
 4447                            }
 4448
 4449                            let range = Anchor {
 4450                                buffer_id,
 4451                                excerpt_id,
 4452                                text_anchor: start,
 4453                            }..Anchor {
 4454                                buffer_id,
 4455                                excerpt_id,
 4456                                text_anchor: end,
 4457                            };
 4458                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4459                                write_ranges.push(range);
 4460                            } else {
 4461                                read_ranges.push(range);
 4462                            }
 4463                        }
 4464                    }
 4465
 4466                    this.highlight_background::<DocumentHighlightRead>(
 4467                        &read_ranges,
 4468                        |theme| theme.editor_document_highlight_read_background,
 4469                        cx,
 4470                    );
 4471                    this.highlight_background::<DocumentHighlightWrite>(
 4472                        &write_ranges,
 4473                        |theme| theme.editor_document_highlight_write_background,
 4474                        cx,
 4475                    );
 4476                    cx.notify();
 4477                })
 4478                .log_err();
 4479            }
 4480        }));
 4481        None
 4482    }
 4483
 4484    pub fn refresh_inline_completion(
 4485        &mut self,
 4486        debounce: bool,
 4487        user_requested: bool,
 4488        cx: &mut ViewContext<Self>,
 4489    ) -> Option<()> {
 4490        let provider = self.inline_completion_provider()?;
 4491        let cursor = self.selections.newest_anchor().head();
 4492        let (buffer, cursor_buffer_position) =
 4493            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4494
 4495        if !user_requested
 4496            && (!self.enable_inline_completions
 4497                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4498                || !self.is_focused(cx))
 4499        {
 4500            self.discard_inline_completion(false, cx);
 4501            return None;
 4502        }
 4503
 4504        self.update_visible_inline_completion(cx);
 4505        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4506        Some(())
 4507    }
 4508
 4509    fn cycle_inline_completion(
 4510        &mut self,
 4511        direction: Direction,
 4512        cx: &mut ViewContext<Self>,
 4513    ) -> Option<()> {
 4514        let provider = self.inline_completion_provider()?;
 4515        let cursor = self.selections.newest_anchor().head();
 4516        let (buffer, cursor_buffer_position) =
 4517            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4518        if !self.enable_inline_completions
 4519            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4520        {
 4521            return None;
 4522        }
 4523
 4524        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4525        self.update_visible_inline_completion(cx);
 4526
 4527        Some(())
 4528    }
 4529
 4530    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4531        if !self.has_active_inline_completion() {
 4532            self.refresh_inline_completion(false, true, cx);
 4533            return;
 4534        }
 4535
 4536        self.update_visible_inline_completion(cx);
 4537    }
 4538
 4539    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4540        self.show_cursor_names(cx);
 4541    }
 4542
 4543    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4544        self.show_cursor_names = true;
 4545        cx.notify();
 4546        cx.spawn(|this, mut cx| async move {
 4547            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4548            this.update(&mut cx, |this, cx| {
 4549                this.show_cursor_names = false;
 4550                cx.notify()
 4551            })
 4552            .ok()
 4553        })
 4554        .detach();
 4555    }
 4556
 4557    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4558        if self.has_active_inline_completion() {
 4559            self.cycle_inline_completion(Direction::Next, cx);
 4560        } else {
 4561            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4562            if is_copilot_disabled {
 4563                cx.propagate();
 4564            }
 4565        }
 4566    }
 4567
 4568    pub fn previous_inline_completion(
 4569        &mut self,
 4570        _: &PreviousInlineCompletion,
 4571        cx: &mut ViewContext<Self>,
 4572    ) {
 4573        if self.has_active_inline_completion() {
 4574            self.cycle_inline_completion(Direction::Prev, cx);
 4575        } else {
 4576            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4577            if is_copilot_disabled {
 4578                cx.propagate();
 4579            }
 4580        }
 4581    }
 4582
 4583    pub fn accept_inline_completion(
 4584        &mut self,
 4585        _: &AcceptInlineCompletion,
 4586        cx: &mut ViewContext<Self>,
 4587    ) {
 4588        if self.show_inline_completions_in_menu(cx) {
 4589            self.hide_context_menu(cx);
 4590        }
 4591
 4592        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4593            return;
 4594        };
 4595
 4596        self.report_inline_completion_event(true, cx);
 4597
 4598        match &active_inline_completion.completion {
 4599            InlineCompletion::Move(position) => {
 4600                let position = *position;
 4601                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4602                    selections.select_anchor_ranges([position..position]);
 4603                });
 4604            }
 4605            InlineCompletion::Edit(edits) => {
 4606                if let Some(provider) = self.inline_completion_provider() {
 4607                    provider.accept(cx);
 4608                }
 4609
 4610                let snapshot = self.buffer.read(cx).snapshot(cx);
 4611                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4612
 4613                self.buffer.update(cx, |buffer, cx| {
 4614                    buffer.edit(edits.iter().cloned(), None, cx)
 4615                });
 4616
 4617                self.change_selections(None, cx, |s| {
 4618                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4619                });
 4620
 4621                self.update_visible_inline_completion(cx);
 4622                if self.active_inline_completion.is_none() {
 4623                    self.refresh_inline_completion(true, true, cx);
 4624                }
 4625
 4626                cx.notify();
 4627            }
 4628        }
 4629    }
 4630
 4631    pub fn accept_partial_inline_completion(
 4632        &mut self,
 4633        _: &AcceptPartialInlineCompletion,
 4634        cx: &mut ViewContext<Self>,
 4635    ) {
 4636        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4637            return;
 4638        };
 4639        if self.selections.count() != 1 {
 4640            return;
 4641        }
 4642
 4643        self.report_inline_completion_event(true, cx);
 4644
 4645        match &active_inline_completion.completion {
 4646            InlineCompletion::Move(position) => {
 4647                let position = *position;
 4648                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4649                    selections.select_anchor_ranges([position..position]);
 4650                });
 4651            }
 4652            InlineCompletion::Edit(edits) => {
 4653                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4654                    let text = edits[0].1.as_str();
 4655                    let mut partial_completion = text
 4656                        .chars()
 4657                        .by_ref()
 4658                        .take_while(|c| c.is_alphabetic())
 4659                        .collect::<String>();
 4660                    if partial_completion.is_empty() {
 4661                        partial_completion = text
 4662                            .chars()
 4663                            .by_ref()
 4664                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4665                            .collect::<String>();
 4666                    }
 4667
 4668                    cx.emit(EditorEvent::InputHandled {
 4669                        utf16_range_to_replace: None,
 4670                        text: partial_completion.clone().into(),
 4671                    });
 4672
 4673                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4674
 4675                    self.refresh_inline_completion(true, true, cx);
 4676                    cx.notify();
 4677                }
 4678            }
 4679        }
 4680    }
 4681
 4682    fn discard_inline_completion(
 4683        &mut self,
 4684        should_report_inline_completion_event: bool,
 4685        cx: &mut ViewContext<Self>,
 4686    ) -> bool {
 4687        if should_report_inline_completion_event {
 4688            self.report_inline_completion_event(false, cx);
 4689        }
 4690
 4691        if let Some(provider) = self.inline_completion_provider() {
 4692            provider.discard(cx);
 4693        }
 4694
 4695        self.take_active_inline_completion(cx).is_some()
 4696    }
 4697
 4698    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4699        let Some(provider) = self.inline_completion_provider() else {
 4700            return;
 4701        };
 4702        let Some(project) = self.project.as_ref() else {
 4703            return;
 4704        };
 4705        let Some((_, buffer, _)) = self
 4706            .buffer
 4707            .read(cx)
 4708            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4709        else {
 4710            return;
 4711        };
 4712
 4713        let project = project.read(cx);
 4714        let extension = buffer
 4715            .read(cx)
 4716            .file()
 4717            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4718        project.client().telemetry().report_inline_completion_event(
 4719            provider.name().into(),
 4720            accepted,
 4721            extension,
 4722        );
 4723    }
 4724
 4725    pub fn has_active_inline_completion(&self) -> bool {
 4726        self.active_inline_completion.is_some()
 4727    }
 4728
 4729    fn take_active_inline_completion(
 4730        &mut self,
 4731        cx: &mut ViewContext<Self>,
 4732    ) -> Option<InlineCompletion> {
 4733        let active_inline_completion = self.active_inline_completion.take()?;
 4734        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4735        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4736        Some(active_inline_completion.completion)
 4737    }
 4738
 4739    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4740        let selection = self.selections.newest_anchor();
 4741        let cursor = selection.head();
 4742        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4743        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4744        let excerpt_id = cursor.excerpt_id;
 4745
 4746        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4747            && (self.context_menu.borrow().is_some()
 4748                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4749        if completions_menu_has_precedence
 4750            || !offset_selection.is_empty()
 4751            || self
 4752                .active_inline_completion
 4753                .as_ref()
 4754                .map_or(false, |completion| {
 4755                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4756                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4757                    !invalidation_range.contains(&offset_selection.head())
 4758                })
 4759        {
 4760            self.discard_inline_completion(false, cx);
 4761            return None;
 4762        }
 4763
 4764        self.take_active_inline_completion(cx);
 4765        let provider = self.inline_completion_provider()?;
 4766
 4767        let (buffer, cursor_buffer_position) =
 4768            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4769
 4770        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4771        let edits = completion
 4772            .edits
 4773            .into_iter()
 4774            .flat_map(|(range, new_text)| {
 4775                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4776                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4777                Some((start..end, new_text))
 4778            })
 4779            .collect::<Vec<_>>();
 4780        if edits.is_empty() {
 4781            return None;
 4782        }
 4783
 4784        let first_edit_start = edits.first().unwrap().0.start;
 4785        let edit_start_row = first_edit_start
 4786            .to_point(&multibuffer)
 4787            .row
 4788            .saturating_sub(2);
 4789
 4790        let last_edit_end = edits.last().unwrap().0.end;
 4791        let edit_end_row = cmp::min(
 4792            multibuffer.max_point().row,
 4793            last_edit_end.to_point(&multibuffer).row + 2,
 4794        );
 4795
 4796        let cursor_row = cursor.to_point(&multibuffer).row;
 4797
 4798        let mut inlay_ids = Vec::new();
 4799        let invalidation_row_range;
 4800        let completion;
 4801        if cursor_row < edit_start_row {
 4802            invalidation_row_range = cursor_row..edit_end_row;
 4803            completion = InlineCompletion::Move(first_edit_start);
 4804        } else if cursor_row > edit_end_row {
 4805            invalidation_row_range = edit_start_row..cursor_row;
 4806            completion = InlineCompletion::Move(first_edit_start);
 4807        } else {
 4808            if edits
 4809                .iter()
 4810                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4811            {
 4812                let mut inlays = Vec::new();
 4813                for (range, new_text) in &edits {
 4814                    let inlay = Inlay::inline_completion(
 4815                        post_inc(&mut self.next_inlay_id),
 4816                        range.start,
 4817                        new_text.as_str(),
 4818                    );
 4819                    inlay_ids.push(inlay.id);
 4820                    inlays.push(inlay);
 4821                }
 4822
 4823                self.splice_inlays(vec![], inlays, cx);
 4824            } else {
 4825                let background_color = cx.theme().status().deleted_background;
 4826                self.highlight_text::<InlineCompletionHighlight>(
 4827                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4828                    HighlightStyle {
 4829                        background_color: Some(background_color),
 4830                        ..Default::default()
 4831                    },
 4832                    cx,
 4833                );
 4834            }
 4835
 4836            invalidation_row_range = edit_start_row..edit_end_row;
 4837            completion = InlineCompletion::Edit(edits);
 4838        };
 4839
 4840        let invalidation_range = multibuffer
 4841            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4842            ..multibuffer.anchor_after(Point::new(
 4843                invalidation_row_range.end,
 4844                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4845            ));
 4846
 4847        self.active_inline_completion = Some(InlineCompletionState {
 4848            inlay_ids,
 4849            completion,
 4850            invalidation_range,
 4851        });
 4852
 4853        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4854            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4855                match self.context_menu.borrow_mut().as_mut() {
 4856                    Some(CodeContextMenu::Completions(menu)) => {
 4857                        menu.show_inline_completion_hint(hint);
 4858                    }
 4859                    _ => {}
 4860                }
 4861            }
 4862        }
 4863
 4864        cx.notify();
 4865
 4866        Some(())
 4867    }
 4868
 4869    fn inline_completion_menu_hint(
 4870        &mut self,
 4871        cx: &mut ViewContext<Self>,
 4872    ) -> Option<InlineCompletionMenuHint> {
 4873        if self.has_active_inline_completion() {
 4874            let provider_name = self.inline_completion_provider()?.display_name();
 4875            let editor_snapshot = self.snapshot(cx);
 4876
 4877            let text = match &self.active_inline_completion.as_ref()?.completion {
 4878                InlineCompletion::Edit(edits) => {
 4879                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4880                }
 4881                InlineCompletion::Move(target) => {
 4882                    let target_point =
 4883                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4884                    let target_line = target_point.row + 1;
 4885                    InlineCompletionText::Move(
 4886                        format!("Jump to edit in line {}", target_line).into(),
 4887                    )
 4888                }
 4889            };
 4890
 4891            Some(InlineCompletionMenuHint {
 4892                provider_name,
 4893                text,
 4894            })
 4895        } else {
 4896            None
 4897        }
 4898    }
 4899
 4900    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4901        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4902    }
 4903
 4904    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4905        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4906            && self
 4907                .inline_completion_provider()
 4908                .map_or(false, |provider| provider.show_completions_in_menu())
 4909    }
 4910
 4911    fn render_code_actions_indicator(
 4912        &self,
 4913        _style: &EditorStyle,
 4914        row: DisplayRow,
 4915        is_active: bool,
 4916        cx: &mut ViewContext<Self>,
 4917    ) -> Option<IconButton> {
 4918        if self.available_code_actions.is_some() {
 4919            Some(
 4920                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4921                    .shape(ui::IconButtonShape::Square)
 4922                    .icon_size(IconSize::XSmall)
 4923                    .icon_color(Color::Muted)
 4924                    .toggle_state(is_active)
 4925                    .tooltip({
 4926                        let focus_handle = self.focus_handle.clone();
 4927                        move |cx| {
 4928                            Tooltip::for_action_in(
 4929                                "Toggle Code Actions",
 4930                                &ToggleCodeActions {
 4931                                    deployed_from_indicator: None,
 4932                                },
 4933                                &focus_handle,
 4934                                cx,
 4935                            )
 4936                        }
 4937                    })
 4938                    .on_click(cx.listener(move |editor, _e, cx| {
 4939                        editor.focus(cx);
 4940                        editor.toggle_code_actions(
 4941                            &ToggleCodeActions {
 4942                                deployed_from_indicator: Some(row),
 4943                            },
 4944                            cx,
 4945                        );
 4946                    })),
 4947            )
 4948        } else {
 4949            None
 4950        }
 4951    }
 4952
 4953    fn clear_tasks(&mut self) {
 4954        self.tasks.clear()
 4955    }
 4956
 4957    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4958        if self.tasks.insert(key, value).is_some() {
 4959            // This case should hopefully be rare, but just in case...
 4960            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4961        }
 4962    }
 4963
 4964    fn build_tasks_context(
 4965        project: &Model<Project>,
 4966        buffer: &Model<Buffer>,
 4967        buffer_row: u32,
 4968        tasks: &Arc<RunnableTasks>,
 4969        cx: &mut ViewContext<Self>,
 4970    ) -> Task<Option<task::TaskContext>> {
 4971        let position = Point::new(buffer_row, tasks.column);
 4972        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4973        let location = Location {
 4974            buffer: buffer.clone(),
 4975            range: range_start..range_start,
 4976        };
 4977        // Fill in the environmental variables from the tree-sitter captures
 4978        let mut captured_task_variables = TaskVariables::default();
 4979        for (capture_name, value) in tasks.extra_variables.clone() {
 4980            captured_task_variables.insert(
 4981                task::VariableName::Custom(capture_name.into()),
 4982                value.clone(),
 4983            );
 4984        }
 4985        project.update(cx, |project, cx| {
 4986            project.task_store().update(cx, |task_store, cx| {
 4987                task_store.task_context_for_location(captured_task_variables, location, cx)
 4988            })
 4989        })
 4990    }
 4991
 4992    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4993        let Some((workspace, _)) = self.workspace.clone() else {
 4994            return;
 4995        };
 4996        let Some(project) = self.project.clone() else {
 4997            return;
 4998        };
 4999
 5000        // Try to find a closest, enclosing node using tree-sitter that has a
 5001        // task
 5002        let Some((buffer, buffer_row, tasks)) = self
 5003            .find_enclosing_node_task(cx)
 5004            // Or find the task that's closest in row-distance.
 5005            .or_else(|| self.find_closest_task(cx))
 5006        else {
 5007            return;
 5008        };
 5009
 5010        let reveal_strategy = action.reveal;
 5011        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5012        cx.spawn(|_, mut cx| async move {
 5013            let context = task_context.await?;
 5014            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5015
 5016            let resolved = resolved_task.resolved.as_mut()?;
 5017            resolved.reveal = reveal_strategy;
 5018
 5019            workspace
 5020                .update(&mut cx, |workspace, cx| {
 5021                    workspace::tasks::schedule_resolved_task(
 5022                        workspace,
 5023                        task_source_kind,
 5024                        resolved_task,
 5025                        false,
 5026                        cx,
 5027                    );
 5028                })
 5029                .ok()
 5030        })
 5031        .detach();
 5032    }
 5033
 5034    fn find_closest_task(
 5035        &mut self,
 5036        cx: &mut ViewContext<Self>,
 5037    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5038        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5039
 5040        let ((buffer_id, row), tasks) = self
 5041            .tasks
 5042            .iter()
 5043            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5044
 5045        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5046        let tasks = Arc::new(tasks.to_owned());
 5047        Some((buffer, *row, tasks))
 5048    }
 5049
 5050    fn find_enclosing_node_task(
 5051        &mut self,
 5052        cx: &mut ViewContext<Self>,
 5053    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5054        let snapshot = self.buffer.read(cx).snapshot(cx);
 5055        let offset = self.selections.newest::<usize>(cx).head();
 5056        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5057        let buffer_id = excerpt.buffer().remote_id();
 5058
 5059        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5060        let mut cursor = layer.node().walk();
 5061
 5062        while cursor.goto_first_child_for_byte(offset).is_some() {
 5063            if cursor.node().end_byte() == offset {
 5064                cursor.goto_next_sibling();
 5065            }
 5066        }
 5067
 5068        // Ascend to the smallest ancestor that contains the range and has a task.
 5069        loop {
 5070            let node = cursor.node();
 5071            let node_range = node.byte_range();
 5072            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5073
 5074            // Check if this node contains our offset
 5075            if node_range.start <= offset && node_range.end >= offset {
 5076                // If it contains offset, check for task
 5077                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5078                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5079                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5080                }
 5081            }
 5082
 5083            if !cursor.goto_parent() {
 5084                break;
 5085            }
 5086        }
 5087        None
 5088    }
 5089
 5090    fn render_run_indicator(
 5091        &self,
 5092        _style: &EditorStyle,
 5093        is_active: bool,
 5094        row: DisplayRow,
 5095        cx: &mut ViewContext<Self>,
 5096    ) -> IconButton {
 5097        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5098            .shape(ui::IconButtonShape::Square)
 5099            .icon_size(IconSize::XSmall)
 5100            .icon_color(Color::Muted)
 5101            .toggle_state(is_active)
 5102            .on_click(cx.listener(move |editor, _e, cx| {
 5103                editor.focus(cx);
 5104                editor.toggle_code_actions(
 5105                    &ToggleCodeActions {
 5106                        deployed_from_indicator: Some(row),
 5107                    },
 5108                    cx,
 5109                );
 5110            }))
 5111    }
 5112
 5113    #[cfg(any(feature = "test-support", test))]
 5114    pub fn context_menu_visible(&self) -> bool {
 5115        self.context_menu
 5116            .borrow()
 5117            .as_ref()
 5118            .map_or(false, |menu| menu.visible())
 5119    }
 5120
 5121    #[cfg(feature = "test-support")]
 5122    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5123        self.context_menu
 5124            .borrow()
 5125            .as_ref()
 5126            .map_or(false, |menu| match menu {
 5127                CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
 5128                    matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5129                }),
 5130                CodeContextMenu::CodeActions(_) => false,
 5131            })
 5132    }
 5133
 5134    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5135        self.context_menu
 5136            .borrow()
 5137            .as_ref()
 5138            .map(|menu| menu.origin(cursor_position))
 5139    }
 5140
 5141    fn render_context_menu(
 5142        &self,
 5143        style: &EditorStyle,
 5144        max_height_in_lines: u32,
 5145        cx: &mut ViewContext<Editor>,
 5146    ) -> Option<AnyElement> {
 5147        self.context_menu.borrow().as_ref().and_then(|menu| {
 5148            if menu.visible() {
 5149                Some(menu.render(style, max_height_in_lines, cx))
 5150            } else {
 5151                None
 5152            }
 5153        })
 5154    }
 5155
 5156    fn render_context_menu_aside(
 5157        &self,
 5158        style: &EditorStyle,
 5159        max_size: Size<Pixels>,
 5160        cx: &mut ViewContext<Editor>,
 5161    ) -> Option<AnyElement> {
 5162        self.context_menu.borrow().as_ref().and_then(|menu| {
 5163            if menu.visible() {
 5164                menu.render_aside(
 5165                    style,
 5166                    max_size,
 5167                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5168                    cx,
 5169                )
 5170            } else {
 5171                None
 5172            }
 5173        })
 5174    }
 5175
 5176    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5177        cx.notify();
 5178        self.completion_tasks.clear();
 5179        let context_menu = self.context_menu.borrow_mut().take();
 5180        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5181            self.update_visible_inline_completion(cx);
 5182        }
 5183        context_menu
 5184    }
 5185
 5186    fn show_snippet_choices(
 5187        &mut self,
 5188        choices: &Vec<String>,
 5189        selection: Range<Anchor>,
 5190        cx: &mut ViewContext<Self>,
 5191    ) {
 5192        if selection.start.buffer_id.is_none() {
 5193            return;
 5194        }
 5195        let buffer_id = selection.start.buffer_id.unwrap();
 5196        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5197        let id = post_inc(&mut self.next_completion_id);
 5198
 5199        if let Some(buffer) = buffer {
 5200            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5201                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5202            ));
 5203        }
 5204    }
 5205
 5206    pub fn insert_snippet(
 5207        &mut self,
 5208        insertion_ranges: &[Range<usize>],
 5209        snippet: Snippet,
 5210        cx: &mut ViewContext<Self>,
 5211    ) -> Result<()> {
 5212        struct Tabstop<T> {
 5213            is_end_tabstop: bool,
 5214            ranges: Vec<Range<T>>,
 5215            choices: Option<Vec<String>>,
 5216        }
 5217
 5218        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5219            let snippet_text: Arc<str> = snippet.text.clone().into();
 5220            buffer.edit(
 5221                insertion_ranges
 5222                    .iter()
 5223                    .cloned()
 5224                    .map(|range| (range, snippet_text.clone())),
 5225                Some(AutoindentMode::EachLine),
 5226                cx,
 5227            );
 5228
 5229            let snapshot = &*buffer.read(cx);
 5230            let snippet = &snippet;
 5231            snippet
 5232                .tabstops
 5233                .iter()
 5234                .map(|tabstop| {
 5235                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5236                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5237                    });
 5238                    let mut tabstop_ranges = tabstop
 5239                        .ranges
 5240                        .iter()
 5241                        .flat_map(|tabstop_range| {
 5242                            let mut delta = 0_isize;
 5243                            insertion_ranges.iter().map(move |insertion_range| {
 5244                                let insertion_start = insertion_range.start as isize + delta;
 5245                                delta +=
 5246                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5247
 5248                                let start = ((insertion_start + tabstop_range.start) as usize)
 5249                                    .min(snapshot.len());
 5250                                let end = ((insertion_start + tabstop_range.end) as usize)
 5251                                    .min(snapshot.len());
 5252                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5253                            })
 5254                        })
 5255                        .collect::<Vec<_>>();
 5256                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5257
 5258                    Tabstop {
 5259                        is_end_tabstop,
 5260                        ranges: tabstop_ranges,
 5261                        choices: tabstop.choices.clone(),
 5262                    }
 5263                })
 5264                .collect::<Vec<_>>()
 5265        });
 5266        if let Some(tabstop) = tabstops.first() {
 5267            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5268                s.select_ranges(tabstop.ranges.iter().cloned());
 5269            });
 5270
 5271            if let Some(choices) = &tabstop.choices {
 5272                if let Some(selection) = tabstop.ranges.first() {
 5273                    self.show_snippet_choices(choices, selection.clone(), cx)
 5274                }
 5275            }
 5276
 5277            // If we're already at the last tabstop and it's at the end of the snippet,
 5278            // we're done, we don't need to keep the state around.
 5279            if !tabstop.is_end_tabstop {
 5280                let choices = tabstops
 5281                    .iter()
 5282                    .map(|tabstop| tabstop.choices.clone())
 5283                    .collect();
 5284
 5285                let ranges = tabstops
 5286                    .into_iter()
 5287                    .map(|tabstop| tabstop.ranges)
 5288                    .collect::<Vec<_>>();
 5289
 5290                self.snippet_stack.push(SnippetState {
 5291                    active_index: 0,
 5292                    ranges,
 5293                    choices,
 5294                });
 5295            }
 5296
 5297            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5298            if self.autoclose_regions.is_empty() {
 5299                let snapshot = self.buffer.read(cx).snapshot(cx);
 5300                for selection in &mut self.selections.all::<Point>(cx) {
 5301                    let selection_head = selection.head();
 5302                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5303                        continue;
 5304                    };
 5305
 5306                    let mut bracket_pair = None;
 5307                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5308                    let prev_chars = snapshot
 5309                        .reversed_chars_at(selection_head)
 5310                        .collect::<String>();
 5311                    for (pair, enabled) in scope.brackets() {
 5312                        if enabled
 5313                            && pair.close
 5314                            && prev_chars.starts_with(pair.start.as_str())
 5315                            && next_chars.starts_with(pair.end.as_str())
 5316                        {
 5317                            bracket_pair = Some(pair.clone());
 5318                            break;
 5319                        }
 5320                    }
 5321                    if let Some(pair) = bracket_pair {
 5322                        let start = snapshot.anchor_after(selection_head);
 5323                        let end = snapshot.anchor_after(selection_head);
 5324                        self.autoclose_regions.push(AutocloseRegion {
 5325                            selection_id: selection.id,
 5326                            range: start..end,
 5327                            pair,
 5328                        });
 5329                    }
 5330                }
 5331            }
 5332        }
 5333        Ok(())
 5334    }
 5335
 5336    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5337        self.move_to_snippet_tabstop(Bias::Right, cx)
 5338    }
 5339
 5340    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5341        self.move_to_snippet_tabstop(Bias::Left, cx)
 5342    }
 5343
 5344    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5345        if let Some(mut snippet) = self.snippet_stack.pop() {
 5346            match bias {
 5347                Bias::Left => {
 5348                    if snippet.active_index > 0 {
 5349                        snippet.active_index -= 1;
 5350                    } else {
 5351                        self.snippet_stack.push(snippet);
 5352                        return false;
 5353                    }
 5354                }
 5355                Bias::Right => {
 5356                    if snippet.active_index + 1 < snippet.ranges.len() {
 5357                        snippet.active_index += 1;
 5358                    } else {
 5359                        self.snippet_stack.push(snippet);
 5360                        return false;
 5361                    }
 5362                }
 5363            }
 5364            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5365                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5366                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5367                });
 5368
 5369                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5370                    if let Some(selection) = current_ranges.first() {
 5371                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5372                    }
 5373                }
 5374
 5375                // If snippet state is not at the last tabstop, push it back on the stack
 5376                if snippet.active_index + 1 < snippet.ranges.len() {
 5377                    self.snippet_stack.push(snippet);
 5378                }
 5379                return true;
 5380            }
 5381        }
 5382
 5383        false
 5384    }
 5385
 5386    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5387        self.transact(cx, |this, cx| {
 5388            this.select_all(&SelectAll, cx);
 5389            this.insert("", cx);
 5390        });
 5391    }
 5392
 5393    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5394        self.transact(cx, |this, cx| {
 5395            this.select_autoclose_pair(cx);
 5396            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5397            if !this.linked_edit_ranges.is_empty() {
 5398                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5399                let snapshot = this.buffer.read(cx).snapshot(cx);
 5400
 5401                for selection in selections.iter() {
 5402                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5403                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5404                    if selection_start.buffer_id != selection_end.buffer_id {
 5405                        continue;
 5406                    }
 5407                    if let Some(ranges) =
 5408                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5409                    {
 5410                        for (buffer, entries) in ranges {
 5411                            linked_ranges.entry(buffer).or_default().extend(entries);
 5412                        }
 5413                    }
 5414                }
 5415            }
 5416
 5417            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5418            if !this.selections.line_mode {
 5419                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5420                for selection in &mut selections {
 5421                    if selection.is_empty() {
 5422                        let old_head = selection.head();
 5423                        let mut new_head =
 5424                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5425                                .to_point(&display_map);
 5426                        if let Some((buffer, line_buffer_range)) = display_map
 5427                            .buffer_snapshot
 5428                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5429                        {
 5430                            let indent_size =
 5431                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5432                            let indent_len = match indent_size.kind {
 5433                                IndentKind::Space => {
 5434                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5435                                }
 5436                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5437                            };
 5438                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5439                                let indent_len = indent_len.get();
 5440                                new_head = cmp::min(
 5441                                    new_head,
 5442                                    MultiBufferPoint::new(
 5443                                        old_head.row,
 5444                                        ((old_head.column - 1) / indent_len) * indent_len,
 5445                                    ),
 5446                                );
 5447                            }
 5448                        }
 5449
 5450                        selection.set_head(new_head, SelectionGoal::None);
 5451                    }
 5452                }
 5453            }
 5454
 5455            this.signature_help_state.set_backspace_pressed(true);
 5456            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5457            this.insert("", cx);
 5458            let empty_str: Arc<str> = Arc::from("");
 5459            for (buffer, edits) in linked_ranges {
 5460                let snapshot = buffer.read(cx).snapshot();
 5461                use text::ToPoint as TP;
 5462
 5463                let edits = edits
 5464                    .into_iter()
 5465                    .map(|range| {
 5466                        let end_point = TP::to_point(&range.end, &snapshot);
 5467                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5468
 5469                        if end_point == start_point {
 5470                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5471                                .saturating_sub(1);
 5472                            start_point =
 5473                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5474                        };
 5475
 5476                        (start_point..end_point, empty_str.clone())
 5477                    })
 5478                    .sorted_by_key(|(range, _)| range.start)
 5479                    .collect::<Vec<_>>();
 5480                buffer.update(cx, |this, cx| {
 5481                    this.edit(edits, None, cx);
 5482                })
 5483            }
 5484            this.refresh_inline_completion(true, false, cx);
 5485            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5486        });
 5487    }
 5488
 5489    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5490        self.transact(cx, |this, cx| {
 5491            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5492                let line_mode = s.line_mode;
 5493                s.move_with(|map, selection| {
 5494                    if selection.is_empty() && !line_mode {
 5495                        let cursor = movement::right(map, selection.head());
 5496                        selection.end = cursor;
 5497                        selection.reversed = true;
 5498                        selection.goal = SelectionGoal::None;
 5499                    }
 5500                })
 5501            });
 5502            this.insert("", cx);
 5503            this.refresh_inline_completion(true, false, cx);
 5504        });
 5505    }
 5506
 5507    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5508        if self.move_to_prev_snippet_tabstop(cx) {
 5509            return;
 5510        }
 5511
 5512        self.outdent(&Outdent, cx);
 5513    }
 5514
 5515    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5516        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5517            return;
 5518        }
 5519
 5520        let mut selections = self.selections.all_adjusted(cx);
 5521        let buffer = self.buffer.read(cx);
 5522        let snapshot = buffer.snapshot(cx);
 5523        let rows_iter = selections.iter().map(|s| s.head().row);
 5524        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5525
 5526        let mut edits = Vec::new();
 5527        let mut prev_edited_row = 0;
 5528        let mut row_delta = 0;
 5529        for selection in &mut selections {
 5530            if selection.start.row != prev_edited_row {
 5531                row_delta = 0;
 5532            }
 5533            prev_edited_row = selection.end.row;
 5534
 5535            // If the selection is non-empty, then increase the indentation of the selected lines.
 5536            if !selection.is_empty() {
 5537                row_delta =
 5538                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5539                continue;
 5540            }
 5541
 5542            // If the selection is empty and the cursor is in the leading whitespace before the
 5543            // suggested indentation, then auto-indent the line.
 5544            let cursor = selection.head();
 5545            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5546            if let Some(suggested_indent) =
 5547                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5548            {
 5549                if cursor.column < suggested_indent.len
 5550                    && cursor.column <= current_indent.len
 5551                    && current_indent.len <= suggested_indent.len
 5552                {
 5553                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5554                    selection.end = selection.start;
 5555                    if row_delta == 0 {
 5556                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5557                            cursor.row,
 5558                            current_indent,
 5559                            suggested_indent,
 5560                        ));
 5561                        row_delta = suggested_indent.len - current_indent.len;
 5562                    }
 5563                    continue;
 5564                }
 5565            }
 5566
 5567            // Otherwise, insert a hard or soft tab.
 5568            let settings = buffer.settings_at(cursor, cx);
 5569            let tab_size = if settings.hard_tabs {
 5570                IndentSize::tab()
 5571            } else {
 5572                let tab_size = settings.tab_size.get();
 5573                let char_column = snapshot
 5574                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5575                    .flat_map(str::chars)
 5576                    .count()
 5577                    + row_delta as usize;
 5578                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5579                IndentSize::spaces(chars_to_next_tab_stop)
 5580            };
 5581            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5582            selection.end = selection.start;
 5583            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5584            row_delta += tab_size.len;
 5585        }
 5586
 5587        self.transact(cx, |this, cx| {
 5588            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5589            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5590            this.refresh_inline_completion(true, false, cx);
 5591        });
 5592    }
 5593
 5594    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5595        if self.read_only(cx) {
 5596            return;
 5597        }
 5598        let mut selections = self.selections.all::<Point>(cx);
 5599        let mut prev_edited_row = 0;
 5600        let mut row_delta = 0;
 5601        let mut edits = Vec::new();
 5602        let buffer = self.buffer.read(cx);
 5603        let snapshot = buffer.snapshot(cx);
 5604        for selection in &mut selections {
 5605            if selection.start.row != prev_edited_row {
 5606                row_delta = 0;
 5607            }
 5608            prev_edited_row = selection.end.row;
 5609
 5610            row_delta =
 5611                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5612        }
 5613
 5614        self.transact(cx, |this, cx| {
 5615            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5616            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5617        });
 5618    }
 5619
 5620    fn indent_selection(
 5621        buffer: &MultiBuffer,
 5622        snapshot: &MultiBufferSnapshot,
 5623        selection: &mut Selection<Point>,
 5624        edits: &mut Vec<(Range<Point>, String)>,
 5625        delta_for_start_row: u32,
 5626        cx: &AppContext,
 5627    ) -> u32 {
 5628        let settings = buffer.settings_at(selection.start, cx);
 5629        let tab_size = settings.tab_size.get();
 5630        let indent_kind = if settings.hard_tabs {
 5631            IndentKind::Tab
 5632        } else {
 5633            IndentKind::Space
 5634        };
 5635        let mut start_row = selection.start.row;
 5636        let mut end_row = selection.end.row + 1;
 5637
 5638        // If a selection ends at the beginning of a line, don't indent
 5639        // that last line.
 5640        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5641            end_row -= 1;
 5642        }
 5643
 5644        // Avoid re-indenting a row that has already been indented by a
 5645        // previous selection, but still update this selection's column
 5646        // to reflect that indentation.
 5647        if delta_for_start_row > 0 {
 5648            start_row += 1;
 5649            selection.start.column += delta_for_start_row;
 5650            if selection.end.row == selection.start.row {
 5651                selection.end.column += delta_for_start_row;
 5652            }
 5653        }
 5654
 5655        let mut delta_for_end_row = 0;
 5656        let has_multiple_rows = start_row + 1 != end_row;
 5657        for row in start_row..end_row {
 5658            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5659            let indent_delta = match (current_indent.kind, indent_kind) {
 5660                (IndentKind::Space, IndentKind::Space) => {
 5661                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5662                    IndentSize::spaces(columns_to_next_tab_stop)
 5663                }
 5664                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5665                (_, IndentKind::Tab) => IndentSize::tab(),
 5666            };
 5667
 5668            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5669                0
 5670            } else {
 5671                selection.start.column
 5672            };
 5673            let row_start = Point::new(row, start);
 5674            edits.push((
 5675                row_start..row_start,
 5676                indent_delta.chars().collect::<String>(),
 5677            ));
 5678
 5679            // Update this selection's endpoints to reflect the indentation.
 5680            if row == selection.start.row {
 5681                selection.start.column += indent_delta.len;
 5682            }
 5683            if row == selection.end.row {
 5684                selection.end.column += indent_delta.len;
 5685                delta_for_end_row = indent_delta.len;
 5686            }
 5687        }
 5688
 5689        if selection.start.row == selection.end.row {
 5690            delta_for_start_row + delta_for_end_row
 5691        } else {
 5692            delta_for_end_row
 5693        }
 5694    }
 5695
 5696    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5697        if self.read_only(cx) {
 5698            return;
 5699        }
 5700        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5701        let selections = self.selections.all::<Point>(cx);
 5702        let mut deletion_ranges = Vec::new();
 5703        let mut last_outdent = None;
 5704        {
 5705            let buffer = self.buffer.read(cx);
 5706            let snapshot = buffer.snapshot(cx);
 5707            for selection in &selections {
 5708                let settings = buffer.settings_at(selection.start, cx);
 5709                let tab_size = settings.tab_size.get();
 5710                let mut rows = selection.spanned_rows(false, &display_map);
 5711
 5712                // Avoid re-outdenting a row that has already been outdented by a
 5713                // previous selection.
 5714                if let Some(last_row) = last_outdent {
 5715                    if last_row == rows.start {
 5716                        rows.start = rows.start.next_row();
 5717                    }
 5718                }
 5719                let has_multiple_rows = rows.len() > 1;
 5720                for row in rows.iter_rows() {
 5721                    let indent_size = snapshot.indent_size_for_line(row);
 5722                    if indent_size.len > 0 {
 5723                        let deletion_len = match indent_size.kind {
 5724                            IndentKind::Space => {
 5725                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5726                                if columns_to_prev_tab_stop == 0 {
 5727                                    tab_size
 5728                                } else {
 5729                                    columns_to_prev_tab_stop
 5730                                }
 5731                            }
 5732                            IndentKind::Tab => 1,
 5733                        };
 5734                        let start = if has_multiple_rows
 5735                            || deletion_len > selection.start.column
 5736                            || indent_size.len < selection.start.column
 5737                        {
 5738                            0
 5739                        } else {
 5740                            selection.start.column - deletion_len
 5741                        };
 5742                        deletion_ranges.push(
 5743                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5744                        );
 5745                        last_outdent = Some(row);
 5746                    }
 5747                }
 5748            }
 5749        }
 5750
 5751        self.transact(cx, |this, cx| {
 5752            this.buffer.update(cx, |buffer, cx| {
 5753                let empty_str: Arc<str> = Arc::default();
 5754                buffer.edit(
 5755                    deletion_ranges
 5756                        .into_iter()
 5757                        .map(|range| (range, empty_str.clone())),
 5758                    None,
 5759                    cx,
 5760                );
 5761            });
 5762            let selections = this.selections.all::<usize>(cx);
 5763            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5764        });
 5765    }
 5766
 5767    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5768        if self.read_only(cx) {
 5769            return;
 5770        }
 5771        let selections = self
 5772            .selections
 5773            .all::<usize>(cx)
 5774            .into_iter()
 5775            .map(|s| s.range());
 5776
 5777        self.transact(cx, |this, cx| {
 5778            this.buffer.update(cx, |buffer, cx| {
 5779                buffer.autoindent_ranges(selections, cx);
 5780            });
 5781            let selections = this.selections.all::<usize>(cx);
 5782            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5783        });
 5784    }
 5785
 5786    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5787        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5788        let selections = self.selections.all::<Point>(cx);
 5789
 5790        let mut new_cursors = Vec::new();
 5791        let mut edit_ranges = Vec::new();
 5792        let mut selections = selections.iter().peekable();
 5793        while let Some(selection) = selections.next() {
 5794            let mut rows = selection.spanned_rows(false, &display_map);
 5795            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5796
 5797            // Accumulate contiguous regions of rows that we want to delete.
 5798            while let Some(next_selection) = selections.peek() {
 5799                let next_rows = next_selection.spanned_rows(false, &display_map);
 5800                if next_rows.start <= rows.end {
 5801                    rows.end = next_rows.end;
 5802                    selections.next().unwrap();
 5803                } else {
 5804                    break;
 5805                }
 5806            }
 5807
 5808            let buffer = &display_map.buffer_snapshot;
 5809            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5810            let edit_end;
 5811            let cursor_buffer_row;
 5812            if buffer.max_point().row >= rows.end.0 {
 5813                // If there's a line after the range, delete the \n from the end of the row range
 5814                // and position the cursor on the next line.
 5815                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5816                cursor_buffer_row = rows.end;
 5817            } else {
 5818                // If there isn't a line after the range, delete the \n from the line before the
 5819                // start of the row range and position the cursor there.
 5820                edit_start = edit_start.saturating_sub(1);
 5821                edit_end = buffer.len();
 5822                cursor_buffer_row = rows.start.previous_row();
 5823            }
 5824
 5825            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5826            *cursor.column_mut() =
 5827                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5828
 5829            new_cursors.push((
 5830                selection.id,
 5831                buffer.anchor_after(cursor.to_point(&display_map)),
 5832            ));
 5833            edit_ranges.push(edit_start..edit_end);
 5834        }
 5835
 5836        self.transact(cx, |this, cx| {
 5837            let buffer = this.buffer.update(cx, |buffer, cx| {
 5838                let empty_str: Arc<str> = Arc::default();
 5839                buffer.edit(
 5840                    edit_ranges
 5841                        .into_iter()
 5842                        .map(|range| (range, empty_str.clone())),
 5843                    None,
 5844                    cx,
 5845                );
 5846                buffer.snapshot(cx)
 5847            });
 5848            let new_selections = new_cursors
 5849                .into_iter()
 5850                .map(|(id, cursor)| {
 5851                    let cursor = cursor.to_point(&buffer);
 5852                    Selection {
 5853                        id,
 5854                        start: cursor,
 5855                        end: cursor,
 5856                        reversed: false,
 5857                        goal: SelectionGoal::None,
 5858                    }
 5859                })
 5860                .collect();
 5861
 5862            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5863                s.select(new_selections);
 5864            });
 5865        });
 5866    }
 5867
 5868    pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
 5869        if self.read_only(cx) {
 5870            return;
 5871        }
 5872        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5873        for selection in self.selections.all::<Point>(cx) {
 5874            let start = MultiBufferRow(selection.start.row);
 5875            // Treat single line selections as if they include the next line. Otherwise this action
 5876            // would do nothing for single line selections individual cursors.
 5877            let end = if selection.start.row == selection.end.row {
 5878                MultiBufferRow(selection.start.row + 1)
 5879            } else {
 5880                MultiBufferRow(selection.end.row)
 5881            };
 5882
 5883            if let Some(last_row_range) = row_ranges.last_mut() {
 5884                if start <= last_row_range.end {
 5885                    last_row_range.end = end;
 5886                    continue;
 5887                }
 5888            }
 5889            row_ranges.push(start..end);
 5890        }
 5891
 5892        let snapshot = self.buffer.read(cx).snapshot(cx);
 5893        let mut cursor_positions = Vec::new();
 5894        for row_range in &row_ranges {
 5895            let anchor = snapshot.anchor_before(Point::new(
 5896                row_range.end.previous_row().0,
 5897                snapshot.line_len(row_range.end.previous_row()),
 5898            ));
 5899            cursor_positions.push(anchor..anchor);
 5900        }
 5901
 5902        self.transact(cx, |this, cx| {
 5903            for row_range in row_ranges.into_iter().rev() {
 5904                for row in row_range.iter_rows().rev() {
 5905                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5906                    let next_line_row = row.next_row();
 5907                    let indent = snapshot.indent_size_for_line(next_line_row);
 5908                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5909
 5910                    let replace =
 5911                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 5912                            " "
 5913                        } else {
 5914                            ""
 5915                        };
 5916
 5917                    this.buffer.update(cx, |buffer, cx| {
 5918                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5919                    });
 5920                }
 5921            }
 5922
 5923            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5924                s.select_anchor_ranges(cursor_positions)
 5925            });
 5926        });
 5927    }
 5928
 5929    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5930        self.join_lines_impl(true, cx);
 5931    }
 5932
 5933    pub fn sort_lines_case_sensitive(
 5934        &mut self,
 5935        _: &SortLinesCaseSensitive,
 5936        cx: &mut ViewContext<Self>,
 5937    ) {
 5938        self.manipulate_lines(cx, |lines| lines.sort())
 5939    }
 5940
 5941    pub fn sort_lines_case_insensitive(
 5942        &mut self,
 5943        _: &SortLinesCaseInsensitive,
 5944        cx: &mut ViewContext<Self>,
 5945    ) {
 5946        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5947    }
 5948
 5949    pub fn unique_lines_case_insensitive(
 5950        &mut self,
 5951        _: &UniqueLinesCaseInsensitive,
 5952        cx: &mut ViewContext<Self>,
 5953    ) {
 5954        self.manipulate_lines(cx, |lines| {
 5955            let mut seen = HashSet::default();
 5956            lines.retain(|line| seen.insert(line.to_lowercase()));
 5957        })
 5958    }
 5959
 5960    pub fn unique_lines_case_sensitive(
 5961        &mut self,
 5962        _: &UniqueLinesCaseSensitive,
 5963        cx: &mut ViewContext<Self>,
 5964    ) {
 5965        self.manipulate_lines(cx, |lines| {
 5966            let mut seen = HashSet::default();
 5967            lines.retain(|line| seen.insert(*line));
 5968        })
 5969    }
 5970
 5971    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5972        let mut revert_changes = HashMap::default();
 5973        let snapshot = self.snapshot(cx);
 5974        for hunk in hunks_for_ranges(
 5975            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5976            &snapshot,
 5977        ) {
 5978            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5979        }
 5980        if !revert_changes.is_empty() {
 5981            self.transact(cx, |editor, cx| {
 5982                editor.revert(revert_changes, cx);
 5983            });
 5984        }
 5985    }
 5986
 5987    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5988        let Some(project) = self.project.clone() else {
 5989            return;
 5990        };
 5991        self.reload(project, cx).detach_and_notify_err(cx);
 5992    }
 5993
 5994    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5995        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5996        if !revert_changes.is_empty() {
 5997            self.transact(cx, |editor, cx| {
 5998                editor.revert(revert_changes, cx);
 5999            });
 6000        }
 6001    }
 6002
 6003    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 6004        let snapshot = self.buffer.read(cx).read(cx);
 6005        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 6006            drop(snapshot);
 6007            let mut revert_changes = HashMap::default();
 6008            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6009            if !revert_changes.is_empty() {
 6010                self.revert(revert_changes, cx)
 6011            }
 6012        }
 6013    }
 6014
 6015    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6016        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6017            let project_path = buffer.read(cx).project_path(cx)?;
 6018            let project = self.project.as_ref()?.read(cx);
 6019            let entry = project.entry_for_path(&project_path, cx)?;
 6020            let parent = match &entry.canonical_path {
 6021                Some(canonical_path) => canonical_path.to_path_buf(),
 6022                None => project.absolute_path(&project_path, cx)?,
 6023            }
 6024            .parent()?
 6025            .to_path_buf();
 6026            Some(parent)
 6027        }) {
 6028            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6029        }
 6030    }
 6031
 6032    fn gather_revert_changes(
 6033        &mut self,
 6034        selections: &[Selection<Point>],
 6035        cx: &mut ViewContext<Editor>,
 6036    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6037        let mut revert_changes = HashMap::default();
 6038        let snapshot = self.snapshot(cx);
 6039        for hunk in hunks_for_selections(&snapshot, selections) {
 6040            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6041        }
 6042        revert_changes
 6043    }
 6044
 6045    pub fn prepare_revert_change(
 6046        &mut self,
 6047        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6048        hunk: &MultiBufferDiffHunk,
 6049        cx: &AppContext,
 6050    ) -> Option<()> {
 6051        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6052        let buffer = buffer.read(cx);
 6053        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6054        let original_text = change_set
 6055            .read(cx)
 6056            .base_text
 6057            .as_ref()?
 6058            .read(cx)
 6059            .as_rope()
 6060            .slice(hunk.diff_base_byte_range.clone());
 6061        let buffer_snapshot = buffer.snapshot();
 6062        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6063        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6064            probe
 6065                .0
 6066                .start
 6067                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6068                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6069        }) {
 6070            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6071            Some(())
 6072        } else {
 6073            None
 6074        }
 6075    }
 6076
 6077    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6078        self.manipulate_lines(cx, |lines| lines.reverse())
 6079    }
 6080
 6081    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6082        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6083    }
 6084
 6085    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6086    where
 6087        Fn: FnMut(&mut Vec<&str>),
 6088    {
 6089        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6090        let buffer = self.buffer.read(cx).snapshot(cx);
 6091
 6092        let mut edits = Vec::new();
 6093
 6094        let selections = self.selections.all::<Point>(cx);
 6095        let mut selections = selections.iter().peekable();
 6096        let mut contiguous_row_selections = Vec::new();
 6097        let mut new_selections = Vec::new();
 6098        let mut added_lines = 0;
 6099        let mut removed_lines = 0;
 6100
 6101        while let Some(selection) = selections.next() {
 6102            let (start_row, end_row) = consume_contiguous_rows(
 6103                &mut contiguous_row_selections,
 6104                selection,
 6105                &display_map,
 6106                &mut selections,
 6107            );
 6108
 6109            let start_point = Point::new(start_row.0, 0);
 6110            let end_point = Point::new(
 6111                end_row.previous_row().0,
 6112                buffer.line_len(end_row.previous_row()),
 6113            );
 6114            let text = buffer
 6115                .text_for_range(start_point..end_point)
 6116                .collect::<String>();
 6117
 6118            let mut lines = text.split('\n').collect_vec();
 6119
 6120            let lines_before = lines.len();
 6121            callback(&mut lines);
 6122            let lines_after = lines.len();
 6123
 6124            edits.push((start_point..end_point, lines.join("\n")));
 6125
 6126            // Selections must change based on added and removed line count
 6127            let start_row =
 6128                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6129            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6130            new_selections.push(Selection {
 6131                id: selection.id,
 6132                start: start_row,
 6133                end: end_row,
 6134                goal: SelectionGoal::None,
 6135                reversed: selection.reversed,
 6136            });
 6137
 6138            if lines_after > lines_before {
 6139                added_lines += lines_after - lines_before;
 6140            } else if lines_before > lines_after {
 6141                removed_lines += lines_before - lines_after;
 6142            }
 6143        }
 6144
 6145        self.transact(cx, |this, cx| {
 6146            let buffer = this.buffer.update(cx, |buffer, cx| {
 6147                buffer.edit(edits, None, cx);
 6148                buffer.snapshot(cx)
 6149            });
 6150
 6151            // Recalculate offsets on newly edited buffer
 6152            let new_selections = new_selections
 6153                .iter()
 6154                .map(|s| {
 6155                    let start_point = Point::new(s.start.0, 0);
 6156                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6157                    Selection {
 6158                        id: s.id,
 6159                        start: buffer.point_to_offset(start_point),
 6160                        end: buffer.point_to_offset(end_point),
 6161                        goal: s.goal,
 6162                        reversed: s.reversed,
 6163                    }
 6164                })
 6165                .collect();
 6166
 6167            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6168                s.select(new_selections);
 6169            });
 6170
 6171            this.request_autoscroll(Autoscroll::fit(), cx);
 6172        });
 6173    }
 6174
 6175    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6176        self.manipulate_text(cx, |text| text.to_uppercase())
 6177    }
 6178
 6179    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6180        self.manipulate_text(cx, |text| text.to_lowercase())
 6181    }
 6182
 6183    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6184        self.manipulate_text(cx, |text| {
 6185            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6186            // https://github.com/rutrum/convert-case/issues/16
 6187            text.split('\n')
 6188                .map(|line| line.to_case(Case::Title))
 6189                .join("\n")
 6190        })
 6191    }
 6192
 6193    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6194        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6195    }
 6196
 6197    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6198        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6199    }
 6200
 6201    pub fn convert_to_upper_camel_case(
 6202        &mut self,
 6203        _: &ConvertToUpperCamelCase,
 6204        cx: &mut ViewContext<Self>,
 6205    ) {
 6206        self.manipulate_text(cx, |text| {
 6207            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6208            // https://github.com/rutrum/convert-case/issues/16
 6209            text.split('\n')
 6210                .map(|line| line.to_case(Case::UpperCamel))
 6211                .join("\n")
 6212        })
 6213    }
 6214
 6215    pub fn convert_to_lower_camel_case(
 6216        &mut self,
 6217        _: &ConvertToLowerCamelCase,
 6218        cx: &mut ViewContext<Self>,
 6219    ) {
 6220        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6221    }
 6222
 6223    pub fn convert_to_opposite_case(
 6224        &mut self,
 6225        _: &ConvertToOppositeCase,
 6226        cx: &mut ViewContext<Self>,
 6227    ) {
 6228        self.manipulate_text(cx, |text| {
 6229            text.chars()
 6230                .fold(String::with_capacity(text.len()), |mut t, c| {
 6231                    if c.is_uppercase() {
 6232                        t.extend(c.to_lowercase());
 6233                    } else {
 6234                        t.extend(c.to_uppercase());
 6235                    }
 6236                    t
 6237                })
 6238        })
 6239    }
 6240
 6241    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6242    where
 6243        Fn: FnMut(&str) -> String,
 6244    {
 6245        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6246        let buffer = self.buffer.read(cx).snapshot(cx);
 6247
 6248        let mut new_selections = Vec::new();
 6249        let mut edits = Vec::new();
 6250        let mut selection_adjustment = 0i32;
 6251
 6252        for selection in self.selections.all::<usize>(cx) {
 6253            let selection_is_empty = selection.is_empty();
 6254
 6255            let (start, end) = if selection_is_empty {
 6256                let word_range = movement::surrounding_word(
 6257                    &display_map,
 6258                    selection.start.to_display_point(&display_map),
 6259                );
 6260                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6261                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6262                (start, end)
 6263            } else {
 6264                (selection.start, selection.end)
 6265            };
 6266
 6267            let text = buffer.text_for_range(start..end).collect::<String>();
 6268            let old_length = text.len() as i32;
 6269            let text = callback(&text);
 6270
 6271            new_selections.push(Selection {
 6272                start: (start as i32 - selection_adjustment) as usize,
 6273                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6274                goal: SelectionGoal::None,
 6275                ..selection
 6276            });
 6277
 6278            selection_adjustment += old_length - text.len() as i32;
 6279
 6280            edits.push((start..end, text));
 6281        }
 6282
 6283        self.transact(cx, |this, cx| {
 6284            this.buffer.update(cx, |buffer, cx| {
 6285                buffer.edit(edits, None, cx);
 6286            });
 6287
 6288            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6289                s.select(new_selections);
 6290            });
 6291
 6292            this.request_autoscroll(Autoscroll::fit(), cx);
 6293        });
 6294    }
 6295
 6296    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6297        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6298        let buffer = &display_map.buffer_snapshot;
 6299        let selections = self.selections.all::<Point>(cx);
 6300
 6301        let mut edits = Vec::new();
 6302        let mut selections_iter = selections.iter().peekable();
 6303        while let Some(selection) = selections_iter.next() {
 6304            let mut rows = selection.spanned_rows(false, &display_map);
 6305            // duplicate line-wise
 6306            if whole_lines || selection.start == selection.end {
 6307                // Avoid duplicating the same lines twice.
 6308                while let Some(next_selection) = selections_iter.peek() {
 6309                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6310                    if next_rows.start < rows.end {
 6311                        rows.end = next_rows.end;
 6312                        selections_iter.next().unwrap();
 6313                    } else {
 6314                        break;
 6315                    }
 6316                }
 6317
 6318                // Copy the text from the selected row region and splice it either at the start
 6319                // or end of the region.
 6320                let start = Point::new(rows.start.0, 0);
 6321                let end = Point::new(
 6322                    rows.end.previous_row().0,
 6323                    buffer.line_len(rows.end.previous_row()),
 6324                );
 6325                let text = buffer
 6326                    .text_for_range(start..end)
 6327                    .chain(Some("\n"))
 6328                    .collect::<String>();
 6329                let insert_location = if upwards {
 6330                    Point::new(rows.end.0, 0)
 6331                } else {
 6332                    start
 6333                };
 6334                edits.push((insert_location..insert_location, text));
 6335            } else {
 6336                // duplicate character-wise
 6337                let start = selection.start;
 6338                let end = selection.end;
 6339                let text = buffer.text_for_range(start..end).collect::<String>();
 6340                edits.push((selection.end..selection.end, text));
 6341            }
 6342        }
 6343
 6344        self.transact(cx, |this, cx| {
 6345            this.buffer.update(cx, |buffer, cx| {
 6346                buffer.edit(edits, None, cx);
 6347            });
 6348
 6349            this.request_autoscroll(Autoscroll::fit(), cx);
 6350        });
 6351    }
 6352
 6353    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6354        self.duplicate(true, true, cx);
 6355    }
 6356
 6357    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6358        self.duplicate(false, true, cx);
 6359    }
 6360
 6361    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6362        self.duplicate(false, false, cx);
 6363    }
 6364
 6365    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6366        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6367        let buffer = self.buffer.read(cx).snapshot(cx);
 6368
 6369        let mut edits = Vec::new();
 6370        let mut unfold_ranges = Vec::new();
 6371        let mut refold_creases = Vec::new();
 6372
 6373        let selections = self.selections.all::<Point>(cx);
 6374        let mut selections = selections.iter().peekable();
 6375        let mut contiguous_row_selections = Vec::new();
 6376        let mut new_selections = Vec::new();
 6377
 6378        while let Some(selection) = selections.next() {
 6379            // Find all the selections that span a contiguous row range
 6380            let (start_row, end_row) = consume_contiguous_rows(
 6381                &mut contiguous_row_selections,
 6382                selection,
 6383                &display_map,
 6384                &mut selections,
 6385            );
 6386
 6387            // Move the text spanned by the row range to be before the line preceding the row range
 6388            if start_row.0 > 0 {
 6389                let range_to_move = Point::new(
 6390                    start_row.previous_row().0,
 6391                    buffer.line_len(start_row.previous_row()),
 6392                )
 6393                    ..Point::new(
 6394                        end_row.previous_row().0,
 6395                        buffer.line_len(end_row.previous_row()),
 6396                    );
 6397                let insertion_point = display_map
 6398                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6399                    .0;
 6400
 6401                // Don't move lines across excerpts
 6402                if buffer
 6403                    .excerpt_boundaries_in_range((
 6404                        Bound::Excluded(insertion_point),
 6405                        Bound::Included(range_to_move.end),
 6406                    ))
 6407                    .next()
 6408                    .is_none()
 6409                {
 6410                    let text = buffer
 6411                        .text_for_range(range_to_move.clone())
 6412                        .flat_map(|s| s.chars())
 6413                        .skip(1)
 6414                        .chain(['\n'])
 6415                        .collect::<String>();
 6416
 6417                    edits.push((
 6418                        buffer.anchor_after(range_to_move.start)
 6419                            ..buffer.anchor_before(range_to_move.end),
 6420                        String::new(),
 6421                    ));
 6422                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6423                    edits.push((insertion_anchor..insertion_anchor, text));
 6424
 6425                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6426
 6427                    // Move selections up
 6428                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6429                        |mut selection| {
 6430                            selection.start.row -= row_delta;
 6431                            selection.end.row -= row_delta;
 6432                            selection
 6433                        },
 6434                    ));
 6435
 6436                    // Move folds up
 6437                    unfold_ranges.push(range_to_move.clone());
 6438                    for fold in display_map.folds_in_range(
 6439                        buffer.anchor_before(range_to_move.start)
 6440                            ..buffer.anchor_after(range_to_move.end),
 6441                    ) {
 6442                        let mut start = fold.range.start.to_point(&buffer);
 6443                        let mut end = fold.range.end.to_point(&buffer);
 6444                        start.row -= row_delta;
 6445                        end.row -= row_delta;
 6446                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6447                    }
 6448                }
 6449            }
 6450
 6451            // If we didn't move line(s), preserve the existing selections
 6452            new_selections.append(&mut contiguous_row_selections);
 6453        }
 6454
 6455        self.transact(cx, |this, cx| {
 6456            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6457            this.buffer.update(cx, |buffer, cx| {
 6458                for (range, text) in edits {
 6459                    buffer.edit([(range, text)], None, cx);
 6460                }
 6461            });
 6462            this.fold_creases(refold_creases, true, cx);
 6463            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6464                s.select(new_selections);
 6465            })
 6466        });
 6467    }
 6468
 6469    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6470        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6471        let buffer = self.buffer.read(cx).snapshot(cx);
 6472
 6473        let mut edits = Vec::new();
 6474        let mut unfold_ranges = Vec::new();
 6475        let mut refold_creases = Vec::new();
 6476
 6477        let selections = self.selections.all::<Point>(cx);
 6478        let mut selections = selections.iter().peekable();
 6479        let mut contiguous_row_selections = Vec::new();
 6480        let mut new_selections = Vec::new();
 6481
 6482        while let Some(selection) = selections.next() {
 6483            // Find all the selections that span a contiguous row range
 6484            let (start_row, end_row) = consume_contiguous_rows(
 6485                &mut contiguous_row_selections,
 6486                selection,
 6487                &display_map,
 6488                &mut selections,
 6489            );
 6490
 6491            // Move the text spanned by the row range to be after the last line of the row range
 6492            if end_row.0 <= buffer.max_point().row {
 6493                let range_to_move =
 6494                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6495                let insertion_point = display_map
 6496                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6497                    .0;
 6498
 6499                // Don't move lines across excerpt boundaries
 6500                if buffer
 6501                    .excerpt_boundaries_in_range((
 6502                        Bound::Excluded(range_to_move.start),
 6503                        Bound::Included(insertion_point),
 6504                    ))
 6505                    .next()
 6506                    .is_none()
 6507                {
 6508                    let mut text = String::from("\n");
 6509                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6510                    text.pop(); // Drop trailing newline
 6511                    edits.push((
 6512                        buffer.anchor_after(range_to_move.start)
 6513                            ..buffer.anchor_before(range_to_move.end),
 6514                        String::new(),
 6515                    ));
 6516                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6517                    edits.push((insertion_anchor..insertion_anchor, text));
 6518
 6519                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6520
 6521                    // Move selections down
 6522                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6523                        |mut selection| {
 6524                            selection.start.row += row_delta;
 6525                            selection.end.row += row_delta;
 6526                            selection
 6527                        },
 6528                    ));
 6529
 6530                    // Move folds down
 6531                    unfold_ranges.push(range_to_move.clone());
 6532                    for fold in display_map.folds_in_range(
 6533                        buffer.anchor_before(range_to_move.start)
 6534                            ..buffer.anchor_after(range_to_move.end),
 6535                    ) {
 6536                        let mut start = fold.range.start.to_point(&buffer);
 6537                        let mut end = fold.range.end.to_point(&buffer);
 6538                        start.row += row_delta;
 6539                        end.row += row_delta;
 6540                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6541                    }
 6542                }
 6543            }
 6544
 6545            // If we didn't move line(s), preserve the existing selections
 6546            new_selections.append(&mut contiguous_row_selections);
 6547        }
 6548
 6549        self.transact(cx, |this, cx| {
 6550            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6551            this.buffer.update(cx, |buffer, cx| {
 6552                for (range, text) in edits {
 6553                    buffer.edit([(range, text)], None, cx);
 6554                }
 6555            });
 6556            this.fold_creases(refold_creases, true, cx);
 6557            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6558        });
 6559    }
 6560
 6561    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6562        let text_layout_details = &self.text_layout_details(cx);
 6563        self.transact(cx, |this, cx| {
 6564            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6565                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6566                let line_mode = s.line_mode;
 6567                s.move_with(|display_map, selection| {
 6568                    if !selection.is_empty() || line_mode {
 6569                        return;
 6570                    }
 6571
 6572                    let mut head = selection.head();
 6573                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6574                    if head.column() == display_map.line_len(head.row()) {
 6575                        transpose_offset = display_map
 6576                            .buffer_snapshot
 6577                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6578                    }
 6579
 6580                    if transpose_offset == 0 {
 6581                        return;
 6582                    }
 6583
 6584                    *head.column_mut() += 1;
 6585                    head = display_map.clip_point(head, Bias::Right);
 6586                    let goal = SelectionGoal::HorizontalPosition(
 6587                        display_map
 6588                            .x_for_display_point(head, text_layout_details)
 6589                            .into(),
 6590                    );
 6591                    selection.collapse_to(head, goal);
 6592
 6593                    let transpose_start = display_map
 6594                        .buffer_snapshot
 6595                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6596                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6597                        let transpose_end = display_map
 6598                            .buffer_snapshot
 6599                            .clip_offset(transpose_offset + 1, Bias::Right);
 6600                        if let Some(ch) =
 6601                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6602                        {
 6603                            edits.push((transpose_start..transpose_offset, String::new()));
 6604                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6605                        }
 6606                    }
 6607                });
 6608                edits
 6609            });
 6610            this.buffer
 6611                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6612            let selections = this.selections.all::<usize>(cx);
 6613            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6614                s.select(selections);
 6615            });
 6616        });
 6617    }
 6618
 6619    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6620        self.rewrap_impl(IsVimMode::No, cx)
 6621    }
 6622
 6623    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6624        let buffer = self.buffer.read(cx).snapshot(cx);
 6625        let selections = self.selections.all::<Point>(cx);
 6626        let mut selections = selections.iter().peekable();
 6627
 6628        let mut edits = Vec::new();
 6629        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6630
 6631        while let Some(selection) = selections.next() {
 6632            let mut start_row = selection.start.row;
 6633            let mut end_row = selection.end.row;
 6634
 6635            // Skip selections that overlap with a range that has already been rewrapped.
 6636            let selection_range = start_row..end_row;
 6637            if rewrapped_row_ranges
 6638                .iter()
 6639                .any(|range| range.overlaps(&selection_range))
 6640            {
 6641                continue;
 6642            }
 6643
 6644            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6645
 6646            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6647                match language_scope.language_name().0.as_ref() {
 6648                    "Markdown" | "Plain Text" => {
 6649                        should_rewrap = true;
 6650                    }
 6651                    _ => {}
 6652                }
 6653            }
 6654
 6655            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6656
 6657            // Since not all lines in the selection may be at the same indent
 6658            // level, choose the indent size that is the most common between all
 6659            // of the lines.
 6660            //
 6661            // If there is a tie, we use the deepest indent.
 6662            let (indent_size, indent_end) = {
 6663                let mut indent_size_occurrences = HashMap::default();
 6664                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6665
 6666                for row in start_row..=end_row {
 6667                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6668                    rows_by_indent_size.entry(indent).or_default().push(row);
 6669                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6670                }
 6671
 6672                let indent_size = indent_size_occurrences
 6673                    .into_iter()
 6674                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6675                    .map(|(indent, _)| indent)
 6676                    .unwrap_or_default();
 6677                let row = rows_by_indent_size[&indent_size][0];
 6678                let indent_end = Point::new(row, indent_size.len);
 6679
 6680                (indent_size, indent_end)
 6681            };
 6682
 6683            let mut line_prefix = indent_size.chars().collect::<String>();
 6684
 6685            if let Some(comment_prefix) =
 6686                buffer
 6687                    .language_scope_at(selection.head())
 6688                    .and_then(|language| {
 6689                        language
 6690                            .line_comment_prefixes()
 6691                            .iter()
 6692                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6693                            .cloned()
 6694                    })
 6695            {
 6696                line_prefix.push_str(&comment_prefix);
 6697                should_rewrap = true;
 6698            }
 6699
 6700            if !should_rewrap {
 6701                continue;
 6702            }
 6703
 6704            if selection.is_empty() {
 6705                'expand_upwards: while start_row > 0 {
 6706                    let prev_row = start_row - 1;
 6707                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6708                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6709                    {
 6710                        start_row = prev_row;
 6711                    } else {
 6712                        break 'expand_upwards;
 6713                    }
 6714                }
 6715
 6716                'expand_downwards: while end_row < buffer.max_point().row {
 6717                    let next_row = end_row + 1;
 6718                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6719                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6720                    {
 6721                        end_row = next_row;
 6722                    } else {
 6723                        break 'expand_downwards;
 6724                    }
 6725                }
 6726            }
 6727
 6728            let start = Point::new(start_row, 0);
 6729            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6730            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6731            let Some(lines_without_prefixes) = selection_text
 6732                .lines()
 6733                .map(|line| {
 6734                    line.strip_prefix(&line_prefix)
 6735                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6736                        .ok_or_else(|| {
 6737                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6738                        })
 6739                })
 6740                .collect::<Result<Vec<_>, _>>()
 6741                .log_err()
 6742            else {
 6743                continue;
 6744            };
 6745
 6746            let wrap_column = buffer
 6747                .settings_at(Point::new(start_row, 0), cx)
 6748                .preferred_line_length as usize;
 6749            let wrapped_text = wrap_with_prefix(
 6750                line_prefix,
 6751                lines_without_prefixes.join(" "),
 6752                wrap_column,
 6753                tab_size,
 6754            );
 6755
 6756            // TODO: should always use char-based diff while still supporting cursor behavior that
 6757            // matches vim.
 6758            let diff = match is_vim_mode {
 6759                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6760                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6761            };
 6762            let mut offset = start.to_offset(&buffer);
 6763            let mut moved_since_edit = true;
 6764
 6765            for change in diff.iter_all_changes() {
 6766                let value = change.value();
 6767                match change.tag() {
 6768                    ChangeTag::Equal => {
 6769                        offset += value.len();
 6770                        moved_since_edit = true;
 6771                    }
 6772                    ChangeTag::Delete => {
 6773                        let start = buffer.anchor_after(offset);
 6774                        let end = buffer.anchor_before(offset + value.len());
 6775
 6776                        if moved_since_edit {
 6777                            edits.push((start..end, String::new()));
 6778                        } else {
 6779                            edits.last_mut().unwrap().0.end = end;
 6780                        }
 6781
 6782                        offset += value.len();
 6783                        moved_since_edit = false;
 6784                    }
 6785                    ChangeTag::Insert => {
 6786                        if moved_since_edit {
 6787                            let anchor = buffer.anchor_after(offset);
 6788                            edits.push((anchor..anchor, value.to_string()));
 6789                        } else {
 6790                            edits.last_mut().unwrap().1.push_str(value);
 6791                        }
 6792
 6793                        moved_since_edit = false;
 6794                    }
 6795                }
 6796            }
 6797
 6798            rewrapped_row_ranges.push(start_row..=end_row);
 6799        }
 6800
 6801        self.buffer
 6802            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6803    }
 6804
 6805    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6806        let mut text = String::new();
 6807        let buffer = self.buffer.read(cx).snapshot(cx);
 6808        let mut selections = self.selections.all::<Point>(cx);
 6809        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6810        {
 6811            let max_point = buffer.max_point();
 6812            let mut is_first = true;
 6813            for selection in &mut selections {
 6814                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6815                if is_entire_line {
 6816                    selection.start = Point::new(selection.start.row, 0);
 6817                    if !selection.is_empty() && selection.end.column == 0 {
 6818                        selection.end = cmp::min(max_point, selection.end);
 6819                    } else {
 6820                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6821                    }
 6822                    selection.goal = SelectionGoal::None;
 6823                }
 6824                if is_first {
 6825                    is_first = false;
 6826                } else {
 6827                    text += "\n";
 6828                }
 6829                let mut len = 0;
 6830                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6831                    text.push_str(chunk);
 6832                    len += chunk.len();
 6833                }
 6834                clipboard_selections.push(ClipboardSelection {
 6835                    len,
 6836                    is_entire_line,
 6837                    first_line_indent: buffer
 6838                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6839                        .len,
 6840                });
 6841            }
 6842        }
 6843
 6844        self.transact(cx, |this, cx| {
 6845            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6846                s.select(selections);
 6847            });
 6848            this.insert("", cx);
 6849        });
 6850        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6851    }
 6852
 6853    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6854        let item = self.cut_common(cx);
 6855        cx.write_to_clipboard(item);
 6856    }
 6857
 6858    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6859        self.change_selections(None, cx, |s| {
 6860            s.move_with(|snapshot, sel| {
 6861                if sel.is_empty() {
 6862                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6863                }
 6864            });
 6865        });
 6866        let item = self.cut_common(cx);
 6867        cx.set_global(KillRing(item))
 6868    }
 6869
 6870    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6871        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6872            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6873                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6874            } else {
 6875                return;
 6876            }
 6877        } else {
 6878            return;
 6879        };
 6880        self.do_paste(&text, metadata, false, cx);
 6881    }
 6882
 6883    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6884        let selections = self.selections.all::<Point>(cx);
 6885        let buffer = self.buffer.read(cx).read(cx);
 6886        let mut text = String::new();
 6887
 6888        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6889        {
 6890            let max_point = buffer.max_point();
 6891            let mut is_first = true;
 6892            for selection in selections.iter() {
 6893                let mut start = selection.start;
 6894                let mut end = selection.end;
 6895                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6896                if is_entire_line {
 6897                    start = Point::new(start.row, 0);
 6898                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6899                }
 6900                if is_first {
 6901                    is_first = false;
 6902                } else {
 6903                    text += "\n";
 6904                }
 6905                let mut len = 0;
 6906                for chunk in buffer.text_for_range(start..end) {
 6907                    text.push_str(chunk);
 6908                    len += chunk.len();
 6909                }
 6910                clipboard_selections.push(ClipboardSelection {
 6911                    len,
 6912                    is_entire_line,
 6913                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6914                });
 6915            }
 6916        }
 6917
 6918        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6919            text,
 6920            clipboard_selections,
 6921        ));
 6922    }
 6923
 6924    pub fn do_paste(
 6925        &mut self,
 6926        text: &String,
 6927        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6928        handle_entire_lines: bool,
 6929        cx: &mut ViewContext<Self>,
 6930    ) {
 6931        if self.read_only(cx) {
 6932            return;
 6933        }
 6934
 6935        let clipboard_text = Cow::Borrowed(text);
 6936
 6937        self.transact(cx, |this, cx| {
 6938            if let Some(mut clipboard_selections) = clipboard_selections {
 6939                let old_selections = this.selections.all::<usize>(cx);
 6940                let all_selections_were_entire_line =
 6941                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6942                let first_selection_indent_column =
 6943                    clipboard_selections.first().map(|s| s.first_line_indent);
 6944                if clipboard_selections.len() != old_selections.len() {
 6945                    clipboard_selections.drain(..);
 6946                }
 6947                let cursor_offset = this.selections.last::<usize>(cx).head();
 6948                let mut auto_indent_on_paste = true;
 6949
 6950                this.buffer.update(cx, |buffer, cx| {
 6951                    let snapshot = buffer.read(cx);
 6952                    auto_indent_on_paste =
 6953                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6954
 6955                    let mut start_offset = 0;
 6956                    let mut edits = Vec::new();
 6957                    let mut original_indent_columns = Vec::new();
 6958                    for (ix, selection) in old_selections.iter().enumerate() {
 6959                        let to_insert;
 6960                        let entire_line;
 6961                        let original_indent_column;
 6962                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6963                            let end_offset = start_offset + clipboard_selection.len;
 6964                            to_insert = &clipboard_text[start_offset..end_offset];
 6965                            entire_line = clipboard_selection.is_entire_line;
 6966                            start_offset = end_offset + 1;
 6967                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6968                        } else {
 6969                            to_insert = clipboard_text.as_str();
 6970                            entire_line = all_selections_were_entire_line;
 6971                            original_indent_column = first_selection_indent_column
 6972                        }
 6973
 6974                        // If the corresponding selection was empty when this slice of the
 6975                        // clipboard text was written, then the entire line containing the
 6976                        // selection was copied. If this selection is also currently empty,
 6977                        // then paste the line before the current line of the buffer.
 6978                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6979                            let column = selection.start.to_point(&snapshot).column as usize;
 6980                            let line_start = selection.start - column;
 6981                            line_start..line_start
 6982                        } else {
 6983                            selection.range()
 6984                        };
 6985
 6986                        edits.push((range, to_insert));
 6987                        original_indent_columns.extend(original_indent_column);
 6988                    }
 6989                    drop(snapshot);
 6990
 6991                    buffer.edit(
 6992                        edits,
 6993                        if auto_indent_on_paste {
 6994                            Some(AutoindentMode::Block {
 6995                                original_indent_columns,
 6996                            })
 6997                        } else {
 6998                            None
 6999                        },
 7000                        cx,
 7001                    );
 7002                });
 7003
 7004                let selections = this.selections.all::<usize>(cx);
 7005                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7006            } else {
 7007                this.insert(&clipboard_text, cx);
 7008            }
 7009        });
 7010    }
 7011
 7012    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7013        if let Some(item) = cx.read_from_clipboard() {
 7014            let entries = item.entries();
 7015
 7016            match entries.first() {
 7017                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7018                // of all the pasted entries.
 7019                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7020                    .do_paste(
 7021                        clipboard_string.text(),
 7022                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7023                        true,
 7024                        cx,
 7025                    ),
 7026                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7027            }
 7028        }
 7029    }
 7030
 7031    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7032        if self.read_only(cx) {
 7033            return;
 7034        }
 7035
 7036        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7037            if let Some((selections, _)) =
 7038                self.selection_history.transaction(transaction_id).cloned()
 7039            {
 7040                self.change_selections(None, cx, |s| {
 7041                    s.select_anchors(selections.to_vec());
 7042                });
 7043            }
 7044            self.request_autoscroll(Autoscroll::fit(), cx);
 7045            self.unmark_text(cx);
 7046            self.refresh_inline_completion(true, false, cx);
 7047            cx.emit(EditorEvent::Edited { transaction_id });
 7048            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7049        }
 7050    }
 7051
 7052    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7053        if self.read_only(cx) {
 7054            return;
 7055        }
 7056
 7057        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7058            if let Some((_, Some(selections))) =
 7059                self.selection_history.transaction(transaction_id).cloned()
 7060            {
 7061                self.change_selections(None, cx, |s| {
 7062                    s.select_anchors(selections.to_vec());
 7063                });
 7064            }
 7065            self.request_autoscroll(Autoscroll::fit(), cx);
 7066            self.unmark_text(cx);
 7067            self.refresh_inline_completion(true, false, cx);
 7068            cx.emit(EditorEvent::Edited { transaction_id });
 7069        }
 7070    }
 7071
 7072    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7073        self.buffer
 7074            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7075    }
 7076
 7077    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7078        self.buffer
 7079            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7080    }
 7081
 7082    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7083        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7084            let line_mode = s.line_mode;
 7085            s.move_with(|map, selection| {
 7086                let cursor = if selection.is_empty() && !line_mode {
 7087                    movement::left(map, selection.start)
 7088                } else {
 7089                    selection.start
 7090                };
 7091                selection.collapse_to(cursor, SelectionGoal::None);
 7092            });
 7093        })
 7094    }
 7095
 7096    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7097        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7098            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7099        })
 7100    }
 7101
 7102    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7103        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7104            let line_mode = s.line_mode;
 7105            s.move_with(|map, selection| {
 7106                let cursor = if selection.is_empty() && !line_mode {
 7107                    movement::right(map, selection.end)
 7108                } else {
 7109                    selection.end
 7110                };
 7111                selection.collapse_to(cursor, SelectionGoal::None)
 7112            });
 7113        })
 7114    }
 7115
 7116    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7117        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7118            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7119        })
 7120    }
 7121
 7122    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7123        if self.take_rename(true, cx).is_some() {
 7124            return;
 7125        }
 7126
 7127        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7128            cx.propagate();
 7129            return;
 7130        }
 7131
 7132        let text_layout_details = &self.text_layout_details(cx);
 7133        let selection_count = self.selections.count();
 7134        let first_selection = self.selections.first_anchor();
 7135
 7136        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7137            let line_mode = s.line_mode;
 7138            s.move_with(|map, selection| {
 7139                if !selection.is_empty() && !line_mode {
 7140                    selection.goal = SelectionGoal::None;
 7141                }
 7142                let (cursor, goal) = movement::up(
 7143                    map,
 7144                    selection.start,
 7145                    selection.goal,
 7146                    false,
 7147                    text_layout_details,
 7148                );
 7149                selection.collapse_to(cursor, goal);
 7150            });
 7151        });
 7152
 7153        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7154        {
 7155            cx.propagate();
 7156        }
 7157    }
 7158
 7159    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7160        if self.take_rename(true, cx).is_some() {
 7161            return;
 7162        }
 7163
 7164        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7165            cx.propagate();
 7166            return;
 7167        }
 7168
 7169        let text_layout_details = &self.text_layout_details(cx);
 7170
 7171        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7172            let line_mode = s.line_mode;
 7173            s.move_with(|map, selection| {
 7174                if !selection.is_empty() && !line_mode {
 7175                    selection.goal = SelectionGoal::None;
 7176                }
 7177                let (cursor, goal) = movement::up_by_rows(
 7178                    map,
 7179                    selection.start,
 7180                    action.lines,
 7181                    selection.goal,
 7182                    false,
 7183                    text_layout_details,
 7184                );
 7185                selection.collapse_to(cursor, goal);
 7186            });
 7187        })
 7188    }
 7189
 7190    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7191        if self.take_rename(true, cx).is_some() {
 7192            return;
 7193        }
 7194
 7195        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7196            cx.propagate();
 7197            return;
 7198        }
 7199
 7200        let text_layout_details = &self.text_layout_details(cx);
 7201
 7202        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7203            let line_mode = s.line_mode;
 7204            s.move_with(|map, selection| {
 7205                if !selection.is_empty() && !line_mode {
 7206                    selection.goal = SelectionGoal::None;
 7207                }
 7208                let (cursor, goal) = movement::down_by_rows(
 7209                    map,
 7210                    selection.start,
 7211                    action.lines,
 7212                    selection.goal,
 7213                    false,
 7214                    text_layout_details,
 7215                );
 7216                selection.collapse_to(cursor, goal);
 7217            });
 7218        })
 7219    }
 7220
 7221    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7222        let text_layout_details = &self.text_layout_details(cx);
 7223        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7224            s.move_heads_with(|map, head, goal| {
 7225                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7226            })
 7227        })
 7228    }
 7229
 7230    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7231        let text_layout_details = &self.text_layout_details(cx);
 7232        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7233            s.move_heads_with(|map, head, goal| {
 7234                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7235            })
 7236        })
 7237    }
 7238
 7239    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7240        let Some(row_count) = self.visible_row_count() else {
 7241            return;
 7242        };
 7243
 7244        let text_layout_details = &self.text_layout_details(cx);
 7245
 7246        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7247            s.move_heads_with(|map, head, goal| {
 7248                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7249            })
 7250        })
 7251    }
 7252
 7253    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7254        if self.take_rename(true, cx).is_some() {
 7255            return;
 7256        }
 7257
 7258        if self
 7259            .context_menu
 7260            .borrow_mut()
 7261            .as_mut()
 7262            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7263            .unwrap_or(false)
 7264        {
 7265            return;
 7266        }
 7267
 7268        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7269            cx.propagate();
 7270            return;
 7271        }
 7272
 7273        let Some(row_count) = self.visible_row_count() else {
 7274            return;
 7275        };
 7276
 7277        let autoscroll = if action.center_cursor {
 7278            Autoscroll::center()
 7279        } else {
 7280            Autoscroll::fit()
 7281        };
 7282
 7283        let text_layout_details = &self.text_layout_details(cx);
 7284
 7285        self.change_selections(Some(autoscroll), cx, |s| {
 7286            let line_mode = s.line_mode;
 7287            s.move_with(|map, selection| {
 7288                if !selection.is_empty() && !line_mode {
 7289                    selection.goal = SelectionGoal::None;
 7290                }
 7291                let (cursor, goal) = movement::up_by_rows(
 7292                    map,
 7293                    selection.end,
 7294                    row_count,
 7295                    selection.goal,
 7296                    false,
 7297                    text_layout_details,
 7298                );
 7299                selection.collapse_to(cursor, goal);
 7300            });
 7301        });
 7302    }
 7303
 7304    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7305        let text_layout_details = &self.text_layout_details(cx);
 7306        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7307            s.move_heads_with(|map, head, goal| {
 7308                movement::up(map, head, goal, false, text_layout_details)
 7309            })
 7310        })
 7311    }
 7312
 7313    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7314        self.take_rename(true, cx);
 7315
 7316        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7317            cx.propagate();
 7318            return;
 7319        }
 7320
 7321        let text_layout_details = &self.text_layout_details(cx);
 7322        let selection_count = self.selections.count();
 7323        let first_selection = self.selections.first_anchor();
 7324
 7325        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7326            let line_mode = s.line_mode;
 7327            s.move_with(|map, selection| {
 7328                if !selection.is_empty() && !line_mode {
 7329                    selection.goal = SelectionGoal::None;
 7330                }
 7331                let (cursor, goal) = movement::down(
 7332                    map,
 7333                    selection.end,
 7334                    selection.goal,
 7335                    false,
 7336                    text_layout_details,
 7337                );
 7338                selection.collapse_to(cursor, goal);
 7339            });
 7340        });
 7341
 7342        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7343        {
 7344            cx.propagate();
 7345        }
 7346    }
 7347
 7348    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7349        let Some(row_count) = self.visible_row_count() else {
 7350            return;
 7351        };
 7352
 7353        let text_layout_details = &self.text_layout_details(cx);
 7354
 7355        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7356            s.move_heads_with(|map, head, goal| {
 7357                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7358            })
 7359        })
 7360    }
 7361
 7362    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7363        if self.take_rename(true, cx).is_some() {
 7364            return;
 7365        }
 7366
 7367        if self
 7368            .context_menu
 7369            .borrow_mut()
 7370            .as_mut()
 7371            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7372            .unwrap_or(false)
 7373        {
 7374            return;
 7375        }
 7376
 7377        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7378            cx.propagate();
 7379            return;
 7380        }
 7381
 7382        let Some(row_count) = self.visible_row_count() else {
 7383            return;
 7384        };
 7385
 7386        let autoscroll = if action.center_cursor {
 7387            Autoscroll::center()
 7388        } else {
 7389            Autoscroll::fit()
 7390        };
 7391
 7392        let text_layout_details = &self.text_layout_details(cx);
 7393        self.change_selections(Some(autoscroll), cx, |s| {
 7394            let line_mode = s.line_mode;
 7395            s.move_with(|map, selection| {
 7396                if !selection.is_empty() && !line_mode {
 7397                    selection.goal = SelectionGoal::None;
 7398                }
 7399                let (cursor, goal) = movement::down_by_rows(
 7400                    map,
 7401                    selection.end,
 7402                    row_count,
 7403                    selection.goal,
 7404                    false,
 7405                    text_layout_details,
 7406                );
 7407                selection.collapse_to(cursor, goal);
 7408            });
 7409        });
 7410    }
 7411
 7412    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7413        let text_layout_details = &self.text_layout_details(cx);
 7414        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7415            s.move_heads_with(|map, head, goal| {
 7416                movement::down(map, head, goal, false, text_layout_details)
 7417            })
 7418        });
 7419    }
 7420
 7421    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7422        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7423            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7424        }
 7425    }
 7426
 7427    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7428        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7429            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7430        }
 7431    }
 7432
 7433    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7434        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7435            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7436        }
 7437    }
 7438
 7439    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7440        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7441            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7442        }
 7443    }
 7444
 7445    pub fn move_to_previous_word_start(
 7446        &mut self,
 7447        _: &MoveToPreviousWordStart,
 7448        cx: &mut ViewContext<Self>,
 7449    ) {
 7450        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7451            s.move_cursors_with(|map, head, _| {
 7452                (
 7453                    movement::previous_word_start(map, head),
 7454                    SelectionGoal::None,
 7455                )
 7456            });
 7457        })
 7458    }
 7459
 7460    pub fn move_to_previous_subword_start(
 7461        &mut self,
 7462        _: &MoveToPreviousSubwordStart,
 7463        cx: &mut ViewContext<Self>,
 7464    ) {
 7465        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7466            s.move_cursors_with(|map, head, _| {
 7467                (
 7468                    movement::previous_subword_start(map, head),
 7469                    SelectionGoal::None,
 7470                )
 7471            });
 7472        })
 7473    }
 7474
 7475    pub fn select_to_previous_word_start(
 7476        &mut self,
 7477        _: &SelectToPreviousWordStart,
 7478        cx: &mut ViewContext<Self>,
 7479    ) {
 7480        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7481            s.move_heads_with(|map, head, _| {
 7482                (
 7483                    movement::previous_word_start(map, head),
 7484                    SelectionGoal::None,
 7485                )
 7486            });
 7487        })
 7488    }
 7489
 7490    pub fn select_to_previous_subword_start(
 7491        &mut self,
 7492        _: &SelectToPreviousSubwordStart,
 7493        cx: &mut ViewContext<Self>,
 7494    ) {
 7495        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7496            s.move_heads_with(|map, head, _| {
 7497                (
 7498                    movement::previous_subword_start(map, head),
 7499                    SelectionGoal::None,
 7500                )
 7501            });
 7502        })
 7503    }
 7504
 7505    pub fn delete_to_previous_word_start(
 7506        &mut self,
 7507        action: &DeleteToPreviousWordStart,
 7508        cx: &mut ViewContext<Self>,
 7509    ) {
 7510        self.transact(cx, |this, cx| {
 7511            this.select_autoclose_pair(cx);
 7512            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7513                let line_mode = s.line_mode;
 7514                s.move_with(|map, selection| {
 7515                    if selection.is_empty() && !line_mode {
 7516                        let cursor = if action.ignore_newlines {
 7517                            movement::previous_word_start(map, selection.head())
 7518                        } else {
 7519                            movement::previous_word_start_or_newline(map, selection.head())
 7520                        };
 7521                        selection.set_head(cursor, SelectionGoal::None);
 7522                    }
 7523                });
 7524            });
 7525            this.insert("", cx);
 7526        });
 7527    }
 7528
 7529    pub fn delete_to_previous_subword_start(
 7530        &mut self,
 7531        _: &DeleteToPreviousSubwordStart,
 7532        cx: &mut ViewContext<Self>,
 7533    ) {
 7534        self.transact(cx, |this, cx| {
 7535            this.select_autoclose_pair(cx);
 7536            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7537                let line_mode = s.line_mode;
 7538                s.move_with(|map, selection| {
 7539                    if selection.is_empty() && !line_mode {
 7540                        let cursor = movement::previous_subword_start(map, selection.head());
 7541                        selection.set_head(cursor, SelectionGoal::None);
 7542                    }
 7543                });
 7544            });
 7545            this.insert("", cx);
 7546        });
 7547    }
 7548
 7549    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7550        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7551            s.move_cursors_with(|map, head, _| {
 7552                (movement::next_word_end(map, head), SelectionGoal::None)
 7553            });
 7554        })
 7555    }
 7556
 7557    pub fn move_to_next_subword_end(
 7558        &mut self,
 7559        _: &MoveToNextSubwordEnd,
 7560        cx: &mut ViewContext<Self>,
 7561    ) {
 7562        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7563            s.move_cursors_with(|map, head, _| {
 7564                (movement::next_subword_end(map, head), SelectionGoal::None)
 7565            });
 7566        })
 7567    }
 7568
 7569    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7570        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7571            s.move_heads_with(|map, head, _| {
 7572                (movement::next_word_end(map, head), SelectionGoal::None)
 7573            });
 7574        })
 7575    }
 7576
 7577    pub fn select_to_next_subword_end(
 7578        &mut self,
 7579        _: &SelectToNextSubwordEnd,
 7580        cx: &mut ViewContext<Self>,
 7581    ) {
 7582        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7583            s.move_heads_with(|map, head, _| {
 7584                (movement::next_subword_end(map, head), SelectionGoal::None)
 7585            });
 7586        })
 7587    }
 7588
 7589    pub fn delete_to_next_word_end(
 7590        &mut self,
 7591        action: &DeleteToNextWordEnd,
 7592        cx: &mut ViewContext<Self>,
 7593    ) {
 7594        self.transact(cx, |this, cx| {
 7595            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7596                let line_mode = s.line_mode;
 7597                s.move_with(|map, selection| {
 7598                    if selection.is_empty() && !line_mode {
 7599                        let cursor = if action.ignore_newlines {
 7600                            movement::next_word_end(map, selection.head())
 7601                        } else {
 7602                            movement::next_word_end_or_newline(map, selection.head())
 7603                        };
 7604                        selection.set_head(cursor, SelectionGoal::None);
 7605                    }
 7606                });
 7607            });
 7608            this.insert("", cx);
 7609        });
 7610    }
 7611
 7612    pub fn delete_to_next_subword_end(
 7613        &mut self,
 7614        _: &DeleteToNextSubwordEnd,
 7615        cx: &mut ViewContext<Self>,
 7616    ) {
 7617        self.transact(cx, |this, cx| {
 7618            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7619                s.move_with(|map, selection| {
 7620                    if selection.is_empty() {
 7621                        let cursor = movement::next_subword_end(map, selection.head());
 7622                        selection.set_head(cursor, SelectionGoal::None);
 7623                    }
 7624                });
 7625            });
 7626            this.insert("", cx);
 7627        });
 7628    }
 7629
 7630    pub fn move_to_beginning_of_line(
 7631        &mut self,
 7632        action: &MoveToBeginningOfLine,
 7633        cx: &mut ViewContext<Self>,
 7634    ) {
 7635        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7636            s.move_cursors_with(|map, head, _| {
 7637                (
 7638                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7639                    SelectionGoal::None,
 7640                )
 7641            });
 7642        })
 7643    }
 7644
 7645    pub fn select_to_beginning_of_line(
 7646        &mut self,
 7647        action: &SelectToBeginningOfLine,
 7648        cx: &mut ViewContext<Self>,
 7649    ) {
 7650        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7651            s.move_heads_with(|map, head, _| {
 7652                (
 7653                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7654                    SelectionGoal::None,
 7655                )
 7656            });
 7657        });
 7658    }
 7659
 7660    pub fn delete_to_beginning_of_line(
 7661        &mut self,
 7662        _: &DeleteToBeginningOfLine,
 7663        cx: &mut ViewContext<Self>,
 7664    ) {
 7665        self.transact(cx, |this, cx| {
 7666            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7667                s.move_with(|_, selection| {
 7668                    selection.reversed = true;
 7669                });
 7670            });
 7671
 7672            this.select_to_beginning_of_line(
 7673                &SelectToBeginningOfLine {
 7674                    stop_at_soft_wraps: false,
 7675                },
 7676                cx,
 7677            );
 7678            this.backspace(&Backspace, cx);
 7679        });
 7680    }
 7681
 7682    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7683        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7684            s.move_cursors_with(|map, head, _| {
 7685                (
 7686                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7687                    SelectionGoal::None,
 7688                )
 7689            });
 7690        })
 7691    }
 7692
 7693    pub fn select_to_end_of_line(
 7694        &mut self,
 7695        action: &SelectToEndOfLine,
 7696        cx: &mut ViewContext<Self>,
 7697    ) {
 7698        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7699            s.move_heads_with(|map, head, _| {
 7700                (
 7701                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7702                    SelectionGoal::None,
 7703                )
 7704            });
 7705        })
 7706    }
 7707
 7708    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7709        self.transact(cx, |this, cx| {
 7710            this.select_to_end_of_line(
 7711                &SelectToEndOfLine {
 7712                    stop_at_soft_wraps: false,
 7713                },
 7714                cx,
 7715            );
 7716            this.delete(&Delete, cx);
 7717        });
 7718    }
 7719
 7720    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7721        self.transact(cx, |this, cx| {
 7722            this.select_to_end_of_line(
 7723                &SelectToEndOfLine {
 7724                    stop_at_soft_wraps: false,
 7725                },
 7726                cx,
 7727            );
 7728            this.cut(&Cut, cx);
 7729        });
 7730    }
 7731
 7732    pub fn move_to_start_of_paragraph(
 7733        &mut self,
 7734        _: &MoveToStartOfParagraph,
 7735        cx: &mut ViewContext<Self>,
 7736    ) {
 7737        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7738            cx.propagate();
 7739            return;
 7740        }
 7741
 7742        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7743            s.move_with(|map, selection| {
 7744                selection.collapse_to(
 7745                    movement::start_of_paragraph(map, selection.head(), 1),
 7746                    SelectionGoal::None,
 7747                )
 7748            });
 7749        })
 7750    }
 7751
 7752    pub fn move_to_end_of_paragraph(
 7753        &mut self,
 7754        _: &MoveToEndOfParagraph,
 7755        cx: &mut ViewContext<Self>,
 7756    ) {
 7757        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7758            cx.propagate();
 7759            return;
 7760        }
 7761
 7762        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7763            s.move_with(|map, selection| {
 7764                selection.collapse_to(
 7765                    movement::end_of_paragraph(map, selection.head(), 1),
 7766                    SelectionGoal::None,
 7767                )
 7768            });
 7769        })
 7770    }
 7771
 7772    pub fn select_to_start_of_paragraph(
 7773        &mut self,
 7774        _: &SelectToStartOfParagraph,
 7775        cx: &mut ViewContext<Self>,
 7776    ) {
 7777        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7778            cx.propagate();
 7779            return;
 7780        }
 7781
 7782        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7783            s.move_heads_with(|map, head, _| {
 7784                (
 7785                    movement::start_of_paragraph(map, head, 1),
 7786                    SelectionGoal::None,
 7787                )
 7788            });
 7789        })
 7790    }
 7791
 7792    pub fn select_to_end_of_paragraph(
 7793        &mut self,
 7794        _: &SelectToEndOfParagraph,
 7795        cx: &mut ViewContext<Self>,
 7796    ) {
 7797        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7798            cx.propagate();
 7799            return;
 7800        }
 7801
 7802        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7803            s.move_heads_with(|map, head, _| {
 7804                (
 7805                    movement::end_of_paragraph(map, head, 1),
 7806                    SelectionGoal::None,
 7807                )
 7808            });
 7809        })
 7810    }
 7811
 7812    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7813        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7814            cx.propagate();
 7815            return;
 7816        }
 7817
 7818        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7819            s.select_ranges(vec![0..0]);
 7820        });
 7821    }
 7822
 7823    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7824        let mut selection = self.selections.last::<Point>(cx);
 7825        selection.set_head(Point::zero(), SelectionGoal::None);
 7826
 7827        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7828            s.select(vec![selection]);
 7829        });
 7830    }
 7831
 7832    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7833        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7834            cx.propagate();
 7835            return;
 7836        }
 7837
 7838        let cursor = self.buffer.read(cx).read(cx).len();
 7839        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7840            s.select_ranges(vec![cursor..cursor])
 7841        });
 7842    }
 7843
 7844    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7845        self.nav_history = nav_history;
 7846    }
 7847
 7848    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7849        self.nav_history.as_ref()
 7850    }
 7851
 7852    fn push_to_nav_history(
 7853        &mut self,
 7854        cursor_anchor: Anchor,
 7855        new_position: Option<Point>,
 7856        cx: &mut ViewContext<Self>,
 7857    ) {
 7858        if let Some(nav_history) = self.nav_history.as_mut() {
 7859            let buffer = self.buffer.read(cx).read(cx);
 7860            let cursor_position = cursor_anchor.to_point(&buffer);
 7861            let scroll_state = self.scroll_manager.anchor();
 7862            let scroll_top_row = scroll_state.top_row(&buffer);
 7863            drop(buffer);
 7864
 7865            if let Some(new_position) = new_position {
 7866                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7867                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7868                    return;
 7869                }
 7870            }
 7871
 7872            nav_history.push(
 7873                Some(NavigationData {
 7874                    cursor_anchor,
 7875                    cursor_position,
 7876                    scroll_anchor: scroll_state,
 7877                    scroll_top_row,
 7878                }),
 7879                cx,
 7880            );
 7881        }
 7882    }
 7883
 7884    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7885        let buffer = self.buffer.read(cx).snapshot(cx);
 7886        let mut selection = self.selections.first::<usize>(cx);
 7887        selection.set_head(buffer.len(), SelectionGoal::None);
 7888        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7889            s.select(vec![selection]);
 7890        });
 7891    }
 7892
 7893    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7894        let end = self.buffer.read(cx).read(cx).len();
 7895        self.change_selections(None, cx, |s| {
 7896            s.select_ranges(vec![0..end]);
 7897        });
 7898    }
 7899
 7900    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7901        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7902        let mut selections = self.selections.all::<Point>(cx);
 7903        let max_point = display_map.buffer_snapshot.max_point();
 7904        for selection in &mut selections {
 7905            let rows = selection.spanned_rows(true, &display_map);
 7906            selection.start = Point::new(rows.start.0, 0);
 7907            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7908            selection.reversed = false;
 7909        }
 7910        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7911            s.select(selections);
 7912        });
 7913    }
 7914
 7915    pub fn split_selection_into_lines(
 7916        &mut self,
 7917        _: &SplitSelectionIntoLines,
 7918        cx: &mut ViewContext<Self>,
 7919    ) {
 7920        let mut to_unfold = Vec::new();
 7921        let mut new_selection_ranges = Vec::new();
 7922        {
 7923            let selections = self.selections.all::<Point>(cx);
 7924            let buffer = self.buffer.read(cx).read(cx);
 7925            for selection in selections {
 7926                for row in selection.start.row..selection.end.row {
 7927                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7928                    new_selection_ranges.push(cursor..cursor);
 7929                }
 7930                new_selection_ranges.push(selection.end..selection.end);
 7931                to_unfold.push(selection.start..selection.end);
 7932            }
 7933        }
 7934        self.unfold_ranges(&to_unfold, true, true, cx);
 7935        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7936            s.select_ranges(new_selection_ranges);
 7937        });
 7938    }
 7939
 7940    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7941        self.add_selection(true, cx);
 7942    }
 7943
 7944    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7945        self.add_selection(false, cx);
 7946    }
 7947
 7948    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7949        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7950        let mut selections = self.selections.all::<Point>(cx);
 7951        let text_layout_details = self.text_layout_details(cx);
 7952        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7953            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7954            let range = oldest_selection.display_range(&display_map).sorted();
 7955
 7956            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7957            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7958            let positions = start_x.min(end_x)..start_x.max(end_x);
 7959
 7960            selections.clear();
 7961            let mut stack = Vec::new();
 7962            for row in range.start.row().0..=range.end.row().0 {
 7963                if let Some(selection) = self.selections.build_columnar_selection(
 7964                    &display_map,
 7965                    DisplayRow(row),
 7966                    &positions,
 7967                    oldest_selection.reversed,
 7968                    &text_layout_details,
 7969                ) {
 7970                    stack.push(selection.id);
 7971                    selections.push(selection);
 7972                }
 7973            }
 7974
 7975            if above {
 7976                stack.reverse();
 7977            }
 7978
 7979            AddSelectionsState { above, stack }
 7980        });
 7981
 7982        let last_added_selection = *state.stack.last().unwrap();
 7983        let mut new_selections = Vec::new();
 7984        if above == state.above {
 7985            let end_row = if above {
 7986                DisplayRow(0)
 7987            } else {
 7988                display_map.max_point().row()
 7989            };
 7990
 7991            'outer: for selection in selections {
 7992                if selection.id == last_added_selection {
 7993                    let range = selection.display_range(&display_map).sorted();
 7994                    debug_assert_eq!(range.start.row(), range.end.row());
 7995                    let mut row = range.start.row();
 7996                    let positions =
 7997                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7998                            px(start)..px(end)
 7999                        } else {
 8000                            let start_x =
 8001                                display_map.x_for_display_point(range.start, &text_layout_details);
 8002                            let end_x =
 8003                                display_map.x_for_display_point(range.end, &text_layout_details);
 8004                            start_x.min(end_x)..start_x.max(end_x)
 8005                        };
 8006
 8007                    while row != end_row {
 8008                        if above {
 8009                            row.0 -= 1;
 8010                        } else {
 8011                            row.0 += 1;
 8012                        }
 8013
 8014                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8015                            &display_map,
 8016                            row,
 8017                            &positions,
 8018                            selection.reversed,
 8019                            &text_layout_details,
 8020                        ) {
 8021                            state.stack.push(new_selection.id);
 8022                            if above {
 8023                                new_selections.push(new_selection);
 8024                                new_selections.push(selection);
 8025                            } else {
 8026                                new_selections.push(selection);
 8027                                new_selections.push(new_selection);
 8028                            }
 8029
 8030                            continue 'outer;
 8031                        }
 8032                    }
 8033                }
 8034
 8035                new_selections.push(selection);
 8036            }
 8037        } else {
 8038            new_selections = selections;
 8039            new_selections.retain(|s| s.id != last_added_selection);
 8040            state.stack.pop();
 8041        }
 8042
 8043        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8044            s.select(new_selections);
 8045        });
 8046        if state.stack.len() > 1 {
 8047            self.add_selections_state = Some(state);
 8048        }
 8049    }
 8050
 8051    pub fn select_next_match_internal(
 8052        &mut self,
 8053        display_map: &DisplaySnapshot,
 8054        replace_newest: bool,
 8055        autoscroll: Option<Autoscroll>,
 8056        cx: &mut ViewContext<Self>,
 8057    ) -> Result<()> {
 8058        fn select_next_match_ranges(
 8059            this: &mut Editor,
 8060            range: Range<usize>,
 8061            replace_newest: bool,
 8062            auto_scroll: Option<Autoscroll>,
 8063            cx: &mut ViewContext<Editor>,
 8064        ) {
 8065            this.unfold_ranges(&[range.clone()], false, true, cx);
 8066            this.change_selections(auto_scroll, cx, |s| {
 8067                if replace_newest {
 8068                    s.delete(s.newest_anchor().id);
 8069                }
 8070                s.insert_range(range.clone());
 8071            });
 8072        }
 8073
 8074        let buffer = &display_map.buffer_snapshot;
 8075        let mut selections = self.selections.all::<usize>(cx);
 8076        if let Some(mut select_next_state) = self.select_next_state.take() {
 8077            let query = &select_next_state.query;
 8078            if !select_next_state.done {
 8079                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8080                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8081                let mut next_selected_range = None;
 8082
 8083                let bytes_after_last_selection =
 8084                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8085                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8086                let query_matches = query
 8087                    .stream_find_iter(bytes_after_last_selection)
 8088                    .map(|result| (last_selection.end, result))
 8089                    .chain(
 8090                        query
 8091                            .stream_find_iter(bytes_before_first_selection)
 8092                            .map(|result| (0, result)),
 8093                    );
 8094
 8095                for (start_offset, query_match) in query_matches {
 8096                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8097                    let offset_range =
 8098                        start_offset + query_match.start()..start_offset + query_match.end();
 8099                    let display_range = offset_range.start.to_display_point(display_map)
 8100                        ..offset_range.end.to_display_point(display_map);
 8101
 8102                    if !select_next_state.wordwise
 8103                        || (!movement::is_inside_word(display_map, display_range.start)
 8104                            && !movement::is_inside_word(display_map, display_range.end))
 8105                    {
 8106                        // TODO: This is n^2, because we might check all the selections
 8107                        if !selections
 8108                            .iter()
 8109                            .any(|selection| selection.range().overlaps(&offset_range))
 8110                        {
 8111                            next_selected_range = Some(offset_range);
 8112                            break;
 8113                        }
 8114                    }
 8115                }
 8116
 8117                if let Some(next_selected_range) = next_selected_range {
 8118                    select_next_match_ranges(
 8119                        self,
 8120                        next_selected_range,
 8121                        replace_newest,
 8122                        autoscroll,
 8123                        cx,
 8124                    );
 8125                } else {
 8126                    select_next_state.done = true;
 8127                }
 8128            }
 8129
 8130            self.select_next_state = Some(select_next_state);
 8131        } else {
 8132            let mut only_carets = true;
 8133            let mut same_text_selected = true;
 8134            let mut selected_text = None;
 8135
 8136            let mut selections_iter = selections.iter().peekable();
 8137            while let Some(selection) = selections_iter.next() {
 8138                if selection.start != selection.end {
 8139                    only_carets = false;
 8140                }
 8141
 8142                if same_text_selected {
 8143                    if selected_text.is_none() {
 8144                        selected_text =
 8145                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8146                    }
 8147
 8148                    if let Some(next_selection) = selections_iter.peek() {
 8149                        if next_selection.range().len() == selection.range().len() {
 8150                            let next_selected_text = buffer
 8151                                .text_for_range(next_selection.range())
 8152                                .collect::<String>();
 8153                            if Some(next_selected_text) != selected_text {
 8154                                same_text_selected = false;
 8155                                selected_text = None;
 8156                            }
 8157                        } else {
 8158                            same_text_selected = false;
 8159                            selected_text = None;
 8160                        }
 8161                    }
 8162                }
 8163            }
 8164
 8165            if only_carets {
 8166                for selection in &mut selections {
 8167                    let word_range = movement::surrounding_word(
 8168                        display_map,
 8169                        selection.start.to_display_point(display_map),
 8170                    );
 8171                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8172                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8173                    selection.goal = SelectionGoal::None;
 8174                    selection.reversed = false;
 8175                    select_next_match_ranges(
 8176                        self,
 8177                        selection.start..selection.end,
 8178                        replace_newest,
 8179                        autoscroll,
 8180                        cx,
 8181                    );
 8182                }
 8183
 8184                if selections.len() == 1 {
 8185                    let selection = selections
 8186                        .last()
 8187                        .expect("ensured that there's only one selection");
 8188                    let query = buffer
 8189                        .text_for_range(selection.start..selection.end)
 8190                        .collect::<String>();
 8191                    let is_empty = query.is_empty();
 8192                    let select_state = SelectNextState {
 8193                        query: AhoCorasick::new(&[query])?,
 8194                        wordwise: true,
 8195                        done: is_empty,
 8196                    };
 8197                    self.select_next_state = Some(select_state);
 8198                } else {
 8199                    self.select_next_state = None;
 8200                }
 8201            } else if let Some(selected_text) = selected_text {
 8202                self.select_next_state = Some(SelectNextState {
 8203                    query: AhoCorasick::new(&[selected_text])?,
 8204                    wordwise: false,
 8205                    done: false,
 8206                });
 8207                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8208            }
 8209        }
 8210        Ok(())
 8211    }
 8212
 8213    pub fn select_all_matches(
 8214        &mut self,
 8215        _action: &SelectAllMatches,
 8216        cx: &mut ViewContext<Self>,
 8217    ) -> Result<()> {
 8218        self.push_to_selection_history();
 8219        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8220
 8221        self.select_next_match_internal(&display_map, false, None, cx)?;
 8222        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8223            return Ok(());
 8224        };
 8225        if select_next_state.done {
 8226            return Ok(());
 8227        }
 8228
 8229        let mut new_selections = self.selections.all::<usize>(cx);
 8230
 8231        let buffer = &display_map.buffer_snapshot;
 8232        let query_matches = select_next_state
 8233            .query
 8234            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8235
 8236        for query_match in query_matches {
 8237            let query_match = query_match.unwrap(); // can only fail due to I/O
 8238            let offset_range = query_match.start()..query_match.end();
 8239            let display_range = offset_range.start.to_display_point(&display_map)
 8240                ..offset_range.end.to_display_point(&display_map);
 8241
 8242            if !select_next_state.wordwise
 8243                || (!movement::is_inside_word(&display_map, display_range.start)
 8244                    && !movement::is_inside_word(&display_map, display_range.end))
 8245            {
 8246                self.selections.change_with(cx, |selections| {
 8247                    new_selections.push(Selection {
 8248                        id: selections.new_selection_id(),
 8249                        start: offset_range.start,
 8250                        end: offset_range.end,
 8251                        reversed: false,
 8252                        goal: SelectionGoal::None,
 8253                    });
 8254                });
 8255            }
 8256        }
 8257
 8258        new_selections.sort_by_key(|selection| selection.start);
 8259        let mut ix = 0;
 8260        while ix + 1 < new_selections.len() {
 8261            let current_selection = &new_selections[ix];
 8262            let next_selection = &new_selections[ix + 1];
 8263            if current_selection.range().overlaps(&next_selection.range()) {
 8264                if current_selection.id < next_selection.id {
 8265                    new_selections.remove(ix + 1);
 8266                } else {
 8267                    new_selections.remove(ix);
 8268                }
 8269            } else {
 8270                ix += 1;
 8271            }
 8272        }
 8273
 8274        select_next_state.done = true;
 8275        self.unfold_ranges(
 8276            &new_selections
 8277                .iter()
 8278                .map(|selection| selection.range())
 8279                .collect::<Vec<_>>(),
 8280            false,
 8281            false,
 8282            cx,
 8283        );
 8284        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8285            selections.select(new_selections)
 8286        });
 8287
 8288        Ok(())
 8289    }
 8290
 8291    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8292        self.push_to_selection_history();
 8293        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8294        self.select_next_match_internal(
 8295            &display_map,
 8296            action.replace_newest,
 8297            Some(Autoscroll::newest()),
 8298            cx,
 8299        )?;
 8300        Ok(())
 8301    }
 8302
 8303    pub fn select_previous(
 8304        &mut self,
 8305        action: &SelectPrevious,
 8306        cx: &mut ViewContext<Self>,
 8307    ) -> Result<()> {
 8308        self.push_to_selection_history();
 8309        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8310        let buffer = &display_map.buffer_snapshot;
 8311        let mut selections = self.selections.all::<usize>(cx);
 8312        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8313            let query = &select_prev_state.query;
 8314            if !select_prev_state.done {
 8315                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8316                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8317                let mut next_selected_range = None;
 8318                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8319                let bytes_before_last_selection =
 8320                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8321                let bytes_after_first_selection =
 8322                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8323                let query_matches = query
 8324                    .stream_find_iter(bytes_before_last_selection)
 8325                    .map(|result| (last_selection.start, result))
 8326                    .chain(
 8327                        query
 8328                            .stream_find_iter(bytes_after_first_selection)
 8329                            .map(|result| (buffer.len(), result)),
 8330                    );
 8331                for (end_offset, query_match) in query_matches {
 8332                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8333                    let offset_range =
 8334                        end_offset - query_match.end()..end_offset - query_match.start();
 8335                    let display_range = offset_range.start.to_display_point(&display_map)
 8336                        ..offset_range.end.to_display_point(&display_map);
 8337
 8338                    if !select_prev_state.wordwise
 8339                        || (!movement::is_inside_word(&display_map, display_range.start)
 8340                            && !movement::is_inside_word(&display_map, display_range.end))
 8341                    {
 8342                        next_selected_range = Some(offset_range);
 8343                        break;
 8344                    }
 8345                }
 8346
 8347                if let Some(next_selected_range) = next_selected_range {
 8348                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8349                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8350                        if action.replace_newest {
 8351                            s.delete(s.newest_anchor().id);
 8352                        }
 8353                        s.insert_range(next_selected_range);
 8354                    });
 8355                } else {
 8356                    select_prev_state.done = true;
 8357                }
 8358            }
 8359
 8360            self.select_prev_state = Some(select_prev_state);
 8361        } else {
 8362            let mut only_carets = true;
 8363            let mut same_text_selected = true;
 8364            let mut selected_text = None;
 8365
 8366            let mut selections_iter = selections.iter().peekable();
 8367            while let Some(selection) = selections_iter.next() {
 8368                if selection.start != selection.end {
 8369                    only_carets = false;
 8370                }
 8371
 8372                if same_text_selected {
 8373                    if selected_text.is_none() {
 8374                        selected_text =
 8375                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8376                    }
 8377
 8378                    if let Some(next_selection) = selections_iter.peek() {
 8379                        if next_selection.range().len() == selection.range().len() {
 8380                            let next_selected_text = buffer
 8381                                .text_for_range(next_selection.range())
 8382                                .collect::<String>();
 8383                            if Some(next_selected_text) != selected_text {
 8384                                same_text_selected = false;
 8385                                selected_text = None;
 8386                            }
 8387                        } else {
 8388                            same_text_selected = false;
 8389                            selected_text = None;
 8390                        }
 8391                    }
 8392                }
 8393            }
 8394
 8395            if only_carets {
 8396                for selection in &mut selections {
 8397                    let word_range = movement::surrounding_word(
 8398                        &display_map,
 8399                        selection.start.to_display_point(&display_map),
 8400                    );
 8401                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8402                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8403                    selection.goal = SelectionGoal::None;
 8404                    selection.reversed = false;
 8405                }
 8406                if selections.len() == 1 {
 8407                    let selection = selections
 8408                        .last()
 8409                        .expect("ensured that there's only one selection");
 8410                    let query = buffer
 8411                        .text_for_range(selection.start..selection.end)
 8412                        .collect::<String>();
 8413                    let is_empty = query.is_empty();
 8414                    let select_state = SelectNextState {
 8415                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8416                        wordwise: true,
 8417                        done: is_empty,
 8418                    };
 8419                    self.select_prev_state = Some(select_state);
 8420                } else {
 8421                    self.select_prev_state = None;
 8422                }
 8423
 8424                self.unfold_ranges(
 8425                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8426                    false,
 8427                    true,
 8428                    cx,
 8429                );
 8430                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8431                    s.select(selections);
 8432                });
 8433            } else if let Some(selected_text) = selected_text {
 8434                self.select_prev_state = Some(SelectNextState {
 8435                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8436                    wordwise: false,
 8437                    done: false,
 8438                });
 8439                self.select_previous(action, cx)?;
 8440            }
 8441        }
 8442        Ok(())
 8443    }
 8444
 8445    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8446        if self.read_only(cx) {
 8447            return;
 8448        }
 8449        let text_layout_details = &self.text_layout_details(cx);
 8450        self.transact(cx, |this, cx| {
 8451            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8452            let mut edits = Vec::new();
 8453            let mut selection_edit_ranges = Vec::new();
 8454            let mut last_toggled_row = None;
 8455            let snapshot = this.buffer.read(cx).read(cx);
 8456            let empty_str: Arc<str> = Arc::default();
 8457            let mut suffixes_inserted = Vec::new();
 8458            let ignore_indent = action.ignore_indent;
 8459
 8460            fn comment_prefix_range(
 8461                snapshot: &MultiBufferSnapshot,
 8462                row: MultiBufferRow,
 8463                comment_prefix: &str,
 8464                comment_prefix_whitespace: &str,
 8465                ignore_indent: bool,
 8466            ) -> Range<Point> {
 8467                let indent_size = if ignore_indent {
 8468                    0
 8469                } else {
 8470                    snapshot.indent_size_for_line(row).len
 8471                };
 8472
 8473                let start = Point::new(row.0, indent_size);
 8474
 8475                let mut line_bytes = snapshot
 8476                    .bytes_in_range(start..snapshot.max_point())
 8477                    .flatten()
 8478                    .copied();
 8479
 8480                // If this line currently begins with the line comment prefix, then record
 8481                // the range containing the prefix.
 8482                if line_bytes
 8483                    .by_ref()
 8484                    .take(comment_prefix.len())
 8485                    .eq(comment_prefix.bytes())
 8486                {
 8487                    // Include any whitespace that matches the comment prefix.
 8488                    let matching_whitespace_len = line_bytes
 8489                        .zip(comment_prefix_whitespace.bytes())
 8490                        .take_while(|(a, b)| a == b)
 8491                        .count() as u32;
 8492                    let end = Point::new(
 8493                        start.row,
 8494                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8495                    );
 8496                    start..end
 8497                } else {
 8498                    start..start
 8499                }
 8500            }
 8501
 8502            fn comment_suffix_range(
 8503                snapshot: &MultiBufferSnapshot,
 8504                row: MultiBufferRow,
 8505                comment_suffix: &str,
 8506                comment_suffix_has_leading_space: bool,
 8507            ) -> Range<Point> {
 8508                let end = Point::new(row.0, snapshot.line_len(row));
 8509                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8510
 8511                let mut line_end_bytes = snapshot
 8512                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8513                    .flatten()
 8514                    .copied();
 8515
 8516                let leading_space_len = if suffix_start_column > 0
 8517                    && line_end_bytes.next() == Some(b' ')
 8518                    && comment_suffix_has_leading_space
 8519                {
 8520                    1
 8521                } else {
 8522                    0
 8523                };
 8524
 8525                // If this line currently begins with the line comment prefix, then record
 8526                // the range containing the prefix.
 8527                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8528                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8529                    start..end
 8530                } else {
 8531                    end..end
 8532                }
 8533            }
 8534
 8535            // TODO: Handle selections that cross excerpts
 8536            for selection in &mut selections {
 8537                let start_column = snapshot
 8538                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8539                    .len;
 8540                let language = if let Some(language) =
 8541                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8542                {
 8543                    language
 8544                } else {
 8545                    continue;
 8546                };
 8547
 8548                selection_edit_ranges.clear();
 8549
 8550                // If multiple selections contain a given row, avoid processing that
 8551                // row more than once.
 8552                let mut start_row = MultiBufferRow(selection.start.row);
 8553                if last_toggled_row == Some(start_row) {
 8554                    start_row = start_row.next_row();
 8555                }
 8556                let end_row =
 8557                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8558                        MultiBufferRow(selection.end.row - 1)
 8559                    } else {
 8560                        MultiBufferRow(selection.end.row)
 8561                    };
 8562                last_toggled_row = Some(end_row);
 8563
 8564                if start_row > end_row {
 8565                    continue;
 8566                }
 8567
 8568                // If the language has line comments, toggle those.
 8569                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8570
 8571                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8572                if ignore_indent {
 8573                    full_comment_prefixes = full_comment_prefixes
 8574                        .into_iter()
 8575                        .map(|s| Arc::from(s.trim_end()))
 8576                        .collect();
 8577                }
 8578
 8579                if !full_comment_prefixes.is_empty() {
 8580                    let first_prefix = full_comment_prefixes
 8581                        .first()
 8582                        .expect("prefixes is non-empty");
 8583                    let prefix_trimmed_lengths = full_comment_prefixes
 8584                        .iter()
 8585                        .map(|p| p.trim_end_matches(' ').len())
 8586                        .collect::<SmallVec<[usize; 4]>>();
 8587
 8588                    let mut all_selection_lines_are_comments = true;
 8589
 8590                    for row in start_row.0..=end_row.0 {
 8591                        let row = MultiBufferRow(row);
 8592                        if start_row < end_row && snapshot.is_line_blank(row) {
 8593                            continue;
 8594                        }
 8595
 8596                        let prefix_range = full_comment_prefixes
 8597                            .iter()
 8598                            .zip(prefix_trimmed_lengths.iter().copied())
 8599                            .map(|(prefix, trimmed_prefix_len)| {
 8600                                comment_prefix_range(
 8601                                    snapshot.deref(),
 8602                                    row,
 8603                                    &prefix[..trimmed_prefix_len],
 8604                                    &prefix[trimmed_prefix_len..],
 8605                                    ignore_indent,
 8606                                )
 8607                            })
 8608                            .max_by_key(|range| range.end.column - range.start.column)
 8609                            .expect("prefixes is non-empty");
 8610
 8611                        if prefix_range.is_empty() {
 8612                            all_selection_lines_are_comments = false;
 8613                        }
 8614
 8615                        selection_edit_ranges.push(prefix_range);
 8616                    }
 8617
 8618                    if all_selection_lines_are_comments {
 8619                        edits.extend(
 8620                            selection_edit_ranges
 8621                                .iter()
 8622                                .cloned()
 8623                                .map(|range| (range, empty_str.clone())),
 8624                        );
 8625                    } else {
 8626                        let min_column = selection_edit_ranges
 8627                            .iter()
 8628                            .map(|range| range.start.column)
 8629                            .min()
 8630                            .unwrap_or(0);
 8631                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8632                            let position = Point::new(range.start.row, min_column);
 8633                            (position..position, first_prefix.clone())
 8634                        }));
 8635                    }
 8636                } else if let Some((full_comment_prefix, comment_suffix)) =
 8637                    language.block_comment_delimiters()
 8638                {
 8639                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8640                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8641                    let prefix_range = comment_prefix_range(
 8642                        snapshot.deref(),
 8643                        start_row,
 8644                        comment_prefix,
 8645                        comment_prefix_whitespace,
 8646                        ignore_indent,
 8647                    );
 8648                    let suffix_range = comment_suffix_range(
 8649                        snapshot.deref(),
 8650                        end_row,
 8651                        comment_suffix.trim_start_matches(' '),
 8652                        comment_suffix.starts_with(' '),
 8653                    );
 8654
 8655                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8656                        edits.push((
 8657                            prefix_range.start..prefix_range.start,
 8658                            full_comment_prefix.clone(),
 8659                        ));
 8660                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8661                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8662                    } else {
 8663                        edits.push((prefix_range, empty_str.clone()));
 8664                        edits.push((suffix_range, empty_str.clone()));
 8665                    }
 8666                } else {
 8667                    continue;
 8668                }
 8669            }
 8670
 8671            drop(snapshot);
 8672            this.buffer.update(cx, |buffer, cx| {
 8673                buffer.edit(edits, None, cx);
 8674            });
 8675
 8676            // Adjust selections so that they end before any comment suffixes that
 8677            // were inserted.
 8678            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8679            let mut selections = this.selections.all::<Point>(cx);
 8680            let snapshot = this.buffer.read(cx).read(cx);
 8681            for selection in &mut selections {
 8682                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8683                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8684                        Ordering::Less => {
 8685                            suffixes_inserted.next();
 8686                            continue;
 8687                        }
 8688                        Ordering::Greater => break,
 8689                        Ordering::Equal => {
 8690                            if selection.end.column == snapshot.line_len(row) {
 8691                                if selection.is_empty() {
 8692                                    selection.start.column -= suffix_len as u32;
 8693                                }
 8694                                selection.end.column -= suffix_len as u32;
 8695                            }
 8696                            break;
 8697                        }
 8698                    }
 8699                }
 8700            }
 8701
 8702            drop(snapshot);
 8703            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8704
 8705            let selections = this.selections.all::<Point>(cx);
 8706            let selections_on_single_row = selections.windows(2).all(|selections| {
 8707                selections[0].start.row == selections[1].start.row
 8708                    && selections[0].end.row == selections[1].end.row
 8709                    && selections[0].start.row == selections[0].end.row
 8710            });
 8711            let selections_selecting = selections
 8712                .iter()
 8713                .any(|selection| selection.start != selection.end);
 8714            let advance_downwards = action.advance_downwards
 8715                && selections_on_single_row
 8716                && !selections_selecting
 8717                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8718
 8719            if advance_downwards {
 8720                let snapshot = this.buffer.read(cx).snapshot(cx);
 8721
 8722                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8723                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8724                        let mut point = display_point.to_point(display_snapshot);
 8725                        point.row += 1;
 8726                        point = snapshot.clip_point(point, Bias::Left);
 8727                        let display_point = point.to_display_point(display_snapshot);
 8728                        let goal = SelectionGoal::HorizontalPosition(
 8729                            display_snapshot
 8730                                .x_for_display_point(display_point, text_layout_details)
 8731                                .into(),
 8732                        );
 8733                        (display_point, goal)
 8734                    })
 8735                });
 8736            }
 8737        });
 8738    }
 8739
 8740    pub fn select_enclosing_symbol(
 8741        &mut self,
 8742        _: &SelectEnclosingSymbol,
 8743        cx: &mut ViewContext<Self>,
 8744    ) {
 8745        let buffer = self.buffer.read(cx).snapshot(cx);
 8746        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8747
 8748        fn update_selection(
 8749            selection: &Selection<usize>,
 8750            buffer_snap: &MultiBufferSnapshot,
 8751        ) -> Option<Selection<usize>> {
 8752            let cursor = selection.head();
 8753            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8754            for symbol in symbols.iter().rev() {
 8755                let start = symbol.range.start.to_offset(buffer_snap);
 8756                let end = symbol.range.end.to_offset(buffer_snap);
 8757                let new_range = start..end;
 8758                if start < selection.start || end > selection.end {
 8759                    return Some(Selection {
 8760                        id: selection.id,
 8761                        start: new_range.start,
 8762                        end: new_range.end,
 8763                        goal: SelectionGoal::None,
 8764                        reversed: selection.reversed,
 8765                    });
 8766                }
 8767            }
 8768            None
 8769        }
 8770
 8771        let mut selected_larger_symbol = false;
 8772        let new_selections = old_selections
 8773            .iter()
 8774            .map(|selection| match update_selection(selection, &buffer) {
 8775                Some(new_selection) => {
 8776                    if new_selection.range() != selection.range() {
 8777                        selected_larger_symbol = true;
 8778                    }
 8779                    new_selection
 8780                }
 8781                None => selection.clone(),
 8782            })
 8783            .collect::<Vec<_>>();
 8784
 8785        if selected_larger_symbol {
 8786            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8787                s.select(new_selections);
 8788            });
 8789        }
 8790    }
 8791
 8792    pub fn select_larger_syntax_node(
 8793        &mut self,
 8794        _: &SelectLargerSyntaxNode,
 8795        cx: &mut ViewContext<Self>,
 8796    ) {
 8797        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8798        let buffer = self.buffer.read(cx).snapshot(cx);
 8799        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8800
 8801        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8802        let mut selected_larger_node = false;
 8803        let new_selections = old_selections
 8804            .iter()
 8805            .map(|selection| {
 8806                let old_range = selection.start..selection.end;
 8807                let mut new_range = old_range.clone();
 8808                let mut new_node = None;
 8809                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8810                {
 8811                    new_node = Some(node);
 8812                    new_range = containing_range;
 8813                    if !display_map.intersects_fold(new_range.start)
 8814                        && !display_map.intersects_fold(new_range.end)
 8815                    {
 8816                        break;
 8817                    }
 8818                }
 8819
 8820                if let Some(node) = new_node {
 8821                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8822                    // nodes. Parent and grandparent are also logged because this operation will not
 8823                    // visit nodes that have the same range as their parent.
 8824                    log::info!("Node: {node:?}");
 8825                    let parent = node.parent();
 8826                    log::info!("Parent: {parent:?}");
 8827                    let grandparent = parent.and_then(|x| x.parent());
 8828                    log::info!("Grandparent: {grandparent:?}");
 8829                }
 8830
 8831                selected_larger_node |= new_range != old_range;
 8832                Selection {
 8833                    id: selection.id,
 8834                    start: new_range.start,
 8835                    end: new_range.end,
 8836                    goal: SelectionGoal::None,
 8837                    reversed: selection.reversed,
 8838                }
 8839            })
 8840            .collect::<Vec<_>>();
 8841
 8842        if selected_larger_node {
 8843            stack.push(old_selections);
 8844            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8845                s.select(new_selections);
 8846            });
 8847        }
 8848        self.select_larger_syntax_node_stack = stack;
 8849    }
 8850
 8851    pub fn select_smaller_syntax_node(
 8852        &mut self,
 8853        _: &SelectSmallerSyntaxNode,
 8854        cx: &mut ViewContext<Self>,
 8855    ) {
 8856        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8857        if let Some(selections) = stack.pop() {
 8858            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8859                s.select(selections.to_vec());
 8860            });
 8861        }
 8862        self.select_larger_syntax_node_stack = stack;
 8863    }
 8864
 8865    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8866        if !EditorSettings::get_global(cx).gutter.runnables {
 8867            self.clear_tasks();
 8868            return Task::ready(());
 8869        }
 8870        let project = self.project.as_ref().map(Model::downgrade);
 8871        cx.spawn(|this, mut cx| async move {
 8872            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8873            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8874                return;
 8875            };
 8876            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8877                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8878            }) else {
 8879                return;
 8880            };
 8881
 8882            let hide_runnables = project
 8883                .update(&mut cx, |project, cx| {
 8884                    // Do not display any test indicators in non-dev server remote projects.
 8885                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8886                })
 8887                .unwrap_or(true);
 8888            if hide_runnables {
 8889                return;
 8890            }
 8891            let new_rows =
 8892                cx.background_executor()
 8893                    .spawn({
 8894                        let snapshot = display_snapshot.clone();
 8895                        async move {
 8896                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8897                        }
 8898                    })
 8899                    .await;
 8900            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8901
 8902            this.update(&mut cx, |this, _| {
 8903                this.clear_tasks();
 8904                for (key, value) in rows {
 8905                    this.insert_tasks(key, value);
 8906                }
 8907            })
 8908            .ok();
 8909        })
 8910    }
 8911    fn fetch_runnable_ranges(
 8912        snapshot: &DisplaySnapshot,
 8913        range: Range<Anchor>,
 8914    ) -> Vec<language::RunnableRange> {
 8915        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8916    }
 8917
 8918    fn runnable_rows(
 8919        project: Model<Project>,
 8920        snapshot: DisplaySnapshot,
 8921        runnable_ranges: Vec<RunnableRange>,
 8922        mut cx: AsyncWindowContext,
 8923    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8924        runnable_ranges
 8925            .into_iter()
 8926            .filter_map(|mut runnable| {
 8927                let tasks = cx
 8928                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8929                    .ok()?;
 8930                if tasks.is_empty() {
 8931                    return None;
 8932                }
 8933
 8934                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8935
 8936                let row = snapshot
 8937                    .buffer_snapshot
 8938                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8939                    .1
 8940                    .start
 8941                    .row;
 8942
 8943                let context_range =
 8944                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8945                Some((
 8946                    (runnable.buffer_id, row),
 8947                    RunnableTasks {
 8948                        templates: tasks,
 8949                        offset: MultiBufferOffset(runnable.run_range.start),
 8950                        context_range,
 8951                        column: point.column,
 8952                        extra_variables: runnable.extra_captures,
 8953                    },
 8954                ))
 8955            })
 8956            .collect()
 8957    }
 8958
 8959    fn templates_with_tags(
 8960        project: &Model<Project>,
 8961        runnable: &mut Runnable,
 8962        cx: &WindowContext,
 8963    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8964        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8965            let (worktree_id, file) = project
 8966                .buffer_for_id(runnable.buffer, cx)
 8967                .and_then(|buffer| buffer.read(cx).file())
 8968                .map(|file| (file.worktree_id(cx), file.clone()))
 8969                .unzip();
 8970
 8971            (
 8972                project.task_store().read(cx).task_inventory().cloned(),
 8973                worktree_id,
 8974                file,
 8975            )
 8976        });
 8977
 8978        let tags = mem::take(&mut runnable.tags);
 8979        let mut tags: Vec<_> = tags
 8980            .into_iter()
 8981            .flat_map(|tag| {
 8982                let tag = tag.0.clone();
 8983                inventory
 8984                    .as_ref()
 8985                    .into_iter()
 8986                    .flat_map(|inventory| {
 8987                        inventory.read(cx).list_tasks(
 8988                            file.clone(),
 8989                            Some(runnable.language.clone()),
 8990                            worktree_id,
 8991                            cx,
 8992                        )
 8993                    })
 8994                    .filter(move |(_, template)| {
 8995                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8996                    })
 8997            })
 8998            .sorted_by_key(|(kind, _)| kind.to_owned())
 8999            .collect();
 9000        if let Some((leading_tag_source, _)) = tags.first() {
 9001            // Strongest source wins; if we have worktree tag binding, prefer that to
 9002            // global and language bindings;
 9003            // if we have a global binding, prefer that to language binding.
 9004            let first_mismatch = tags
 9005                .iter()
 9006                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9007            if let Some(index) = first_mismatch {
 9008                tags.truncate(index);
 9009            }
 9010        }
 9011
 9012        tags
 9013    }
 9014
 9015    pub fn move_to_enclosing_bracket(
 9016        &mut self,
 9017        _: &MoveToEnclosingBracket,
 9018        cx: &mut ViewContext<Self>,
 9019    ) {
 9020        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9021            s.move_offsets_with(|snapshot, selection| {
 9022                let Some(enclosing_bracket_ranges) =
 9023                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9024                else {
 9025                    return;
 9026                };
 9027
 9028                let mut best_length = usize::MAX;
 9029                let mut best_inside = false;
 9030                let mut best_in_bracket_range = false;
 9031                let mut best_destination = None;
 9032                for (open, close) in enclosing_bracket_ranges {
 9033                    let close = close.to_inclusive();
 9034                    let length = close.end() - open.start;
 9035                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9036                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9037                        || close.contains(&selection.head());
 9038
 9039                    // If best is next to a bracket and current isn't, skip
 9040                    if !in_bracket_range && best_in_bracket_range {
 9041                        continue;
 9042                    }
 9043
 9044                    // Prefer smaller lengths unless best is inside and current isn't
 9045                    if length > best_length && (best_inside || !inside) {
 9046                        continue;
 9047                    }
 9048
 9049                    best_length = length;
 9050                    best_inside = inside;
 9051                    best_in_bracket_range = in_bracket_range;
 9052                    best_destination = Some(
 9053                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9054                            if inside {
 9055                                open.end
 9056                            } else {
 9057                                open.start
 9058                            }
 9059                        } else if inside {
 9060                            *close.start()
 9061                        } else {
 9062                            *close.end()
 9063                        },
 9064                    );
 9065                }
 9066
 9067                if let Some(destination) = best_destination {
 9068                    selection.collapse_to(destination, SelectionGoal::None);
 9069                }
 9070            })
 9071        });
 9072    }
 9073
 9074    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9075        self.end_selection(cx);
 9076        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9077        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9078            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9079            self.select_next_state = entry.select_next_state;
 9080            self.select_prev_state = entry.select_prev_state;
 9081            self.add_selections_state = entry.add_selections_state;
 9082            self.request_autoscroll(Autoscroll::newest(), cx);
 9083        }
 9084        self.selection_history.mode = SelectionHistoryMode::Normal;
 9085    }
 9086
 9087    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9088        self.end_selection(cx);
 9089        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9090        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9091            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9092            self.select_next_state = entry.select_next_state;
 9093            self.select_prev_state = entry.select_prev_state;
 9094            self.add_selections_state = entry.add_selections_state;
 9095            self.request_autoscroll(Autoscroll::newest(), cx);
 9096        }
 9097        self.selection_history.mode = SelectionHistoryMode::Normal;
 9098    }
 9099
 9100    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9101        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9102    }
 9103
 9104    pub fn expand_excerpts_down(
 9105        &mut self,
 9106        action: &ExpandExcerptsDown,
 9107        cx: &mut ViewContext<Self>,
 9108    ) {
 9109        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9110    }
 9111
 9112    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9113        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9114    }
 9115
 9116    pub fn expand_excerpts_for_direction(
 9117        &mut self,
 9118        lines: u32,
 9119        direction: ExpandExcerptDirection,
 9120        cx: &mut ViewContext<Self>,
 9121    ) {
 9122        let selections = self.selections.disjoint_anchors();
 9123
 9124        let lines = if lines == 0 {
 9125            EditorSettings::get_global(cx).expand_excerpt_lines
 9126        } else {
 9127            lines
 9128        };
 9129
 9130        self.buffer.update(cx, |buffer, cx| {
 9131            let snapshot = buffer.snapshot(cx);
 9132            let mut excerpt_ids = selections
 9133                .iter()
 9134                .flat_map(|selection| {
 9135                    snapshot
 9136                        .excerpts_for_range(selection.range())
 9137                        .map(|excerpt| excerpt.id())
 9138                })
 9139                .collect::<Vec<_>>();
 9140            excerpt_ids.sort();
 9141            excerpt_ids.dedup();
 9142            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9143        })
 9144    }
 9145
 9146    pub fn expand_excerpt(
 9147        &mut self,
 9148        excerpt: ExcerptId,
 9149        direction: ExpandExcerptDirection,
 9150        cx: &mut ViewContext<Self>,
 9151    ) {
 9152        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9153        self.buffer.update(cx, |buffer, cx| {
 9154            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9155        })
 9156    }
 9157
 9158    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9159        self.go_to_diagnostic_impl(Direction::Next, cx)
 9160    }
 9161
 9162    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9163        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9164    }
 9165
 9166    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9167        let buffer = self.buffer.read(cx).snapshot(cx);
 9168        let selection = self.selections.newest::<usize>(cx);
 9169
 9170        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9171        if direction == Direction::Next {
 9172            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9173                self.activate_diagnostics(popover.group_id(), cx);
 9174                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9175                    let primary_range_start = active_diagnostics.primary_range.start;
 9176                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9177                        let mut new_selection = s.newest_anchor().clone();
 9178                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9179                        s.select_anchors(vec![new_selection.clone()]);
 9180                    });
 9181                }
 9182                return;
 9183            }
 9184        }
 9185
 9186        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9187            active_diagnostics
 9188                .primary_range
 9189                .to_offset(&buffer)
 9190                .to_inclusive()
 9191        });
 9192        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9193            if active_primary_range.contains(&selection.head()) {
 9194                *active_primary_range.start()
 9195            } else {
 9196                selection.head()
 9197            }
 9198        } else {
 9199            selection.head()
 9200        };
 9201        let snapshot = self.snapshot(cx);
 9202        loop {
 9203            let diagnostics = if direction == Direction::Prev {
 9204                buffer
 9205                    .diagnostics_in_range(0..search_start, true)
 9206                    .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
 9207                        diagnostic,
 9208                        range: range.to_offset(&buffer),
 9209                    })
 9210                    .collect::<Vec<_>>()
 9211            } else {
 9212                buffer
 9213                    .diagnostics_in_range(search_start..buffer.len(), false)
 9214                    .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
 9215                        diagnostic,
 9216                        range: range.to_offset(&buffer),
 9217                    })
 9218                    .collect::<Vec<_>>()
 9219            }
 9220            .into_iter()
 9221            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9222            let group = diagnostics
 9223                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9224                // be sorted in a stable way
 9225                // skip until we are at current active diagnostic, if it exists
 9226                .skip_while(|entry| {
 9227                    (match direction {
 9228                        Direction::Prev => entry.range.start >= search_start,
 9229                        Direction::Next => entry.range.start <= search_start,
 9230                    }) && self
 9231                        .active_diagnostics
 9232                        .as_ref()
 9233                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9234                })
 9235                .find_map(|entry| {
 9236                    if entry.diagnostic.is_primary
 9237                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9238                        && !entry.range.is_empty()
 9239                        // if we match with the active diagnostic, skip it
 9240                        && Some(entry.diagnostic.group_id)
 9241                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9242                    {
 9243                        Some((entry.range, entry.diagnostic.group_id))
 9244                    } else {
 9245                        None
 9246                    }
 9247                });
 9248
 9249            if let Some((primary_range, group_id)) = group {
 9250                self.activate_diagnostics(group_id, cx);
 9251                if self.active_diagnostics.is_some() {
 9252                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9253                        s.select(vec![Selection {
 9254                            id: selection.id,
 9255                            start: primary_range.start,
 9256                            end: primary_range.start,
 9257                            reversed: false,
 9258                            goal: SelectionGoal::None,
 9259                        }]);
 9260                    });
 9261                }
 9262                break;
 9263            } else {
 9264                // Cycle around to the start of the buffer, potentially moving back to the start of
 9265                // the currently active diagnostic.
 9266                active_primary_range.take();
 9267                if direction == Direction::Prev {
 9268                    if search_start == buffer.len() {
 9269                        break;
 9270                    } else {
 9271                        search_start = buffer.len();
 9272                    }
 9273                } else if search_start == 0 {
 9274                    break;
 9275                } else {
 9276                    search_start = 0;
 9277                }
 9278            }
 9279        }
 9280    }
 9281
 9282    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9283        let snapshot = self.snapshot(cx);
 9284        let selection = self.selections.newest::<Point>(cx);
 9285        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9286    }
 9287
 9288    fn go_to_hunk_after_position(
 9289        &mut self,
 9290        snapshot: &EditorSnapshot,
 9291        position: Point,
 9292        cx: &mut ViewContext<Editor>,
 9293    ) -> Option<MultiBufferDiffHunk> {
 9294        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9295            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9296                snapshot,
 9297                position,
 9298                ix > 0,
 9299                snapshot.diff_map.diff_hunks_in_range(
 9300                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9301                    &snapshot.buffer_snapshot,
 9302                ),
 9303                cx,
 9304            ) {
 9305                return Some(hunk);
 9306            }
 9307        }
 9308        None
 9309    }
 9310
 9311    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9312        let snapshot = self.snapshot(cx);
 9313        let selection = self.selections.newest::<Point>(cx);
 9314        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9315    }
 9316
 9317    fn go_to_hunk_before_position(
 9318        &mut self,
 9319        snapshot: &EditorSnapshot,
 9320        position: Point,
 9321        cx: &mut ViewContext<Editor>,
 9322    ) -> Option<MultiBufferDiffHunk> {
 9323        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9324            .into_iter()
 9325            .enumerate()
 9326        {
 9327            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9328                snapshot,
 9329                position,
 9330                ix > 0,
 9331                snapshot
 9332                    .diff_map
 9333                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9334                cx,
 9335            ) {
 9336                return Some(hunk);
 9337            }
 9338        }
 9339        None
 9340    }
 9341
 9342    fn go_to_next_hunk_in_direction(
 9343        &mut self,
 9344        snapshot: &DisplaySnapshot,
 9345        initial_point: Point,
 9346        is_wrapped: bool,
 9347        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9348        cx: &mut ViewContext<Editor>,
 9349    ) -> Option<MultiBufferDiffHunk> {
 9350        let display_point = initial_point.to_display_point(snapshot);
 9351        let mut hunks = hunks
 9352            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9353            .filter(|(display_hunk, _)| {
 9354                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9355            })
 9356            .dedup();
 9357
 9358        if let Some((display_hunk, hunk)) = hunks.next() {
 9359            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9360                let row = display_hunk.start_display_row();
 9361                let point = DisplayPoint::new(row, 0);
 9362                s.select_display_ranges([point..point]);
 9363            });
 9364
 9365            Some(hunk)
 9366        } else {
 9367            None
 9368        }
 9369    }
 9370
 9371    pub fn go_to_definition(
 9372        &mut self,
 9373        _: &GoToDefinition,
 9374        cx: &mut ViewContext<Self>,
 9375    ) -> Task<Result<Navigated>> {
 9376        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9377        cx.spawn(|editor, mut cx| async move {
 9378            if definition.await? == Navigated::Yes {
 9379                return Ok(Navigated::Yes);
 9380            }
 9381            match editor.update(&mut cx, |editor, cx| {
 9382                editor.find_all_references(&FindAllReferences, cx)
 9383            })? {
 9384                Some(references) => references.await,
 9385                None => Ok(Navigated::No),
 9386            }
 9387        })
 9388    }
 9389
 9390    pub fn go_to_declaration(
 9391        &mut self,
 9392        _: &GoToDeclaration,
 9393        cx: &mut ViewContext<Self>,
 9394    ) -> Task<Result<Navigated>> {
 9395        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9396    }
 9397
 9398    pub fn go_to_declaration_split(
 9399        &mut self,
 9400        _: &GoToDeclaration,
 9401        cx: &mut ViewContext<Self>,
 9402    ) -> Task<Result<Navigated>> {
 9403        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9404    }
 9405
 9406    pub fn go_to_implementation(
 9407        &mut self,
 9408        _: &GoToImplementation,
 9409        cx: &mut ViewContext<Self>,
 9410    ) -> Task<Result<Navigated>> {
 9411        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9412    }
 9413
 9414    pub fn go_to_implementation_split(
 9415        &mut self,
 9416        _: &GoToImplementationSplit,
 9417        cx: &mut ViewContext<Self>,
 9418    ) -> Task<Result<Navigated>> {
 9419        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9420    }
 9421
 9422    pub fn go_to_type_definition(
 9423        &mut self,
 9424        _: &GoToTypeDefinition,
 9425        cx: &mut ViewContext<Self>,
 9426    ) -> Task<Result<Navigated>> {
 9427        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9428    }
 9429
 9430    pub fn go_to_definition_split(
 9431        &mut self,
 9432        _: &GoToDefinitionSplit,
 9433        cx: &mut ViewContext<Self>,
 9434    ) -> Task<Result<Navigated>> {
 9435        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9436    }
 9437
 9438    pub fn go_to_type_definition_split(
 9439        &mut self,
 9440        _: &GoToTypeDefinitionSplit,
 9441        cx: &mut ViewContext<Self>,
 9442    ) -> Task<Result<Navigated>> {
 9443        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9444    }
 9445
 9446    fn go_to_definition_of_kind(
 9447        &mut self,
 9448        kind: GotoDefinitionKind,
 9449        split: bool,
 9450        cx: &mut ViewContext<Self>,
 9451    ) -> Task<Result<Navigated>> {
 9452        let Some(provider) = self.semantics_provider.clone() else {
 9453            return Task::ready(Ok(Navigated::No));
 9454        };
 9455        let head = self.selections.newest::<usize>(cx).head();
 9456        let buffer = self.buffer.read(cx);
 9457        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9458            text_anchor
 9459        } else {
 9460            return Task::ready(Ok(Navigated::No));
 9461        };
 9462
 9463        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9464            return Task::ready(Ok(Navigated::No));
 9465        };
 9466
 9467        cx.spawn(|editor, mut cx| async move {
 9468            let definitions = definitions.await?;
 9469            let navigated = editor
 9470                .update(&mut cx, |editor, cx| {
 9471                    editor.navigate_to_hover_links(
 9472                        Some(kind),
 9473                        definitions
 9474                            .into_iter()
 9475                            .filter(|location| {
 9476                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9477                            })
 9478                            .map(HoverLink::Text)
 9479                            .collect::<Vec<_>>(),
 9480                        split,
 9481                        cx,
 9482                    )
 9483                })?
 9484                .await?;
 9485            anyhow::Ok(navigated)
 9486        })
 9487    }
 9488
 9489    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9490        let selection = self.selections.newest_anchor();
 9491        let head = selection.head();
 9492        let tail = selection.tail();
 9493
 9494        let Some((buffer, start_position)) =
 9495            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9496        else {
 9497            return;
 9498        };
 9499
 9500        let end_position = if head != tail {
 9501            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9502                return;
 9503            };
 9504            Some(pos)
 9505        } else {
 9506            None
 9507        };
 9508
 9509        let url_finder = cx.spawn(|editor, mut cx| async move {
 9510            let url = if let Some(end_pos) = end_position {
 9511                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9512            } else {
 9513                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9514            };
 9515
 9516            if let Some(url) = url {
 9517                editor.update(&mut cx, |_, cx| {
 9518                    cx.open_url(&url);
 9519                })
 9520            } else {
 9521                Ok(())
 9522            }
 9523        });
 9524
 9525        url_finder.detach();
 9526    }
 9527
 9528    pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
 9529        let Some(workspace) = self.workspace() else {
 9530            return;
 9531        };
 9532
 9533        let position = self.selections.newest_anchor().head();
 9534
 9535        let Some((buffer, buffer_position)) =
 9536            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9537        else {
 9538            return;
 9539        };
 9540
 9541        let project = self.project.clone();
 9542
 9543        cx.spawn(|_, mut cx| async move {
 9544            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9545
 9546            if let Some((_, path)) = result {
 9547                workspace
 9548                    .update(&mut cx, |workspace, cx| {
 9549                        workspace.open_resolved_path(path, cx)
 9550                    })?
 9551                    .await?;
 9552            }
 9553            anyhow::Ok(())
 9554        })
 9555        .detach();
 9556    }
 9557
 9558    pub(crate) fn navigate_to_hover_links(
 9559        &mut self,
 9560        kind: Option<GotoDefinitionKind>,
 9561        mut definitions: Vec<HoverLink>,
 9562        split: bool,
 9563        cx: &mut ViewContext<Editor>,
 9564    ) -> Task<Result<Navigated>> {
 9565        // If there is one definition, just open it directly
 9566        if definitions.len() == 1 {
 9567            let definition = definitions.pop().unwrap();
 9568
 9569            enum TargetTaskResult {
 9570                Location(Option<Location>),
 9571                AlreadyNavigated,
 9572            }
 9573
 9574            let target_task = match definition {
 9575                HoverLink::Text(link) => {
 9576                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9577                }
 9578                HoverLink::InlayHint(lsp_location, server_id) => {
 9579                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9580                    cx.background_executor().spawn(async move {
 9581                        let location = computation.await?;
 9582                        Ok(TargetTaskResult::Location(location))
 9583                    })
 9584                }
 9585                HoverLink::Url(url) => {
 9586                    cx.open_url(&url);
 9587                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9588                }
 9589                HoverLink::File(path) => {
 9590                    if let Some(workspace) = self.workspace() {
 9591                        cx.spawn(|_, mut cx| async move {
 9592                            workspace
 9593                                .update(&mut cx, |workspace, cx| {
 9594                                    workspace.open_resolved_path(path, cx)
 9595                                })?
 9596                                .await
 9597                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9598                        })
 9599                    } else {
 9600                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9601                    }
 9602                }
 9603            };
 9604            cx.spawn(|editor, mut cx| async move {
 9605                let target = match target_task.await.context("target resolution task")? {
 9606                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9607                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9608                    TargetTaskResult::Location(Some(target)) => target,
 9609                };
 9610
 9611                editor.update(&mut cx, |editor, cx| {
 9612                    let Some(workspace) = editor.workspace() else {
 9613                        return Navigated::No;
 9614                    };
 9615                    let pane = workspace.read(cx).active_pane().clone();
 9616
 9617                    let range = target.range.to_offset(target.buffer.read(cx));
 9618                    let range = editor.range_for_match(&range);
 9619
 9620                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9621                        let buffer = target.buffer.read(cx);
 9622                        let range = check_multiline_range(buffer, range);
 9623                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9624                            s.select_ranges([range]);
 9625                        });
 9626                    } else {
 9627                        cx.window_context().defer(move |cx| {
 9628                            let target_editor: View<Self> =
 9629                                workspace.update(cx, |workspace, cx| {
 9630                                    let pane = if split {
 9631                                        workspace.adjacent_pane(cx)
 9632                                    } else {
 9633                                        workspace.active_pane().clone()
 9634                                    };
 9635
 9636                                    workspace.open_project_item(
 9637                                        pane,
 9638                                        target.buffer.clone(),
 9639                                        true,
 9640                                        true,
 9641                                        cx,
 9642                                    )
 9643                                });
 9644                            target_editor.update(cx, |target_editor, cx| {
 9645                                // When selecting a definition in a different buffer, disable the nav history
 9646                                // to avoid creating a history entry at the previous cursor location.
 9647                                pane.update(cx, |pane, _| pane.disable_history());
 9648                                let buffer = target.buffer.read(cx);
 9649                                let range = check_multiline_range(buffer, range);
 9650                                target_editor.change_selections(
 9651                                    Some(Autoscroll::focused()),
 9652                                    cx,
 9653                                    |s| {
 9654                                        s.select_ranges([range]);
 9655                                    },
 9656                                );
 9657                                pane.update(cx, |pane, _| pane.enable_history());
 9658                            });
 9659                        });
 9660                    }
 9661                    Navigated::Yes
 9662                })
 9663            })
 9664        } else if !definitions.is_empty() {
 9665            cx.spawn(|editor, mut cx| async move {
 9666                let (title, location_tasks, workspace) = editor
 9667                    .update(&mut cx, |editor, cx| {
 9668                        let tab_kind = match kind {
 9669                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9670                            _ => "Definitions",
 9671                        };
 9672                        let title = definitions
 9673                            .iter()
 9674                            .find_map(|definition| match definition {
 9675                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9676                                    let buffer = origin.buffer.read(cx);
 9677                                    format!(
 9678                                        "{} for {}",
 9679                                        tab_kind,
 9680                                        buffer
 9681                                            .text_for_range(origin.range.clone())
 9682                                            .collect::<String>()
 9683                                    )
 9684                                }),
 9685                                HoverLink::InlayHint(_, _) => None,
 9686                                HoverLink::Url(_) => None,
 9687                                HoverLink::File(_) => None,
 9688                            })
 9689                            .unwrap_or(tab_kind.to_string());
 9690                        let location_tasks = definitions
 9691                            .into_iter()
 9692                            .map(|definition| match definition {
 9693                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9694                                HoverLink::InlayHint(lsp_location, server_id) => {
 9695                                    editor.compute_target_location(lsp_location, server_id, cx)
 9696                                }
 9697                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9698                                HoverLink::File(_) => Task::ready(Ok(None)),
 9699                            })
 9700                            .collect::<Vec<_>>();
 9701                        (title, location_tasks, editor.workspace().clone())
 9702                    })
 9703                    .context("location tasks preparation")?;
 9704
 9705                let locations = future::join_all(location_tasks)
 9706                    .await
 9707                    .into_iter()
 9708                    .filter_map(|location| location.transpose())
 9709                    .collect::<Result<_>>()
 9710                    .context("location tasks")?;
 9711
 9712                let Some(workspace) = workspace else {
 9713                    return Ok(Navigated::No);
 9714                };
 9715                let opened = workspace
 9716                    .update(&mut cx, |workspace, cx| {
 9717                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9718                    })
 9719                    .ok();
 9720
 9721                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9722            })
 9723        } else {
 9724            Task::ready(Ok(Navigated::No))
 9725        }
 9726    }
 9727
 9728    fn compute_target_location(
 9729        &self,
 9730        lsp_location: lsp::Location,
 9731        server_id: LanguageServerId,
 9732        cx: &mut ViewContext<Self>,
 9733    ) -> Task<anyhow::Result<Option<Location>>> {
 9734        let Some(project) = self.project.clone() else {
 9735            return Task::ready(Ok(None));
 9736        };
 9737
 9738        cx.spawn(move |editor, mut cx| async move {
 9739            let location_task = editor.update(&mut cx, |_, cx| {
 9740                project.update(cx, |project, cx| {
 9741                    let language_server_name = project
 9742                        .language_server_statuses(cx)
 9743                        .find(|(id, _)| server_id == *id)
 9744                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9745                    language_server_name.map(|language_server_name| {
 9746                        project.open_local_buffer_via_lsp(
 9747                            lsp_location.uri.clone(),
 9748                            server_id,
 9749                            language_server_name,
 9750                            cx,
 9751                        )
 9752                    })
 9753                })
 9754            })?;
 9755            let location = match location_task {
 9756                Some(task) => Some({
 9757                    let target_buffer_handle = task.await.context("open local buffer")?;
 9758                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9759                        let target_start = target_buffer
 9760                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9761                        let target_end = target_buffer
 9762                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9763                        target_buffer.anchor_after(target_start)
 9764                            ..target_buffer.anchor_before(target_end)
 9765                    })?;
 9766                    Location {
 9767                        buffer: target_buffer_handle,
 9768                        range,
 9769                    }
 9770                }),
 9771                None => None,
 9772            };
 9773            Ok(location)
 9774        })
 9775    }
 9776
 9777    pub fn find_all_references(
 9778        &mut self,
 9779        _: &FindAllReferences,
 9780        cx: &mut ViewContext<Self>,
 9781    ) -> Option<Task<Result<Navigated>>> {
 9782        let selection = self.selections.newest::<usize>(cx);
 9783        let multi_buffer = self.buffer.read(cx);
 9784        let head = selection.head();
 9785
 9786        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9787        let head_anchor = multi_buffer_snapshot.anchor_at(
 9788            head,
 9789            if head < selection.tail() {
 9790                Bias::Right
 9791            } else {
 9792                Bias::Left
 9793            },
 9794        );
 9795
 9796        match self
 9797            .find_all_references_task_sources
 9798            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9799        {
 9800            Ok(_) => {
 9801                log::info!(
 9802                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9803                );
 9804                return None;
 9805            }
 9806            Err(i) => {
 9807                self.find_all_references_task_sources.insert(i, head_anchor);
 9808            }
 9809        }
 9810
 9811        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9812        let workspace = self.workspace()?;
 9813        let project = workspace.read(cx).project().clone();
 9814        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9815        Some(cx.spawn(|editor, mut cx| async move {
 9816            let _cleanup = defer({
 9817                let mut cx = cx.clone();
 9818                move || {
 9819                    let _ = editor.update(&mut cx, |editor, _| {
 9820                        if let Ok(i) =
 9821                            editor
 9822                                .find_all_references_task_sources
 9823                                .binary_search_by(|anchor| {
 9824                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9825                                })
 9826                        {
 9827                            editor.find_all_references_task_sources.remove(i);
 9828                        }
 9829                    });
 9830                }
 9831            });
 9832
 9833            let locations = references.await?;
 9834            if locations.is_empty() {
 9835                return anyhow::Ok(Navigated::No);
 9836            }
 9837
 9838            workspace.update(&mut cx, |workspace, cx| {
 9839                let title = locations
 9840                    .first()
 9841                    .as_ref()
 9842                    .map(|location| {
 9843                        let buffer = location.buffer.read(cx);
 9844                        format!(
 9845                            "References to `{}`",
 9846                            buffer
 9847                                .text_for_range(location.range.clone())
 9848                                .collect::<String>()
 9849                        )
 9850                    })
 9851                    .unwrap();
 9852                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9853                Navigated::Yes
 9854            })
 9855        }))
 9856    }
 9857
 9858    /// Opens a multibuffer with the given project locations in it
 9859    pub fn open_locations_in_multibuffer(
 9860        workspace: &mut Workspace,
 9861        mut locations: Vec<Location>,
 9862        title: String,
 9863        split: bool,
 9864        cx: &mut ViewContext<Workspace>,
 9865    ) {
 9866        // If there are multiple definitions, open them in a multibuffer
 9867        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9868        let mut locations = locations.into_iter().peekable();
 9869        let mut ranges_to_highlight = Vec::new();
 9870        let capability = workspace.project().read(cx).capability();
 9871
 9872        let excerpt_buffer = cx.new_model(|cx| {
 9873            let mut multibuffer = MultiBuffer::new(capability);
 9874            while let Some(location) = locations.next() {
 9875                let buffer = location.buffer.read(cx);
 9876                let mut ranges_for_buffer = Vec::new();
 9877                let range = location.range.to_offset(buffer);
 9878                ranges_for_buffer.push(range.clone());
 9879
 9880                while let Some(next_location) = locations.peek() {
 9881                    if next_location.buffer == location.buffer {
 9882                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9883                        locations.next();
 9884                    } else {
 9885                        break;
 9886                    }
 9887                }
 9888
 9889                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9890                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9891                    location.buffer.clone(),
 9892                    ranges_for_buffer,
 9893                    DEFAULT_MULTIBUFFER_CONTEXT,
 9894                    cx,
 9895                ))
 9896            }
 9897
 9898            multibuffer.with_title(title)
 9899        });
 9900
 9901        let editor = cx.new_view(|cx| {
 9902            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9903        });
 9904        editor.update(cx, |editor, cx| {
 9905            if let Some(first_range) = ranges_to_highlight.first() {
 9906                editor.change_selections(None, cx, |selections| {
 9907                    selections.clear_disjoint();
 9908                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9909                });
 9910            }
 9911            editor.highlight_background::<Self>(
 9912                &ranges_to_highlight,
 9913                |theme| theme.editor_highlighted_line_background,
 9914                cx,
 9915            );
 9916            editor.register_buffers_with_language_servers(cx);
 9917        });
 9918
 9919        let item = Box::new(editor);
 9920        let item_id = item.item_id();
 9921
 9922        if split {
 9923            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9924        } else {
 9925            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9926                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9927                    pane.close_current_preview_item(cx)
 9928                } else {
 9929                    None
 9930                }
 9931            });
 9932            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9933        }
 9934        workspace.active_pane().update(cx, |pane, cx| {
 9935            pane.set_preview_item_id(Some(item_id), cx);
 9936        });
 9937    }
 9938
 9939    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9940        use language::ToOffset as _;
 9941
 9942        let provider = self.semantics_provider.clone()?;
 9943        let selection = self.selections.newest_anchor().clone();
 9944        let (cursor_buffer, cursor_buffer_position) = self
 9945            .buffer
 9946            .read(cx)
 9947            .text_anchor_for_position(selection.head(), cx)?;
 9948        let (tail_buffer, cursor_buffer_position_end) = self
 9949            .buffer
 9950            .read(cx)
 9951            .text_anchor_for_position(selection.tail(), cx)?;
 9952        if tail_buffer != cursor_buffer {
 9953            return None;
 9954        }
 9955
 9956        let snapshot = cursor_buffer.read(cx).snapshot();
 9957        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9958        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9959        let prepare_rename = provider
 9960            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9961            .unwrap_or_else(|| Task::ready(Ok(None)));
 9962        drop(snapshot);
 9963
 9964        Some(cx.spawn(|this, mut cx| async move {
 9965            let rename_range = if let Some(range) = prepare_rename.await? {
 9966                Some(range)
 9967            } else {
 9968                this.update(&mut cx, |this, cx| {
 9969                    let buffer = this.buffer.read(cx).snapshot(cx);
 9970                    let mut buffer_highlights = this
 9971                        .document_highlights_for_position(selection.head(), &buffer)
 9972                        .filter(|highlight| {
 9973                            highlight.start.excerpt_id == selection.head().excerpt_id
 9974                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9975                        });
 9976                    buffer_highlights
 9977                        .next()
 9978                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9979                })?
 9980            };
 9981            if let Some(rename_range) = rename_range {
 9982                this.update(&mut cx, |this, cx| {
 9983                    let snapshot = cursor_buffer.read(cx).snapshot();
 9984                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9985                    let cursor_offset_in_rename_range =
 9986                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9987                    let cursor_offset_in_rename_range_end =
 9988                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9989
 9990                    this.take_rename(false, cx);
 9991                    let buffer = this.buffer.read(cx).read(cx);
 9992                    let cursor_offset = selection.head().to_offset(&buffer);
 9993                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9994                    let rename_end = rename_start + rename_buffer_range.len();
 9995                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9996                    let mut old_highlight_id = None;
 9997                    let old_name: Arc<str> = buffer
 9998                        .chunks(rename_start..rename_end, true)
 9999                        .map(|chunk| {
10000                            if old_highlight_id.is_none() {
10001                                old_highlight_id = chunk.syntax_highlight_id;
10002                            }
10003                            chunk.text
10004                        })
10005                        .collect::<String>()
10006                        .into();
10007
10008                    drop(buffer);
10009
10010                    // Position the selection in the rename editor so that it matches the current selection.
10011                    this.show_local_selections = false;
10012                    let rename_editor = cx.new_view(|cx| {
10013                        let mut editor = Editor::single_line(cx);
10014                        editor.buffer.update(cx, |buffer, cx| {
10015                            buffer.edit([(0..0, old_name.clone())], None, cx)
10016                        });
10017                        let rename_selection_range = match cursor_offset_in_rename_range
10018                            .cmp(&cursor_offset_in_rename_range_end)
10019                        {
10020                            Ordering::Equal => {
10021                                editor.select_all(&SelectAll, cx);
10022                                return editor;
10023                            }
10024                            Ordering::Less => {
10025                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10026                            }
10027                            Ordering::Greater => {
10028                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10029                            }
10030                        };
10031                        if rename_selection_range.end > old_name.len() {
10032                            editor.select_all(&SelectAll, cx);
10033                        } else {
10034                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10035                                s.select_ranges([rename_selection_range]);
10036                            });
10037                        }
10038                        editor
10039                    });
10040                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10041                        if e == &EditorEvent::Focused {
10042                            cx.emit(EditorEvent::FocusedIn)
10043                        }
10044                    })
10045                    .detach();
10046
10047                    let write_highlights =
10048                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10049                    let read_highlights =
10050                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10051                    let ranges = write_highlights
10052                        .iter()
10053                        .flat_map(|(_, ranges)| ranges.iter())
10054                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10055                        .cloned()
10056                        .collect();
10057
10058                    this.highlight_text::<Rename>(
10059                        ranges,
10060                        HighlightStyle {
10061                            fade_out: Some(0.6),
10062                            ..Default::default()
10063                        },
10064                        cx,
10065                    );
10066                    let rename_focus_handle = rename_editor.focus_handle(cx);
10067                    cx.focus(&rename_focus_handle);
10068                    let block_id = this.insert_blocks(
10069                        [BlockProperties {
10070                            style: BlockStyle::Flex,
10071                            placement: BlockPlacement::Below(range.start),
10072                            height: 1,
10073                            render: Arc::new({
10074                                let rename_editor = rename_editor.clone();
10075                                move |cx: &mut BlockContext| {
10076                                    let mut text_style = cx.editor_style.text.clone();
10077                                    if let Some(highlight_style) = old_highlight_id
10078                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10079                                    {
10080                                        text_style = text_style.highlight(highlight_style);
10081                                    }
10082                                    div()
10083                                        .block_mouse_down()
10084                                        .pl(cx.anchor_x)
10085                                        .child(EditorElement::new(
10086                                            &rename_editor,
10087                                            EditorStyle {
10088                                                background: cx.theme().system().transparent,
10089                                                local_player: cx.editor_style.local_player,
10090                                                text: text_style,
10091                                                scrollbar_width: cx.editor_style.scrollbar_width,
10092                                                syntax: cx.editor_style.syntax.clone(),
10093                                                status: cx.editor_style.status.clone(),
10094                                                inlay_hints_style: HighlightStyle {
10095                                                    font_weight: Some(FontWeight::BOLD),
10096                                                    ..make_inlay_hints_style(cx)
10097                                                },
10098                                                inline_completion_styles: make_suggestion_styles(
10099                                                    cx,
10100                                                ),
10101                                                ..EditorStyle::default()
10102                                            },
10103                                        ))
10104                                        .into_any_element()
10105                                }
10106                            }),
10107                            priority: 0,
10108                        }],
10109                        Some(Autoscroll::fit()),
10110                        cx,
10111                    )[0];
10112                    this.pending_rename = Some(RenameState {
10113                        range,
10114                        old_name,
10115                        editor: rename_editor,
10116                        block_id,
10117                    });
10118                })?;
10119            }
10120
10121            Ok(())
10122        }))
10123    }
10124
10125    pub fn confirm_rename(
10126        &mut self,
10127        _: &ConfirmRename,
10128        cx: &mut ViewContext<Self>,
10129    ) -> Option<Task<Result<()>>> {
10130        let rename = self.take_rename(false, cx)?;
10131        let workspace = self.workspace()?.downgrade();
10132        let (buffer, start) = self
10133            .buffer
10134            .read(cx)
10135            .text_anchor_for_position(rename.range.start, cx)?;
10136        let (end_buffer, _) = self
10137            .buffer
10138            .read(cx)
10139            .text_anchor_for_position(rename.range.end, cx)?;
10140        if buffer != end_buffer {
10141            return None;
10142        }
10143
10144        let old_name = rename.old_name;
10145        let new_name = rename.editor.read(cx).text(cx);
10146
10147        let rename = self.semantics_provider.as_ref()?.perform_rename(
10148            &buffer,
10149            start,
10150            new_name.clone(),
10151            cx,
10152        )?;
10153
10154        Some(cx.spawn(|editor, mut cx| async move {
10155            let project_transaction = rename.await?;
10156            Self::open_project_transaction(
10157                &editor,
10158                workspace,
10159                project_transaction,
10160                format!("Rename: {}{}", old_name, new_name),
10161                cx.clone(),
10162            )
10163            .await?;
10164
10165            editor.update(&mut cx, |editor, cx| {
10166                editor.refresh_document_highlights(cx);
10167            })?;
10168            Ok(())
10169        }))
10170    }
10171
10172    fn take_rename(
10173        &mut self,
10174        moving_cursor: bool,
10175        cx: &mut ViewContext<Self>,
10176    ) -> Option<RenameState> {
10177        let rename = self.pending_rename.take()?;
10178        if rename.editor.focus_handle(cx).is_focused(cx) {
10179            cx.focus(&self.focus_handle);
10180        }
10181
10182        self.remove_blocks(
10183            [rename.block_id].into_iter().collect(),
10184            Some(Autoscroll::fit()),
10185            cx,
10186        );
10187        self.clear_highlights::<Rename>(cx);
10188        self.show_local_selections = true;
10189
10190        if moving_cursor {
10191            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10192                editor.selections.newest::<usize>(cx).head()
10193            });
10194
10195            // Update the selection to match the position of the selection inside
10196            // the rename editor.
10197            let snapshot = self.buffer.read(cx).read(cx);
10198            let rename_range = rename.range.to_offset(&snapshot);
10199            let cursor_in_editor = snapshot
10200                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10201                .min(rename_range.end);
10202            drop(snapshot);
10203
10204            self.change_selections(None, cx, |s| {
10205                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10206            });
10207        } else {
10208            self.refresh_document_highlights(cx);
10209        }
10210
10211        Some(rename)
10212    }
10213
10214    pub fn pending_rename(&self) -> Option<&RenameState> {
10215        self.pending_rename.as_ref()
10216    }
10217
10218    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10219        let project = match &self.project {
10220            Some(project) => project.clone(),
10221            None => return None,
10222        };
10223
10224        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10225    }
10226
10227    fn format_selections(
10228        &mut self,
10229        _: &FormatSelections,
10230        cx: &mut ViewContext<Self>,
10231    ) -> Option<Task<Result<()>>> {
10232        let project = match &self.project {
10233            Some(project) => project.clone(),
10234            None => return None,
10235        };
10236
10237        let selections = self
10238            .selections
10239            .all_adjusted(cx)
10240            .into_iter()
10241            .filter(|s| !s.is_empty())
10242            .collect_vec();
10243
10244        Some(self.perform_format(
10245            project,
10246            FormatTrigger::Manual,
10247            FormatTarget::Ranges(selections),
10248            cx,
10249        ))
10250    }
10251
10252    fn perform_format(
10253        &mut self,
10254        project: Model<Project>,
10255        trigger: FormatTrigger,
10256        target: FormatTarget,
10257        cx: &mut ViewContext<Self>,
10258    ) -> Task<Result<()>> {
10259        let buffer = self.buffer().clone();
10260        let mut buffers = buffer.read(cx).all_buffers();
10261        if trigger == FormatTrigger::Save {
10262            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10263        }
10264
10265        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10266        let format = project.update(cx, |project, cx| {
10267            project.format(buffers, true, trigger, target, cx)
10268        });
10269
10270        cx.spawn(|_, mut cx| async move {
10271            let transaction = futures::select_biased! {
10272                () = timeout => {
10273                    log::warn!("timed out waiting for formatting");
10274                    None
10275                }
10276                transaction = format.log_err().fuse() => transaction,
10277            };
10278
10279            buffer
10280                .update(&mut cx, |buffer, cx| {
10281                    if let Some(transaction) = transaction {
10282                        if !buffer.is_singleton() {
10283                            buffer.push_transaction(&transaction.0, cx);
10284                        }
10285                    }
10286
10287                    cx.notify();
10288                })
10289                .ok();
10290
10291            Ok(())
10292        })
10293    }
10294
10295    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10296        if let Some(project) = self.project.clone() {
10297            self.buffer.update(cx, |multi_buffer, cx| {
10298                project.update(cx, |project, cx| {
10299                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10300                });
10301            })
10302        }
10303    }
10304
10305    fn cancel_language_server_work(
10306        &mut self,
10307        _: &actions::CancelLanguageServerWork,
10308        cx: &mut ViewContext<Self>,
10309    ) {
10310        if let Some(project) = self.project.clone() {
10311            self.buffer.update(cx, |multi_buffer, cx| {
10312                project.update(cx, |project, cx| {
10313                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10314                });
10315            })
10316        }
10317    }
10318
10319    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10320        cx.show_character_palette();
10321    }
10322
10323    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10324        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10325            let buffer = self.buffer.read(cx).snapshot(cx);
10326            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10327            let is_valid = buffer
10328                .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10329                .any(|entry| {
10330                    let range = entry.range.to_offset(&buffer);
10331                    entry.diagnostic.is_primary
10332                        && !range.is_empty()
10333                        && range.start == primary_range_start
10334                        && entry.diagnostic.message == active_diagnostics.primary_message
10335                });
10336
10337            if is_valid != active_diagnostics.is_valid {
10338                active_diagnostics.is_valid = is_valid;
10339                let mut new_styles = HashMap::default();
10340                for (block_id, diagnostic) in &active_diagnostics.blocks {
10341                    new_styles.insert(
10342                        *block_id,
10343                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10344                    );
10345                }
10346                self.display_map.update(cx, |display_map, _cx| {
10347                    display_map.replace_blocks(new_styles)
10348                });
10349            }
10350        }
10351    }
10352
10353    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10354        self.dismiss_diagnostics(cx);
10355        let snapshot = self.snapshot(cx);
10356        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10357            let buffer = self.buffer.read(cx).snapshot(cx);
10358
10359            let mut primary_range = None;
10360            let mut primary_message = None;
10361            let mut group_end = Point::zero();
10362            let diagnostic_group = buffer
10363                .diagnostic_group(group_id)
10364                .filter_map(|entry| {
10365                    let start = entry.range.start.to_point(&buffer);
10366                    let end = entry.range.end.to_point(&buffer);
10367                    if snapshot.is_line_folded(MultiBufferRow(start.row))
10368                        && (start.row == end.row
10369                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
10370                    {
10371                        return None;
10372                    }
10373                    if end > group_end {
10374                        group_end = end;
10375                    }
10376                    if entry.diagnostic.is_primary {
10377                        primary_range = Some(entry.range.clone());
10378                        primary_message = Some(entry.diagnostic.message.clone());
10379                    }
10380                    Some(entry)
10381                })
10382                .collect::<Vec<_>>();
10383            let primary_range = primary_range?;
10384            let primary_message = primary_message?;
10385
10386            let blocks = display_map
10387                .insert_blocks(
10388                    diagnostic_group.iter().map(|entry| {
10389                        let diagnostic = entry.diagnostic.clone();
10390                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10391                        BlockProperties {
10392                            style: BlockStyle::Fixed,
10393                            placement: BlockPlacement::Below(
10394                                buffer.anchor_after(entry.range.start),
10395                            ),
10396                            height: message_height,
10397                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10398                            priority: 0,
10399                        }
10400                    }),
10401                    cx,
10402                )
10403                .into_iter()
10404                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10405                .collect();
10406
10407            Some(ActiveDiagnosticGroup {
10408                primary_range,
10409                primary_message,
10410                group_id,
10411                blocks,
10412                is_valid: true,
10413            })
10414        });
10415    }
10416
10417    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10418        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10419            self.display_map.update(cx, |display_map, cx| {
10420                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10421            });
10422            cx.notify();
10423        }
10424    }
10425
10426    pub fn set_selections_from_remote(
10427        &mut self,
10428        selections: Vec<Selection<Anchor>>,
10429        pending_selection: Option<Selection<Anchor>>,
10430        cx: &mut ViewContext<Self>,
10431    ) {
10432        let old_cursor_position = self.selections.newest_anchor().head();
10433        self.selections.change_with(cx, |s| {
10434            s.select_anchors(selections);
10435            if let Some(pending_selection) = pending_selection {
10436                s.set_pending(pending_selection, SelectMode::Character);
10437            } else {
10438                s.clear_pending();
10439            }
10440        });
10441        self.selections_did_change(false, &old_cursor_position, true, cx);
10442    }
10443
10444    fn push_to_selection_history(&mut self) {
10445        self.selection_history.push(SelectionHistoryEntry {
10446            selections: self.selections.disjoint_anchors(),
10447            select_next_state: self.select_next_state.clone(),
10448            select_prev_state: self.select_prev_state.clone(),
10449            add_selections_state: self.add_selections_state.clone(),
10450        });
10451    }
10452
10453    pub fn transact(
10454        &mut self,
10455        cx: &mut ViewContext<Self>,
10456        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10457    ) -> Option<TransactionId> {
10458        self.start_transaction_at(Instant::now(), cx);
10459        update(self, cx);
10460        self.end_transaction_at(Instant::now(), cx)
10461    }
10462
10463    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10464        self.end_selection(cx);
10465        if let Some(tx_id) = self
10466            .buffer
10467            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10468        {
10469            self.selection_history
10470                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10471            cx.emit(EditorEvent::TransactionBegun {
10472                transaction_id: tx_id,
10473            })
10474        }
10475    }
10476
10477    pub fn end_transaction_at(
10478        &mut self,
10479        now: Instant,
10480        cx: &mut ViewContext<Self>,
10481    ) -> Option<TransactionId> {
10482        if let Some(transaction_id) = self
10483            .buffer
10484            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10485        {
10486            if let Some((_, end_selections)) =
10487                self.selection_history.transaction_mut(transaction_id)
10488            {
10489                *end_selections = Some(self.selections.disjoint_anchors());
10490            } else {
10491                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10492            }
10493
10494            cx.emit(EditorEvent::Edited { transaction_id });
10495            Some(transaction_id)
10496        } else {
10497            None
10498        }
10499    }
10500
10501    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10502        if self.is_singleton(cx) {
10503            let selection = self.selections.newest::<Point>(cx);
10504
10505            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10506            let range = if selection.is_empty() {
10507                let point = selection.head().to_display_point(&display_map);
10508                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10509                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10510                    .to_point(&display_map);
10511                start..end
10512            } else {
10513                selection.range()
10514            };
10515            if display_map.folds_in_range(range).next().is_some() {
10516                self.unfold_lines(&Default::default(), cx)
10517            } else {
10518                self.fold(&Default::default(), cx)
10519            }
10520        } else {
10521            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10522            let mut toggled_buffers = HashSet::default();
10523            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10524                self.selections
10525                    .disjoint_anchors()
10526                    .into_iter()
10527                    .map(|selection| selection.range()),
10528            ) {
10529                let buffer_id = buffer_snapshot.remote_id();
10530                if toggled_buffers.insert(buffer_id) {
10531                    if self.buffer_folded(buffer_id, cx) {
10532                        self.unfold_buffer(buffer_id, cx);
10533                    } else {
10534                        self.fold_buffer(buffer_id, cx);
10535                    }
10536                }
10537            }
10538        }
10539    }
10540
10541    pub fn toggle_fold_recursive(
10542        &mut self,
10543        _: &actions::ToggleFoldRecursive,
10544        cx: &mut ViewContext<Self>,
10545    ) {
10546        let selection = self.selections.newest::<Point>(cx);
10547
10548        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10549        let range = if selection.is_empty() {
10550            let point = selection.head().to_display_point(&display_map);
10551            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10552            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10553                .to_point(&display_map);
10554            start..end
10555        } else {
10556            selection.range()
10557        };
10558        if display_map.folds_in_range(range).next().is_some() {
10559            self.unfold_recursive(&Default::default(), cx)
10560        } else {
10561            self.fold_recursive(&Default::default(), cx)
10562        }
10563    }
10564
10565    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10566        if self.is_singleton(cx) {
10567            let mut to_fold = Vec::new();
10568            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10569            let selections = self.selections.all_adjusted(cx);
10570
10571            for selection in selections {
10572                let range = selection.range().sorted();
10573                let buffer_start_row = range.start.row;
10574
10575                if range.start.row != range.end.row {
10576                    let mut found = false;
10577                    let mut row = range.start.row;
10578                    while row <= range.end.row {
10579                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10580                        {
10581                            found = true;
10582                            row = crease.range().end.row + 1;
10583                            to_fold.push(crease);
10584                        } else {
10585                            row += 1
10586                        }
10587                    }
10588                    if found {
10589                        continue;
10590                    }
10591                }
10592
10593                for row in (0..=range.start.row).rev() {
10594                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10595                        if crease.range().end.row >= buffer_start_row {
10596                            to_fold.push(crease);
10597                            if row <= range.start.row {
10598                                break;
10599                            }
10600                        }
10601                    }
10602                }
10603            }
10604
10605            self.fold_creases(to_fold, true, cx);
10606        } else {
10607            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10608            let mut folded_buffers = HashSet::default();
10609            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10610                self.selections
10611                    .disjoint_anchors()
10612                    .into_iter()
10613                    .map(|selection| selection.range()),
10614            ) {
10615                let buffer_id = buffer_snapshot.remote_id();
10616                if folded_buffers.insert(buffer_id) {
10617                    self.fold_buffer(buffer_id, cx);
10618                }
10619            }
10620        }
10621    }
10622
10623    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10624        if !self.buffer.read(cx).is_singleton() {
10625            return;
10626        }
10627
10628        let fold_at_level = fold_at.level;
10629        let snapshot = self.buffer.read(cx).snapshot(cx);
10630        let mut to_fold = Vec::new();
10631        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10632
10633        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10634            while start_row < end_row {
10635                match self
10636                    .snapshot(cx)
10637                    .crease_for_buffer_row(MultiBufferRow(start_row))
10638                {
10639                    Some(crease) => {
10640                        let nested_start_row = crease.range().start.row + 1;
10641                        let nested_end_row = crease.range().end.row;
10642
10643                        if current_level < fold_at_level {
10644                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10645                        } else if current_level == fold_at_level {
10646                            to_fold.push(crease);
10647                        }
10648
10649                        start_row = nested_end_row + 1;
10650                    }
10651                    None => start_row += 1,
10652                }
10653            }
10654        }
10655
10656        self.fold_creases(to_fold, true, cx);
10657    }
10658
10659    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10660        if self.buffer.read(cx).is_singleton() {
10661            let mut fold_ranges = Vec::new();
10662            let snapshot = self.buffer.read(cx).snapshot(cx);
10663
10664            for row in 0..snapshot.max_row().0 {
10665                if let Some(foldable_range) =
10666                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10667                {
10668                    fold_ranges.push(foldable_range);
10669                }
10670            }
10671
10672            self.fold_creases(fold_ranges, true, cx);
10673        } else {
10674            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10675                editor
10676                    .update(&mut cx, |editor, cx| {
10677                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10678                            editor.fold_buffer(buffer_id, cx);
10679                        }
10680                    })
10681                    .ok();
10682            });
10683        }
10684    }
10685
10686    pub fn fold_function_bodies(
10687        &mut self,
10688        _: &actions::FoldFunctionBodies,
10689        cx: &mut ViewContext<Self>,
10690    ) {
10691        let snapshot = self.buffer.read(cx).snapshot(cx);
10692        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10693            return;
10694        };
10695        let creases = buffer
10696            .function_body_fold_ranges(0..buffer.len())
10697            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10698            .collect();
10699
10700        self.fold_creases(creases, true, cx);
10701    }
10702
10703    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10704        let mut to_fold = Vec::new();
10705        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10706        let selections = self.selections.all_adjusted(cx);
10707
10708        for selection in selections {
10709            let range = selection.range().sorted();
10710            let buffer_start_row = range.start.row;
10711
10712            if range.start.row != range.end.row {
10713                let mut found = false;
10714                for row in range.start.row..=range.end.row {
10715                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10716                        found = true;
10717                        to_fold.push(crease);
10718                    }
10719                }
10720                if found {
10721                    continue;
10722                }
10723            }
10724
10725            for row in (0..=range.start.row).rev() {
10726                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10727                    if crease.range().end.row >= buffer_start_row {
10728                        to_fold.push(crease);
10729                    } else {
10730                        break;
10731                    }
10732                }
10733            }
10734        }
10735
10736        self.fold_creases(to_fold, true, cx);
10737    }
10738
10739    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10740        let buffer_row = fold_at.buffer_row;
10741        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10742
10743        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10744            let autoscroll = self
10745                .selections
10746                .all::<Point>(cx)
10747                .iter()
10748                .any(|selection| crease.range().overlaps(&selection.range()));
10749
10750            self.fold_creases(vec![crease], autoscroll, cx);
10751        }
10752    }
10753
10754    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10755        if self.is_singleton(cx) {
10756            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10757            let buffer = &display_map.buffer_snapshot;
10758            let selections = self.selections.all::<Point>(cx);
10759            let ranges = selections
10760                .iter()
10761                .map(|s| {
10762                    let range = s.display_range(&display_map).sorted();
10763                    let mut start = range.start.to_point(&display_map);
10764                    let mut end = range.end.to_point(&display_map);
10765                    start.column = 0;
10766                    end.column = buffer.line_len(MultiBufferRow(end.row));
10767                    start..end
10768                })
10769                .collect::<Vec<_>>();
10770
10771            self.unfold_ranges(&ranges, true, true, cx);
10772        } else {
10773            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10774            let mut unfolded_buffers = HashSet::default();
10775            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10776                self.selections
10777                    .disjoint_anchors()
10778                    .into_iter()
10779                    .map(|selection| selection.range()),
10780            ) {
10781                let buffer_id = buffer_snapshot.remote_id();
10782                if unfolded_buffers.insert(buffer_id) {
10783                    self.unfold_buffer(buffer_id, cx);
10784                }
10785            }
10786        }
10787    }
10788
10789    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10790        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10791        let selections = self.selections.all::<Point>(cx);
10792        let ranges = selections
10793            .iter()
10794            .map(|s| {
10795                let mut range = s.display_range(&display_map).sorted();
10796                *range.start.column_mut() = 0;
10797                *range.end.column_mut() = display_map.line_len(range.end.row());
10798                let start = range.start.to_point(&display_map);
10799                let end = range.end.to_point(&display_map);
10800                start..end
10801            })
10802            .collect::<Vec<_>>();
10803
10804        self.unfold_ranges(&ranges, true, true, cx);
10805    }
10806
10807    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10809
10810        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10811            ..Point::new(
10812                unfold_at.buffer_row.0,
10813                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10814            );
10815
10816        let autoscroll = self
10817            .selections
10818            .all::<Point>(cx)
10819            .iter()
10820            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10821
10822        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10823    }
10824
10825    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10826        if self.buffer.read(cx).is_singleton() {
10827            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10828            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10829        } else {
10830            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10831                editor
10832                    .update(&mut cx, |editor, cx| {
10833                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10834                            editor.unfold_buffer(buffer_id, cx);
10835                        }
10836                    })
10837                    .ok();
10838            });
10839        }
10840    }
10841
10842    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10843        let selections = self.selections.all::<Point>(cx);
10844        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10845        let line_mode = self.selections.line_mode;
10846        let ranges = selections
10847            .into_iter()
10848            .map(|s| {
10849                if line_mode {
10850                    let start = Point::new(s.start.row, 0);
10851                    let end = Point::new(
10852                        s.end.row,
10853                        display_map
10854                            .buffer_snapshot
10855                            .line_len(MultiBufferRow(s.end.row)),
10856                    );
10857                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10858                } else {
10859                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10860                }
10861            })
10862            .collect::<Vec<_>>();
10863        self.fold_creases(ranges, true, cx);
10864    }
10865
10866    pub fn fold_creases<T: ToOffset + Clone>(
10867        &mut self,
10868        creases: Vec<Crease<T>>,
10869        auto_scroll: bool,
10870        cx: &mut ViewContext<Self>,
10871    ) {
10872        if creases.is_empty() {
10873            return;
10874        }
10875
10876        let mut buffers_affected = HashSet::default();
10877        let multi_buffer = self.buffer().read(cx);
10878        for crease in &creases {
10879            if let Some((_, buffer, _)) =
10880                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10881            {
10882                buffers_affected.insert(buffer.read(cx).remote_id());
10883            };
10884        }
10885
10886        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10887
10888        if auto_scroll {
10889            self.request_autoscroll(Autoscroll::fit(), cx);
10890        }
10891
10892        for buffer_id in buffers_affected {
10893            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10894        }
10895
10896        cx.notify();
10897
10898        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10899            // Clear diagnostics block when folding a range that contains it.
10900            let snapshot = self.snapshot(cx);
10901            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10902                drop(snapshot);
10903                self.active_diagnostics = Some(active_diagnostics);
10904                self.dismiss_diagnostics(cx);
10905            } else {
10906                self.active_diagnostics = Some(active_diagnostics);
10907            }
10908        }
10909
10910        self.scrollbar_marker_state.dirty = true;
10911    }
10912
10913    /// Removes any folds whose ranges intersect any of the given ranges.
10914    pub fn unfold_ranges<T: ToOffset + Clone>(
10915        &mut self,
10916        ranges: &[Range<T>],
10917        inclusive: bool,
10918        auto_scroll: bool,
10919        cx: &mut ViewContext<Self>,
10920    ) {
10921        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10922            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10923        });
10924    }
10925
10926    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10927        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10928            return;
10929        }
10930        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10931            return;
10932        };
10933        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10934        self.display_map
10935            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10936        cx.emit(EditorEvent::BufferFoldToggled {
10937            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10938            folded: true,
10939        });
10940        cx.notify();
10941    }
10942
10943    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10944        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10945            return;
10946        }
10947        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10948            return;
10949        };
10950        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10951        self.display_map.update(cx, |display_map, cx| {
10952            display_map.unfold_buffer(buffer_id, cx);
10953        });
10954        cx.emit(EditorEvent::BufferFoldToggled {
10955            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10956            folded: false,
10957        });
10958        cx.notify();
10959    }
10960
10961    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10962        self.display_map.read(cx).buffer_folded(buffer)
10963    }
10964
10965    /// Removes any folds with the given ranges.
10966    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10967        &mut self,
10968        ranges: &[Range<T>],
10969        type_id: TypeId,
10970        auto_scroll: bool,
10971        cx: &mut ViewContext<Self>,
10972    ) {
10973        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10974            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10975        });
10976    }
10977
10978    fn remove_folds_with<T: ToOffset + Clone>(
10979        &mut self,
10980        ranges: &[Range<T>],
10981        auto_scroll: bool,
10982        cx: &mut ViewContext<Self>,
10983        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10984    ) {
10985        if ranges.is_empty() {
10986            return;
10987        }
10988
10989        let mut buffers_affected = HashSet::default();
10990        let multi_buffer = self.buffer().read(cx);
10991        for range in ranges {
10992            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10993                buffers_affected.insert(buffer.read(cx).remote_id());
10994            };
10995        }
10996
10997        self.display_map.update(cx, update);
10998
10999        if auto_scroll {
11000            self.request_autoscroll(Autoscroll::fit(), cx);
11001        }
11002
11003        for buffer_id in buffers_affected {
11004            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11005        }
11006
11007        cx.notify();
11008        self.scrollbar_marker_state.dirty = true;
11009        self.active_indent_guides_state.dirty = true;
11010    }
11011
11012    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11013        self.display_map.read(cx).fold_placeholder.clone()
11014    }
11015
11016    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11017        if hovered != self.gutter_hovered {
11018            self.gutter_hovered = hovered;
11019            cx.notify();
11020        }
11021    }
11022
11023    pub fn insert_blocks(
11024        &mut self,
11025        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11026        autoscroll: Option<Autoscroll>,
11027        cx: &mut ViewContext<Self>,
11028    ) -> Vec<CustomBlockId> {
11029        let blocks = self
11030            .display_map
11031            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11032        if let Some(autoscroll) = autoscroll {
11033            self.request_autoscroll(autoscroll, cx);
11034        }
11035        cx.notify();
11036        blocks
11037    }
11038
11039    pub fn resize_blocks(
11040        &mut self,
11041        heights: HashMap<CustomBlockId, u32>,
11042        autoscroll: Option<Autoscroll>,
11043        cx: &mut ViewContext<Self>,
11044    ) {
11045        self.display_map
11046            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11047        if let Some(autoscroll) = autoscroll {
11048            self.request_autoscroll(autoscroll, cx);
11049        }
11050        cx.notify();
11051    }
11052
11053    pub fn replace_blocks(
11054        &mut self,
11055        renderers: HashMap<CustomBlockId, RenderBlock>,
11056        autoscroll: Option<Autoscroll>,
11057        cx: &mut ViewContext<Self>,
11058    ) {
11059        self.display_map
11060            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11061        if let Some(autoscroll) = autoscroll {
11062            self.request_autoscroll(autoscroll, cx);
11063        }
11064        cx.notify();
11065    }
11066
11067    pub fn remove_blocks(
11068        &mut self,
11069        block_ids: HashSet<CustomBlockId>,
11070        autoscroll: Option<Autoscroll>,
11071        cx: &mut ViewContext<Self>,
11072    ) {
11073        self.display_map.update(cx, |display_map, cx| {
11074            display_map.remove_blocks(block_ids, cx)
11075        });
11076        if let Some(autoscroll) = autoscroll {
11077            self.request_autoscroll(autoscroll, cx);
11078        }
11079        cx.notify();
11080    }
11081
11082    pub fn row_for_block(
11083        &self,
11084        block_id: CustomBlockId,
11085        cx: &mut ViewContext<Self>,
11086    ) -> Option<DisplayRow> {
11087        self.display_map
11088            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11089    }
11090
11091    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11092        self.focused_block = Some(focused_block);
11093    }
11094
11095    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11096        self.focused_block.take()
11097    }
11098
11099    pub fn insert_creases(
11100        &mut self,
11101        creases: impl IntoIterator<Item = Crease<Anchor>>,
11102        cx: &mut ViewContext<Self>,
11103    ) -> Vec<CreaseId> {
11104        self.display_map
11105            .update(cx, |map, cx| map.insert_creases(creases, cx))
11106    }
11107
11108    pub fn remove_creases(
11109        &mut self,
11110        ids: impl IntoIterator<Item = CreaseId>,
11111        cx: &mut ViewContext<Self>,
11112    ) {
11113        self.display_map
11114            .update(cx, |map, cx| map.remove_creases(ids, cx));
11115    }
11116
11117    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11118        self.display_map
11119            .update(cx, |map, cx| map.snapshot(cx))
11120            .longest_row()
11121    }
11122
11123    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11124        self.display_map
11125            .update(cx, |map, cx| map.snapshot(cx))
11126            .max_point()
11127    }
11128
11129    pub fn text(&self, cx: &AppContext) -> String {
11130        self.buffer.read(cx).read(cx).text()
11131    }
11132
11133    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11134        let text = self.text(cx);
11135        let text = text.trim();
11136
11137        if text.is_empty() {
11138            return None;
11139        }
11140
11141        Some(text.to_string())
11142    }
11143
11144    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11145        self.transact(cx, |this, cx| {
11146            this.buffer
11147                .read(cx)
11148                .as_singleton()
11149                .expect("you can only call set_text on editors for singleton buffers")
11150                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11151        });
11152    }
11153
11154    pub fn display_text(&self, cx: &mut AppContext) -> String {
11155        self.display_map
11156            .update(cx, |map, cx| map.snapshot(cx))
11157            .text()
11158    }
11159
11160    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11161        let mut wrap_guides = smallvec::smallvec![];
11162
11163        if self.show_wrap_guides == Some(false) {
11164            return wrap_guides;
11165        }
11166
11167        let settings = self.buffer.read(cx).settings_at(0, cx);
11168        if settings.show_wrap_guides {
11169            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11170                wrap_guides.push((soft_wrap as usize, true));
11171            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11172                wrap_guides.push((soft_wrap as usize, true));
11173            }
11174            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11175        }
11176
11177        wrap_guides
11178    }
11179
11180    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11181        let settings = self.buffer.read(cx).settings_at(0, cx);
11182        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11183        match mode {
11184            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11185                SoftWrap::None
11186            }
11187            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11188            language_settings::SoftWrap::PreferredLineLength => {
11189                SoftWrap::Column(settings.preferred_line_length)
11190            }
11191            language_settings::SoftWrap::Bounded => {
11192                SoftWrap::Bounded(settings.preferred_line_length)
11193            }
11194        }
11195    }
11196
11197    pub fn set_soft_wrap_mode(
11198        &mut self,
11199        mode: language_settings::SoftWrap,
11200        cx: &mut ViewContext<Self>,
11201    ) {
11202        self.soft_wrap_mode_override = Some(mode);
11203        cx.notify();
11204    }
11205
11206    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11207        self.text_style_refinement = Some(style);
11208    }
11209
11210    /// called by the Element so we know what style we were most recently rendered with.
11211    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11212        let rem_size = cx.rem_size();
11213        self.display_map.update(cx, |map, cx| {
11214            map.set_font(
11215                style.text.font(),
11216                style.text.font_size.to_pixels(rem_size),
11217                cx,
11218            )
11219        });
11220        self.style = Some(style);
11221    }
11222
11223    pub fn style(&self) -> Option<&EditorStyle> {
11224        self.style.as_ref()
11225    }
11226
11227    // Called by the element. This method is not designed to be called outside of the editor
11228    // element's layout code because it does not notify when rewrapping is computed synchronously.
11229    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11230        self.display_map
11231            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11232    }
11233
11234    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11235        if self.soft_wrap_mode_override.is_some() {
11236            self.soft_wrap_mode_override.take();
11237        } else {
11238            let soft_wrap = match self.soft_wrap_mode(cx) {
11239                SoftWrap::GitDiff => return,
11240                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11241                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11242                    language_settings::SoftWrap::None
11243                }
11244            };
11245            self.soft_wrap_mode_override = Some(soft_wrap);
11246        }
11247        cx.notify();
11248    }
11249
11250    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11251        let Some(workspace) = self.workspace() else {
11252            return;
11253        };
11254        let fs = workspace.read(cx).app_state().fs.clone();
11255        let current_show = TabBarSettings::get_global(cx).show;
11256        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11257            setting.show = Some(!current_show);
11258        });
11259    }
11260
11261    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11262        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11263            self.buffer
11264                .read(cx)
11265                .settings_at(0, cx)
11266                .indent_guides
11267                .enabled
11268        });
11269        self.show_indent_guides = Some(!currently_enabled);
11270        cx.notify();
11271    }
11272
11273    fn should_show_indent_guides(&self) -> Option<bool> {
11274        self.show_indent_guides
11275    }
11276
11277    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11278        let mut editor_settings = EditorSettings::get_global(cx).clone();
11279        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11280        EditorSettings::override_global(editor_settings, cx);
11281    }
11282
11283    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11284        self.use_relative_line_numbers
11285            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11286    }
11287
11288    pub fn toggle_relative_line_numbers(
11289        &mut self,
11290        _: &ToggleRelativeLineNumbers,
11291        cx: &mut ViewContext<Self>,
11292    ) {
11293        let is_relative = self.should_use_relative_line_numbers(cx);
11294        self.set_relative_line_number(Some(!is_relative), cx)
11295    }
11296
11297    pub fn set_relative_line_number(
11298        &mut self,
11299        is_relative: Option<bool>,
11300        cx: &mut ViewContext<Self>,
11301    ) {
11302        self.use_relative_line_numbers = is_relative;
11303        cx.notify();
11304    }
11305
11306    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11307        self.show_gutter = show_gutter;
11308        cx.notify();
11309    }
11310
11311    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11312        self.show_scrollbars = show_scrollbars;
11313        cx.notify();
11314    }
11315
11316    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11317        self.show_line_numbers = Some(show_line_numbers);
11318        cx.notify();
11319    }
11320
11321    pub fn set_show_git_diff_gutter(
11322        &mut self,
11323        show_git_diff_gutter: bool,
11324        cx: &mut ViewContext<Self>,
11325    ) {
11326        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11327        cx.notify();
11328    }
11329
11330    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11331        self.show_code_actions = Some(show_code_actions);
11332        cx.notify();
11333    }
11334
11335    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11336        self.show_runnables = Some(show_runnables);
11337        cx.notify();
11338    }
11339
11340    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11341        if self.display_map.read(cx).masked != masked {
11342            self.display_map.update(cx, |map, _| map.masked = masked);
11343        }
11344        cx.notify()
11345    }
11346
11347    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11348        self.show_wrap_guides = Some(show_wrap_guides);
11349        cx.notify();
11350    }
11351
11352    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11353        self.show_indent_guides = Some(show_indent_guides);
11354        cx.notify();
11355    }
11356
11357    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11358        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11359            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11360                if let Some(dir) = file.abs_path(cx).parent() {
11361                    return Some(dir.to_owned());
11362                }
11363            }
11364
11365            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11366                return Some(project_path.path.to_path_buf());
11367            }
11368        }
11369
11370        None
11371    }
11372
11373    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11374        self.active_excerpt(cx)?
11375            .1
11376            .read(cx)
11377            .file()
11378            .and_then(|f| f.as_local())
11379    }
11380
11381    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11382        if let Some(target) = self.target_file(cx) {
11383            cx.reveal_path(&target.abs_path(cx));
11384        }
11385    }
11386
11387    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11388        if let Some(file) = self.target_file(cx) {
11389            if let Some(path) = file.abs_path(cx).to_str() {
11390                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11391            }
11392        }
11393    }
11394
11395    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11396        if let Some(file) = self.target_file(cx) {
11397            if let Some(path) = file.path().to_str() {
11398                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11399            }
11400        }
11401    }
11402
11403    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11404        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11405
11406        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11407            self.start_git_blame(true, cx);
11408        }
11409
11410        cx.notify();
11411    }
11412
11413    pub fn toggle_git_blame_inline(
11414        &mut self,
11415        _: &ToggleGitBlameInline,
11416        cx: &mut ViewContext<Self>,
11417    ) {
11418        self.toggle_git_blame_inline_internal(true, cx);
11419        cx.notify();
11420    }
11421
11422    pub fn git_blame_inline_enabled(&self) -> bool {
11423        self.git_blame_inline_enabled
11424    }
11425
11426    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11427        self.show_selection_menu = self
11428            .show_selection_menu
11429            .map(|show_selections_menu| !show_selections_menu)
11430            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11431
11432        cx.notify();
11433    }
11434
11435    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11436        self.show_selection_menu
11437            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11438    }
11439
11440    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11441        if let Some(project) = self.project.as_ref() {
11442            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11443                return;
11444            };
11445
11446            if buffer.read(cx).file().is_none() {
11447                return;
11448            }
11449
11450            let focused = self.focus_handle(cx).contains_focused(cx);
11451
11452            let project = project.clone();
11453            let blame =
11454                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11455            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11456            self.blame = Some(blame);
11457        }
11458    }
11459
11460    fn toggle_git_blame_inline_internal(
11461        &mut self,
11462        user_triggered: bool,
11463        cx: &mut ViewContext<Self>,
11464    ) {
11465        if self.git_blame_inline_enabled {
11466            self.git_blame_inline_enabled = false;
11467            self.show_git_blame_inline = false;
11468            self.show_git_blame_inline_delay_task.take();
11469        } else {
11470            self.git_blame_inline_enabled = true;
11471            self.start_git_blame_inline(user_triggered, cx);
11472        }
11473
11474        cx.notify();
11475    }
11476
11477    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11478        self.start_git_blame(user_triggered, cx);
11479
11480        if ProjectSettings::get_global(cx)
11481            .git
11482            .inline_blame_delay()
11483            .is_some()
11484        {
11485            self.start_inline_blame_timer(cx);
11486        } else {
11487            self.show_git_blame_inline = true
11488        }
11489    }
11490
11491    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11492        self.blame.as_ref()
11493    }
11494
11495    pub fn show_git_blame_gutter(&self) -> bool {
11496        self.show_git_blame_gutter
11497    }
11498
11499    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11500        self.show_git_blame_gutter && self.has_blame_entries(cx)
11501    }
11502
11503    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11504        self.show_git_blame_inline
11505            && self.focus_handle.is_focused(cx)
11506            && !self.newest_selection_head_on_empty_line(cx)
11507            && self.has_blame_entries(cx)
11508    }
11509
11510    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11511        self.blame()
11512            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11513    }
11514
11515    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11516        let cursor_anchor = self.selections.newest_anchor().head();
11517
11518        let snapshot = self.buffer.read(cx).snapshot(cx);
11519        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11520
11521        snapshot.line_len(buffer_row) == 0
11522    }
11523
11524    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11525        let buffer_and_selection = maybe!({
11526            let selection = self.selections.newest::<Point>(cx);
11527            let selection_range = selection.range();
11528
11529            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11530                (buffer, selection_range.start.row..selection_range.end.row)
11531            } else {
11532                let multi_buffer = self.buffer().read(cx);
11533                let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11534                let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11535
11536                let (excerpt, range) = if selection.reversed {
11537                    buffer_ranges.first()
11538                } else {
11539                    buffer_ranges.last()
11540                }?;
11541
11542                let snapshot = excerpt.buffer();
11543                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11544                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11545                (
11546                    multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11547                    selection,
11548                )
11549            };
11550
11551            Some((buffer, selection))
11552        });
11553
11554        let Some((buffer, selection)) = buffer_and_selection else {
11555            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11556        };
11557
11558        let Some(project) = self.project.as_ref() else {
11559            return Task::ready(Err(anyhow!("editor does not have project")));
11560        };
11561
11562        project.update(cx, |project, cx| {
11563            project.get_permalink_to_line(&buffer, selection, cx)
11564        })
11565    }
11566
11567    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11568        let permalink_task = self.get_permalink_to_line(cx);
11569        let workspace = self.workspace();
11570
11571        cx.spawn(|_, mut cx| async move {
11572            match permalink_task.await {
11573                Ok(permalink) => {
11574                    cx.update(|cx| {
11575                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11576                    })
11577                    .ok();
11578                }
11579                Err(err) => {
11580                    let message = format!("Failed to copy permalink: {err}");
11581
11582                    Err::<(), anyhow::Error>(err).log_err();
11583
11584                    if let Some(workspace) = workspace {
11585                        workspace
11586                            .update(&mut cx, |workspace, cx| {
11587                                struct CopyPermalinkToLine;
11588
11589                                workspace.show_toast(
11590                                    Toast::new(
11591                                        NotificationId::unique::<CopyPermalinkToLine>(),
11592                                        message,
11593                                    ),
11594                                    cx,
11595                                )
11596                            })
11597                            .ok();
11598                    }
11599                }
11600            }
11601        })
11602        .detach();
11603    }
11604
11605    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11606        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11607        if let Some(file) = self.target_file(cx) {
11608            if let Some(path) = file.path().to_str() {
11609                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11610            }
11611        }
11612    }
11613
11614    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11615        let permalink_task = self.get_permalink_to_line(cx);
11616        let workspace = self.workspace();
11617
11618        cx.spawn(|_, mut cx| async move {
11619            match permalink_task.await {
11620                Ok(permalink) => {
11621                    cx.update(|cx| {
11622                        cx.open_url(permalink.as_ref());
11623                    })
11624                    .ok();
11625                }
11626                Err(err) => {
11627                    let message = format!("Failed to open permalink: {err}");
11628
11629                    Err::<(), anyhow::Error>(err).log_err();
11630
11631                    if let Some(workspace) = workspace {
11632                        workspace
11633                            .update(&mut cx, |workspace, cx| {
11634                                struct OpenPermalinkToLine;
11635
11636                                workspace.show_toast(
11637                                    Toast::new(
11638                                        NotificationId::unique::<OpenPermalinkToLine>(),
11639                                        message,
11640                                    ),
11641                                    cx,
11642                                )
11643                            })
11644                            .ok();
11645                    }
11646                }
11647            }
11648        })
11649        .detach();
11650    }
11651
11652    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11653        self.insert_uuid(UuidVersion::V4, cx);
11654    }
11655
11656    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11657        self.insert_uuid(UuidVersion::V7, cx);
11658    }
11659
11660    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11661        self.transact(cx, |this, cx| {
11662            let edits = this
11663                .selections
11664                .all::<Point>(cx)
11665                .into_iter()
11666                .map(|selection| {
11667                    let uuid = match version {
11668                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11669                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11670                    };
11671
11672                    (selection.range(), uuid.to_string())
11673                });
11674            this.edit(edits, cx);
11675            this.refresh_inline_completion(true, false, cx);
11676        });
11677    }
11678
11679    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11680    /// last highlight added will be used.
11681    ///
11682    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11683    pub fn highlight_rows<T: 'static>(
11684        &mut self,
11685        range: Range<Anchor>,
11686        color: Hsla,
11687        should_autoscroll: bool,
11688        cx: &mut ViewContext<Self>,
11689    ) {
11690        let snapshot = self.buffer().read(cx).snapshot(cx);
11691        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11692        let ix = row_highlights.binary_search_by(|highlight| {
11693            Ordering::Equal
11694                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11695                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11696        });
11697
11698        if let Err(mut ix) = ix {
11699            let index = post_inc(&mut self.highlight_order);
11700
11701            // If this range intersects with the preceding highlight, then merge it with
11702            // the preceding highlight. Otherwise insert a new highlight.
11703            let mut merged = false;
11704            if ix > 0 {
11705                let prev_highlight = &mut row_highlights[ix - 1];
11706                if prev_highlight
11707                    .range
11708                    .end
11709                    .cmp(&range.start, &snapshot)
11710                    .is_ge()
11711                {
11712                    ix -= 1;
11713                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11714                        prev_highlight.range.end = range.end;
11715                    }
11716                    merged = true;
11717                    prev_highlight.index = index;
11718                    prev_highlight.color = color;
11719                    prev_highlight.should_autoscroll = should_autoscroll;
11720                }
11721            }
11722
11723            if !merged {
11724                row_highlights.insert(
11725                    ix,
11726                    RowHighlight {
11727                        range: range.clone(),
11728                        index,
11729                        color,
11730                        should_autoscroll,
11731                    },
11732                );
11733            }
11734
11735            // If any of the following highlights intersect with this one, merge them.
11736            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11737                let highlight = &row_highlights[ix];
11738                if next_highlight
11739                    .range
11740                    .start
11741                    .cmp(&highlight.range.end, &snapshot)
11742                    .is_le()
11743                {
11744                    if next_highlight
11745                        .range
11746                        .end
11747                        .cmp(&highlight.range.end, &snapshot)
11748                        .is_gt()
11749                    {
11750                        row_highlights[ix].range.end = next_highlight.range.end;
11751                    }
11752                    row_highlights.remove(ix + 1);
11753                } else {
11754                    break;
11755                }
11756            }
11757        }
11758    }
11759
11760    /// Remove any highlighted row ranges of the given type that intersect the
11761    /// given ranges.
11762    pub fn remove_highlighted_rows<T: 'static>(
11763        &mut self,
11764        ranges_to_remove: Vec<Range<Anchor>>,
11765        cx: &mut ViewContext<Self>,
11766    ) {
11767        let snapshot = self.buffer().read(cx).snapshot(cx);
11768        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11769        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11770        row_highlights.retain(|highlight| {
11771            while let Some(range_to_remove) = ranges_to_remove.peek() {
11772                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11773                    Ordering::Less | Ordering::Equal => {
11774                        ranges_to_remove.next();
11775                    }
11776                    Ordering::Greater => {
11777                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11778                            Ordering::Less | Ordering::Equal => {
11779                                return false;
11780                            }
11781                            Ordering::Greater => break,
11782                        }
11783                    }
11784                }
11785            }
11786
11787            true
11788        })
11789    }
11790
11791    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11792    pub fn clear_row_highlights<T: 'static>(&mut self) {
11793        self.highlighted_rows.remove(&TypeId::of::<T>());
11794    }
11795
11796    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11797    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11798        self.highlighted_rows
11799            .get(&TypeId::of::<T>())
11800            .map_or(&[] as &[_], |vec| vec.as_slice())
11801            .iter()
11802            .map(|highlight| (highlight.range.clone(), highlight.color))
11803    }
11804
11805    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11806    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11807    /// Allows to ignore certain kinds of highlights.
11808    pub fn highlighted_display_rows(
11809        &mut self,
11810        cx: &mut WindowContext,
11811    ) -> BTreeMap<DisplayRow, Hsla> {
11812        let snapshot = self.snapshot(cx);
11813        let mut used_highlight_orders = HashMap::default();
11814        self.highlighted_rows
11815            .iter()
11816            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11817            .fold(
11818                BTreeMap::<DisplayRow, Hsla>::new(),
11819                |mut unique_rows, highlight| {
11820                    let start = highlight.range.start.to_display_point(&snapshot);
11821                    let end = highlight.range.end.to_display_point(&snapshot);
11822                    let start_row = start.row().0;
11823                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11824                        && end.column() == 0
11825                    {
11826                        end.row().0.saturating_sub(1)
11827                    } else {
11828                        end.row().0
11829                    };
11830                    for row in start_row..=end_row {
11831                        let used_index =
11832                            used_highlight_orders.entry(row).or_insert(highlight.index);
11833                        if highlight.index >= *used_index {
11834                            *used_index = highlight.index;
11835                            unique_rows.insert(DisplayRow(row), highlight.color);
11836                        }
11837                    }
11838                    unique_rows
11839                },
11840            )
11841    }
11842
11843    pub fn highlighted_display_row_for_autoscroll(
11844        &self,
11845        snapshot: &DisplaySnapshot,
11846    ) -> Option<DisplayRow> {
11847        self.highlighted_rows
11848            .values()
11849            .flat_map(|highlighted_rows| highlighted_rows.iter())
11850            .filter_map(|highlight| {
11851                if highlight.should_autoscroll {
11852                    Some(highlight.range.start.to_display_point(snapshot).row())
11853                } else {
11854                    None
11855                }
11856            })
11857            .min()
11858    }
11859
11860    pub fn set_search_within_ranges(
11861        &mut self,
11862        ranges: &[Range<Anchor>],
11863        cx: &mut ViewContext<Self>,
11864    ) {
11865        self.highlight_background::<SearchWithinRange>(
11866            ranges,
11867            |colors| colors.editor_document_highlight_read_background,
11868            cx,
11869        )
11870    }
11871
11872    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11873        self.breadcrumb_header = Some(new_header);
11874    }
11875
11876    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11877        self.clear_background_highlights::<SearchWithinRange>(cx);
11878    }
11879
11880    pub fn highlight_background<T: 'static>(
11881        &mut self,
11882        ranges: &[Range<Anchor>],
11883        color_fetcher: fn(&ThemeColors) -> Hsla,
11884        cx: &mut ViewContext<Self>,
11885    ) {
11886        self.background_highlights
11887            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11888        self.scrollbar_marker_state.dirty = true;
11889        cx.notify();
11890    }
11891
11892    pub fn clear_background_highlights<T: 'static>(
11893        &mut self,
11894        cx: &mut ViewContext<Self>,
11895    ) -> Option<BackgroundHighlight> {
11896        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11897        if !text_highlights.1.is_empty() {
11898            self.scrollbar_marker_state.dirty = true;
11899            cx.notify();
11900        }
11901        Some(text_highlights)
11902    }
11903
11904    pub fn highlight_gutter<T: 'static>(
11905        &mut self,
11906        ranges: &[Range<Anchor>],
11907        color_fetcher: fn(&AppContext) -> Hsla,
11908        cx: &mut ViewContext<Self>,
11909    ) {
11910        self.gutter_highlights
11911            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11912        cx.notify();
11913    }
11914
11915    pub fn clear_gutter_highlights<T: 'static>(
11916        &mut self,
11917        cx: &mut ViewContext<Self>,
11918    ) -> Option<GutterHighlight> {
11919        cx.notify();
11920        self.gutter_highlights.remove(&TypeId::of::<T>())
11921    }
11922
11923    #[cfg(feature = "test-support")]
11924    pub fn all_text_background_highlights(
11925        &mut self,
11926        cx: &mut ViewContext<Self>,
11927    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11928        let snapshot = self.snapshot(cx);
11929        let buffer = &snapshot.buffer_snapshot;
11930        let start = buffer.anchor_before(0);
11931        let end = buffer.anchor_after(buffer.len());
11932        let theme = cx.theme().colors();
11933        self.background_highlights_in_range(start..end, &snapshot, theme)
11934    }
11935
11936    #[cfg(feature = "test-support")]
11937    pub fn search_background_highlights(
11938        &mut self,
11939        cx: &mut ViewContext<Self>,
11940    ) -> Vec<Range<Point>> {
11941        let snapshot = self.buffer().read(cx).snapshot(cx);
11942
11943        let highlights = self
11944            .background_highlights
11945            .get(&TypeId::of::<items::BufferSearchHighlights>());
11946
11947        if let Some((_color, ranges)) = highlights {
11948            ranges
11949                .iter()
11950                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11951                .collect_vec()
11952        } else {
11953            vec![]
11954        }
11955    }
11956
11957    fn document_highlights_for_position<'a>(
11958        &'a self,
11959        position: Anchor,
11960        buffer: &'a MultiBufferSnapshot,
11961    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11962        let read_highlights = self
11963            .background_highlights
11964            .get(&TypeId::of::<DocumentHighlightRead>())
11965            .map(|h| &h.1);
11966        let write_highlights = self
11967            .background_highlights
11968            .get(&TypeId::of::<DocumentHighlightWrite>())
11969            .map(|h| &h.1);
11970        let left_position = position.bias_left(buffer);
11971        let right_position = position.bias_right(buffer);
11972        read_highlights
11973            .into_iter()
11974            .chain(write_highlights)
11975            .flat_map(move |ranges| {
11976                let start_ix = match ranges.binary_search_by(|probe| {
11977                    let cmp = probe.end.cmp(&left_position, buffer);
11978                    if cmp.is_ge() {
11979                        Ordering::Greater
11980                    } else {
11981                        Ordering::Less
11982                    }
11983                }) {
11984                    Ok(i) | Err(i) => i,
11985                };
11986
11987                ranges[start_ix..]
11988                    .iter()
11989                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11990            })
11991    }
11992
11993    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11994        self.background_highlights
11995            .get(&TypeId::of::<T>())
11996            .map_or(false, |(_, highlights)| !highlights.is_empty())
11997    }
11998
11999    pub fn background_highlights_in_range(
12000        &self,
12001        search_range: Range<Anchor>,
12002        display_snapshot: &DisplaySnapshot,
12003        theme: &ThemeColors,
12004    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12005        let mut results = Vec::new();
12006        for (color_fetcher, ranges) in self.background_highlights.values() {
12007            let color = color_fetcher(theme);
12008            let start_ix = match ranges.binary_search_by(|probe| {
12009                let cmp = probe
12010                    .end
12011                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12012                if cmp.is_gt() {
12013                    Ordering::Greater
12014                } else {
12015                    Ordering::Less
12016                }
12017            }) {
12018                Ok(i) | Err(i) => i,
12019            };
12020            for range in &ranges[start_ix..] {
12021                if range
12022                    .start
12023                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12024                    .is_ge()
12025                {
12026                    break;
12027                }
12028
12029                let start = range.start.to_display_point(display_snapshot);
12030                let end = range.end.to_display_point(display_snapshot);
12031                results.push((start..end, color))
12032            }
12033        }
12034        results
12035    }
12036
12037    pub fn background_highlight_row_ranges<T: 'static>(
12038        &self,
12039        search_range: Range<Anchor>,
12040        display_snapshot: &DisplaySnapshot,
12041        count: usize,
12042    ) -> Vec<RangeInclusive<DisplayPoint>> {
12043        let mut results = Vec::new();
12044        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12045            return vec![];
12046        };
12047
12048        let start_ix = match ranges.binary_search_by(|probe| {
12049            let cmp = probe
12050                .end
12051                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12052            if cmp.is_gt() {
12053                Ordering::Greater
12054            } else {
12055                Ordering::Less
12056            }
12057        }) {
12058            Ok(i) | Err(i) => i,
12059        };
12060        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12061            if let (Some(start_display), Some(end_display)) = (start, end) {
12062                results.push(
12063                    start_display.to_display_point(display_snapshot)
12064                        ..=end_display.to_display_point(display_snapshot),
12065                );
12066            }
12067        };
12068        let mut start_row: Option<Point> = None;
12069        let mut end_row: Option<Point> = None;
12070        if ranges.len() > count {
12071            return Vec::new();
12072        }
12073        for range in &ranges[start_ix..] {
12074            if range
12075                .start
12076                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12077                .is_ge()
12078            {
12079                break;
12080            }
12081            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12082            if let Some(current_row) = &end_row {
12083                if end.row == current_row.row {
12084                    continue;
12085                }
12086            }
12087            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12088            if start_row.is_none() {
12089                assert_eq!(end_row, None);
12090                start_row = Some(start);
12091                end_row = Some(end);
12092                continue;
12093            }
12094            if let Some(current_end) = end_row.as_mut() {
12095                if start.row > current_end.row + 1 {
12096                    push_region(start_row, end_row);
12097                    start_row = Some(start);
12098                    end_row = Some(end);
12099                } else {
12100                    // Merge two hunks.
12101                    *current_end = end;
12102                }
12103            } else {
12104                unreachable!();
12105            }
12106        }
12107        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12108        push_region(start_row, end_row);
12109        results
12110    }
12111
12112    pub fn gutter_highlights_in_range(
12113        &self,
12114        search_range: Range<Anchor>,
12115        display_snapshot: &DisplaySnapshot,
12116        cx: &AppContext,
12117    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12118        let mut results = Vec::new();
12119        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12120            let color = color_fetcher(cx);
12121            let start_ix = match ranges.binary_search_by(|probe| {
12122                let cmp = probe
12123                    .end
12124                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12125                if cmp.is_gt() {
12126                    Ordering::Greater
12127                } else {
12128                    Ordering::Less
12129                }
12130            }) {
12131                Ok(i) | Err(i) => i,
12132            };
12133            for range in &ranges[start_ix..] {
12134                if range
12135                    .start
12136                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12137                    .is_ge()
12138                {
12139                    break;
12140                }
12141
12142                let start = range.start.to_display_point(display_snapshot);
12143                let end = range.end.to_display_point(display_snapshot);
12144                results.push((start..end, color))
12145            }
12146        }
12147        results
12148    }
12149
12150    /// Get the text ranges corresponding to the redaction query
12151    pub fn redacted_ranges(
12152        &self,
12153        search_range: Range<Anchor>,
12154        display_snapshot: &DisplaySnapshot,
12155        cx: &WindowContext,
12156    ) -> Vec<Range<DisplayPoint>> {
12157        display_snapshot
12158            .buffer_snapshot
12159            .redacted_ranges(search_range, |file| {
12160                if let Some(file) = file {
12161                    file.is_private()
12162                        && EditorSettings::get(
12163                            Some(SettingsLocation {
12164                                worktree_id: file.worktree_id(cx),
12165                                path: file.path().as_ref(),
12166                            }),
12167                            cx,
12168                        )
12169                        .redact_private_values
12170                } else {
12171                    false
12172                }
12173            })
12174            .map(|range| {
12175                range.start.to_display_point(display_snapshot)
12176                    ..range.end.to_display_point(display_snapshot)
12177            })
12178            .collect()
12179    }
12180
12181    pub fn highlight_text<T: 'static>(
12182        &mut self,
12183        ranges: Vec<Range<Anchor>>,
12184        style: HighlightStyle,
12185        cx: &mut ViewContext<Self>,
12186    ) {
12187        self.display_map.update(cx, |map, _| {
12188            map.highlight_text(TypeId::of::<T>(), ranges, style)
12189        });
12190        cx.notify();
12191    }
12192
12193    pub(crate) fn highlight_inlays<T: 'static>(
12194        &mut self,
12195        highlights: Vec<InlayHighlight>,
12196        style: HighlightStyle,
12197        cx: &mut ViewContext<Self>,
12198    ) {
12199        self.display_map.update(cx, |map, _| {
12200            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12201        });
12202        cx.notify();
12203    }
12204
12205    pub fn text_highlights<'a, T: 'static>(
12206        &'a self,
12207        cx: &'a AppContext,
12208    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12209        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12210    }
12211
12212    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12213        let cleared = self
12214            .display_map
12215            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12216        if cleared {
12217            cx.notify();
12218        }
12219    }
12220
12221    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12222        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12223            && self.focus_handle.is_focused(cx)
12224    }
12225
12226    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12227        self.show_cursor_when_unfocused = is_enabled;
12228        cx.notify();
12229    }
12230
12231    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12232        self.project
12233            .as_ref()
12234            .map(|project| project.read(cx).lsp_store())
12235    }
12236
12237    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12238        cx.notify();
12239    }
12240
12241    fn on_buffer_event(
12242        &mut self,
12243        multibuffer: Model<MultiBuffer>,
12244        event: &multi_buffer::Event,
12245        cx: &mut ViewContext<Self>,
12246    ) {
12247        match event {
12248            multi_buffer::Event::Edited {
12249                singleton_buffer_edited,
12250                edited_buffer: buffer_edited,
12251            } => {
12252                self.scrollbar_marker_state.dirty = true;
12253                self.active_indent_guides_state.dirty = true;
12254                self.refresh_active_diagnostics(cx);
12255                self.refresh_code_actions(cx);
12256                if self.has_active_inline_completion() {
12257                    self.update_visible_inline_completion(cx);
12258                }
12259                if let Some(buffer) = buffer_edited {
12260                    let buffer_id = buffer.read(cx).remote_id();
12261                    if !self.registered_buffers.contains_key(&buffer_id) {
12262                        if let Some(lsp_store) = self.lsp_store(cx) {
12263                            lsp_store.update(cx, |lsp_store, cx| {
12264                                self.registered_buffers.insert(
12265                                    buffer_id,
12266                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12267                                );
12268                            })
12269                        }
12270                    }
12271                }
12272                cx.emit(EditorEvent::BufferEdited);
12273                cx.emit(SearchEvent::MatchesInvalidated);
12274                if *singleton_buffer_edited {
12275                    if let Some(project) = &self.project {
12276                        let project = project.read(cx);
12277                        #[allow(clippy::mutable_key_type)]
12278                        let languages_affected = multibuffer
12279                            .read(cx)
12280                            .all_buffers()
12281                            .into_iter()
12282                            .filter_map(|buffer| {
12283                                let buffer = buffer.read(cx);
12284                                let language = buffer.language()?;
12285                                if project.is_local()
12286                                    && project
12287                                        .language_servers_for_local_buffer(buffer, cx)
12288                                        .count()
12289                                        == 0
12290                                {
12291                                    None
12292                                } else {
12293                                    Some(language)
12294                                }
12295                            })
12296                            .cloned()
12297                            .collect::<HashSet<_>>();
12298                        if !languages_affected.is_empty() {
12299                            self.refresh_inlay_hints(
12300                                InlayHintRefreshReason::BufferEdited(languages_affected),
12301                                cx,
12302                            );
12303                        }
12304                    }
12305                }
12306
12307                let Some(project) = &self.project else { return };
12308                let (telemetry, is_via_ssh) = {
12309                    let project = project.read(cx);
12310                    let telemetry = project.client().telemetry().clone();
12311                    let is_via_ssh = project.is_via_ssh();
12312                    (telemetry, is_via_ssh)
12313                };
12314                refresh_linked_ranges(self, cx);
12315                telemetry.log_edit_event("editor", is_via_ssh);
12316            }
12317            multi_buffer::Event::ExcerptsAdded {
12318                buffer,
12319                predecessor,
12320                excerpts,
12321            } => {
12322                self.tasks_update_task = Some(self.refresh_runnables(cx));
12323                let buffer_id = buffer.read(cx).remote_id();
12324                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12325                    if let Some(project) = &self.project {
12326                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12327                    }
12328                }
12329                cx.emit(EditorEvent::ExcerptsAdded {
12330                    buffer: buffer.clone(),
12331                    predecessor: *predecessor,
12332                    excerpts: excerpts.clone(),
12333                });
12334                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12335            }
12336            multi_buffer::Event::ExcerptsRemoved { ids } => {
12337                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12338                let buffer = self.buffer.read(cx);
12339                self.registered_buffers
12340                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12341                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12342            }
12343            multi_buffer::Event::ExcerptsEdited { ids } => {
12344                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12345            }
12346            multi_buffer::Event::ExcerptsExpanded { ids } => {
12347                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12348            }
12349            multi_buffer::Event::Reparsed(buffer_id) => {
12350                self.tasks_update_task = Some(self.refresh_runnables(cx));
12351
12352                cx.emit(EditorEvent::Reparsed(*buffer_id));
12353            }
12354            multi_buffer::Event::LanguageChanged(buffer_id) => {
12355                linked_editing_ranges::refresh_linked_ranges(self, cx);
12356                cx.emit(EditorEvent::Reparsed(*buffer_id));
12357                cx.notify();
12358            }
12359            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12360            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12361            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12362                cx.emit(EditorEvent::TitleChanged)
12363            }
12364            // multi_buffer::Event::DiffBaseChanged => {
12365            //     self.scrollbar_marker_state.dirty = true;
12366            //     cx.emit(EditorEvent::DiffBaseChanged);
12367            //     cx.notify();
12368            // }
12369            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12370            multi_buffer::Event::DiagnosticsUpdated => {
12371                self.refresh_active_diagnostics(cx);
12372                self.scrollbar_marker_state.dirty = true;
12373                cx.notify();
12374            }
12375            _ => {}
12376        };
12377    }
12378
12379    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12380        cx.notify();
12381    }
12382
12383    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12384        self.tasks_update_task = Some(self.refresh_runnables(cx));
12385        self.refresh_inline_completion(true, false, cx);
12386        self.refresh_inlay_hints(
12387            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12388                self.selections.newest_anchor().head(),
12389                &self.buffer.read(cx).snapshot(cx),
12390                cx,
12391            )),
12392            cx,
12393        );
12394
12395        let old_cursor_shape = self.cursor_shape;
12396
12397        {
12398            let editor_settings = EditorSettings::get_global(cx);
12399            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12400            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12401            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12402        }
12403
12404        if old_cursor_shape != self.cursor_shape {
12405            cx.emit(EditorEvent::CursorShapeChanged);
12406        }
12407
12408        let project_settings = ProjectSettings::get_global(cx);
12409        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12410
12411        if self.mode == EditorMode::Full {
12412            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12413            if self.git_blame_inline_enabled != inline_blame_enabled {
12414                self.toggle_git_blame_inline_internal(false, cx);
12415            }
12416        }
12417
12418        cx.notify();
12419    }
12420
12421    pub fn set_searchable(&mut self, searchable: bool) {
12422        self.searchable = searchable;
12423    }
12424
12425    pub fn searchable(&self) -> bool {
12426        self.searchable
12427    }
12428
12429    fn open_proposed_changes_editor(
12430        &mut self,
12431        _: &OpenProposedChangesEditor,
12432        cx: &mut ViewContext<Self>,
12433    ) {
12434        let Some(workspace) = self.workspace() else {
12435            cx.propagate();
12436            return;
12437        };
12438
12439        let selections = self.selections.all::<usize>(cx);
12440        let multi_buffer = self.buffer.read(cx);
12441        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12442        let mut new_selections_by_buffer = HashMap::default();
12443        for selection in selections {
12444            for (excerpt, range) in
12445                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12446            {
12447                let mut range = range.to_point(excerpt.buffer());
12448                range.start.column = 0;
12449                range.end.column = excerpt.buffer().line_len(range.end.row);
12450                new_selections_by_buffer
12451                    .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12452                    .or_insert(Vec::new())
12453                    .push(range)
12454            }
12455        }
12456
12457        let proposed_changes_buffers = new_selections_by_buffer
12458            .into_iter()
12459            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12460            .collect::<Vec<_>>();
12461        let proposed_changes_editor = cx.new_view(|cx| {
12462            ProposedChangesEditor::new(
12463                "Proposed changes",
12464                proposed_changes_buffers,
12465                self.project.clone(),
12466                cx,
12467            )
12468        });
12469
12470        cx.window_context().defer(move |cx| {
12471            workspace.update(cx, |workspace, cx| {
12472                workspace.active_pane().update(cx, |pane, cx| {
12473                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12474                });
12475            });
12476        });
12477    }
12478
12479    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12480        self.open_excerpts_common(None, true, cx)
12481    }
12482
12483    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12484        self.open_excerpts_common(None, false, cx)
12485    }
12486
12487    fn open_excerpts_common(
12488        &mut self,
12489        jump_data: Option<JumpData>,
12490        split: bool,
12491        cx: &mut ViewContext<Self>,
12492    ) {
12493        let Some(workspace) = self.workspace() else {
12494            cx.propagate();
12495            return;
12496        };
12497
12498        if self.buffer.read(cx).is_singleton() {
12499            cx.propagate();
12500            return;
12501        }
12502
12503        let mut new_selections_by_buffer = HashMap::default();
12504        match &jump_data {
12505            Some(JumpData::MultiBufferPoint {
12506                excerpt_id,
12507                position,
12508                anchor,
12509                line_offset_from_top,
12510            }) => {
12511                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12512                if let Some(buffer) = multi_buffer_snapshot
12513                    .buffer_id_for_excerpt(*excerpt_id)
12514                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12515                {
12516                    let buffer_snapshot = buffer.read(cx).snapshot();
12517                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12518                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12519                    } else {
12520                        buffer_snapshot.clip_point(*position, Bias::Left)
12521                    };
12522                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12523                    new_selections_by_buffer.insert(
12524                        buffer,
12525                        (
12526                            vec![jump_to_offset..jump_to_offset],
12527                            Some(*line_offset_from_top),
12528                        ),
12529                    );
12530                }
12531            }
12532            Some(JumpData::MultiBufferRow {
12533                row,
12534                line_offset_from_top,
12535            }) => {
12536                let point = MultiBufferPoint::new(row.0, 0);
12537                if let Some((buffer, buffer_point, _)) =
12538                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12539                {
12540                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12541                    new_selections_by_buffer
12542                        .entry(buffer)
12543                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12544                        .0
12545                        .push(buffer_offset..buffer_offset)
12546                }
12547            }
12548            None => {
12549                let selections = self.selections.all::<usize>(cx);
12550                let multi_buffer = self.buffer.read(cx);
12551                for selection in selections {
12552                    for (excerpt, mut range) in multi_buffer
12553                        .snapshot(cx)
12554                        .range_to_buffer_ranges(selection.range())
12555                    {
12556                        // When editing branch buffers, jump to the corresponding location
12557                        // in their base buffer.
12558                        let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12559                        let buffer = buffer_handle.read(cx);
12560                        if let Some(base_buffer) = buffer.base_buffer() {
12561                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12562                            buffer_handle = base_buffer;
12563                        }
12564
12565                        if selection.reversed {
12566                            mem::swap(&mut range.start, &mut range.end);
12567                        }
12568                        new_selections_by_buffer
12569                            .entry(buffer_handle)
12570                            .or_insert((Vec::new(), None))
12571                            .0
12572                            .push(range)
12573                    }
12574                }
12575            }
12576        }
12577
12578        if new_selections_by_buffer.is_empty() {
12579            return;
12580        }
12581
12582        // We defer the pane interaction because we ourselves are a workspace item
12583        // and activating a new item causes the pane to call a method on us reentrantly,
12584        // which panics if we're on the stack.
12585        cx.window_context().defer(move |cx| {
12586            workspace.update(cx, |workspace, cx| {
12587                let pane = if split {
12588                    workspace.adjacent_pane(cx)
12589                } else {
12590                    workspace.active_pane().clone()
12591                };
12592
12593                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12594                    let editor = buffer
12595                        .read(cx)
12596                        .file()
12597                        .is_none()
12598                        .then(|| {
12599                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12600                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12601                            // Instead, we try to activate the existing editor in the pane first.
12602                            let (editor, pane_item_index) =
12603                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12604                                    let editor = item.downcast::<Editor>()?;
12605                                    let singleton_buffer =
12606                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12607                                    if singleton_buffer == buffer {
12608                                        Some((editor, i))
12609                                    } else {
12610                                        None
12611                                    }
12612                                })?;
12613                            pane.update(cx, |pane, cx| {
12614                                pane.activate_item(pane_item_index, true, true, cx)
12615                            });
12616                            Some(editor)
12617                        })
12618                        .flatten()
12619                        .unwrap_or_else(|| {
12620                            workspace.open_project_item::<Self>(
12621                                pane.clone(),
12622                                buffer,
12623                                true,
12624                                true,
12625                                cx,
12626                            )
12627                        });
12628
12629                    editor.update(cx, |editor, cx| {
12630                        let autoscroll = match scroll_offset {
12631                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12632                            None => Autoscroll::newest(),
12633                        };
12634                        let nav_history = editor.nav_history.take();
12635                        editor.change_selections(Some(autoscroll), cx, |s| {
12636                            s.select_ranges(ranges);
12637                        });
12638                        editor.nav_history = nav_history;
12639                    });
12640                }
12641            })
12642        });
12643    }
12644
12645    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12646        let snapshot = self.buffer.read(cx).read(cx);
12647        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12648        Some(
12649            ranges
12650                .iter()
12651                .map(move |range| {
12652                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12653                })
12654                .collect(),
12655        )
12656    }
12657
12658    fn selection_replacement_ranges(
12659        &self,
12660        range: Range<OffsetUtf16>,
12661        cx: &mut AppContext,
12662    ) -> Vec<Range<OffsetUtf16>> {
12663        let selections = self.selections.all::<OffsetUtf16>(cx);
12664        let newest_selection = selections
12665            .iter()
12666            .max_by_key(|selection| selection.id)
12667            .unwrap();
12668        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12669        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12670        let snapshot = self.buffer.read(cx).read(cx);
12671        selections
12672            .into_iter()
12673            .map(|mut selection| {
12674                selection.start.0 =
12675                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12676                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12677                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12678                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12679            })
12680            .collect()
12681    }
12682
12683    fn report_editor_event(
12684        &self,
12685        event_type: &'static str,
12686        file_extension: Option<String>,
12687        cx: &AppContext,
12688    ) {
12689        if cfg!(any(test, feature = "test-support")) {
12690            return;
12691        }
12692
12693        let Some(project) = &self.project else { return };
12694
12695        // If None, we are in a file without an extension
12696        let file = self
12697            .buffer
12698            .read(cx)
12699            .as_singleton()
12700            .and_then(|b| b.read(cx).file());
12701        let file_extension = file_extension.or(file
12702            .as_ref()
12703            .and_then(|file| Path::new(file.file_name(cx)).extension())
12704            .and_then(|e| e.to_str())
12705            .map(|a| a.to_string()));
12706
12707        let vim_mode = cx
12708            .global::<SettingsStore>()
12709            .raw_user_settings()
12710            .get("vim_mode")
12711            == Some(&serde_json::Value::Bool(true));
12712
12713        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12714            == language::language_settings::InlineCompletionProvider::Copilot;
12715        let copilot_enabled_for_language = self
12716            .buffer
12717            .read(cx)
12718            .settings_at(0, cx)
12719            .show_inline_completions;
12720
12721        let project = project.read(cx);
12722        telemetry::event!(
12723            event_type,
12724            file_extension,
12725            vim_mode,
12726            copilot_enabled,
12727            copilot_enabled_for_language,
12728            is_via_ssh = project.is_via_ssh(),
12729        );
12730    }
12731
12732    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12733    /// with each line being an array of {text, highlight} objects.
12734    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12735        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12736            return;
12737        };
12738
12739        #[derive(Serialize)]
12740        struct Chunk<'a> {
12741            text: String,
12742            highlight: Option<&'a str>,
12743        }
12744
12745        let snapshot = buffer.read(cx).snapshot();
12746        let range = self
12747            .selected_text_range(false, cx)
12748            .and_then(|selection| {
12749                if selection.range.is_empty() {
12750                    None
12751                } else {
12752                    Some(selection.range)
12753                }
12754            })
12755            .unwrap_or_else(|| 0..snapshot.len());
12756
12757        let chunks = snapshot.chunks(range, true);
12758        let mut lines = Vec::new();
12759        let mut line: VecDeque<Chunk> = VecDeque::new();
12760
12761        let Some(style) = self.style.as_ref() else {
12762            return;
12763        };
12764
12765        for chunk in chunks {
12766            let highlight = chunk
12767                .syntax_highlight_id
12768                .and_then(|id| id.name(&style.syntax));
12769            let mut chunk_lines = chunk.text.split('\n').peekable();
12770            while let Some(text) = chunk_lines.next() {
12771                let mut merged_with_last_token = false;
12772                if let Some(last_token) = line.back_mut() {
12773                    if last_token.highlight == highlight {
12774                        last_token.text.push_str(text);
12775                        merged_with_last_token = true;
12776                    }
12777                }
12778
12779                if !merged_with_last_token {
12780                    line.push_back(Chunk {
12781                        text: text.into(),
12782                        highlight,
12783                    });
12784                }
12785
12786                if chunk_lines.peek().is_some() {
12787                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12788                        line.pop_front();
12789                    }
12790                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12791                        line.pop_back();
12792                    }
12793
12794                    lines.push(mem::take(&mut line));
12795                }
12796            }
12797        }
12798
12799        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12800            return;
12801        };
12802        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12803    }
12804
12805    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12806        self.request_autoscroll(Autoscroll::newest(), cx);
12807        let position = self.selections.newest_display(cx).start;
12808        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12809    }
12810
12811    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12812        &self.inlay_hint_cache
12813    }
12814
12815    pub fn replay_insert_event(
12816        &mut self,
12817        text: &str,
12818        relative_utf16_range: Option<Range<isize>>,
12819        cx: &mut ViewContext<Self>,
12820    ) {
12821        if !self.input_enabled {
12822            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12823            return;
12824        }
12825        if let Some(relative_utf16_range) = relative_utf16_range {
12826            let selections = self.selections.all::<OffsetUtf16>(cx);
12827            self.change_selections(None, cx, |s| {
12828                let new_ranges = selections.into_iter().map(|range| {
12829                    let start = OffsetUtf16(
12830                        range
12831                            .head()
12832                            .0
12833                            .saturating_add_signed(relative_utf16_range.start),
12834                    );
12835                    let end = OffsetUtf16(
12836                        range
12837                            .head()
12838                            .0
12839                            .saturating_add_signed(relative_utf16_range.end),
12840                    );
12841                    start..end
12842                });
12843                s.select_ranges(new_ranges);
12844            });
12845        }
12846
12847        self.handle_input(text, cx);
12848    }
12849
12850    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12851        let Some(provider) = self.semantics_provider.as_ref() else {
12852            return false;
12853        };
12854
12855        let mut supports = false;
12856        self.buffer().read(cx).for_each_buffer(|buffer| {
12857            supports |= provider.supports_inlay_hints(buffer, cx);
12858        });
12859        supports
12860    }
12861
12862    pub fn focus(&self, cx: &mut WindowContext) {
12863        cx.focus(&self.focus_handle)
12864    }
12865
12866    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12867        self.focus_handle.is_focused(cx)
12868    }
12869
12870    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12871        cx.emit(EditorEvent::Focused);
12872
12873        if let Some(descendant) = self
12874            .last_focused_descendant
12875            .take()
12876            .and_then(|descendant| descendant.upgrade())
12877        {
12878            cx.focus(&descendant);
12879        } else {
12880            if let Some(blame) = self.blame.as_ref() {
12881                blame.update(cx, GitBlame::focus)
12882            }
12883
12884            self.blink_manager.update(cx, BlinkManager::enable);
12885            self.show_cursor_names(cx);
12886            self.buffer.update(cx, |buffer, cx| {
12887                buffer.finalize_last_transaction(cx);
12888                if self.leader_peer_id.is_none() {
12889                    buffer.set_active_selections(
12890                        &self.selections.disjoint_anchors(),
12891                        self.selections.line_mode,
12892                        self.cursor_shape,
12893                        cx,
12894                    );
12895                }
12896            });
12897        }
12898    }
12899
12900    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12901        cx.emit(EditorEvent::FocusedIn)
12902    }
12903
12904    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12905        if event.blurred != self.focus_handle {
12906            self.last_focused_descendant = Some(event.blurred);
12907        }
12908    }
12909
12910    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12911        self.blink_manager.update(cx, BlinkManager::disable);
12912        self.buffer
12913            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12914
12915        if let Some(blame) = self.blame.as_ref() {
12916            blame.update(cx, GitBlame::blur)
12917        }
12918        if !self.hover_state.focused(cx) {
12919            hide_hover(self, cx);
12920        }
12921
12922        self.hide_context_menu(cx);
12923        cx.emit(EditorEvent::Blurred);
12924        cx.notify();
12925    }
12926
12927    pub fn register_action<A: Action>(
12928        &mut self,
12929        listener: impl Fn(&A, &mut WindowContext) + 'static,
12930    ) -> Subscription {
12931        let id = self.next_editor_action_id.post_inc();
12932        let listener = Arc::new(listener);
12933        self.editor_actions.borrow_mut().insert(
12934            id,
12935            Box::new(move |cx| {
12936                let cx = cx.window_context();
12937                let listener = listener.clone();
12938                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12939                    let action = action.downcast_ref().unwrap();
12940                    if phase == DispatchPhase::Bubble {
12941                        listener(action, cx)
12942                    }
12943                })
12944            }),
12945        );
12946
12947        let editor_actions = self.editor_actions.clone();
12948        Subscription::new(move || {
12949            editor_actions.borrow_mut().remove(&id);
12950        })
12951    }
12952
12953    pub fn file_header_size(&self) -> u32 {
12954        FILE_HEADER_HEIGHT
12955    }
12956
12957    pub fn revert(
12958        &mut self,
12959        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12960        cx: &mut ViewContext<Self>,
12961    ) {
12962        self.buffer().update(cx, |multi_buffer, cx| {
12963            for (buffer_id, changes) in revert_changes {
12964                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12965                    buffer.update(cx, |buffer, cx| {
12966                        buffer.edit(
12967                            changes.into_iter().map(|(range, text)| {
12968                                (range, text.to_string().map(Arc::<str>::from))
12969                            }),
12970                            None,
12971                            cx,
12972                        );
12973                    });
12974                }
12975            }
12976        });
12977        self.change_selections(None, cx, |selections| selections.refresh());
12978    }
12979
12980    pub fn to_pixel_point(
12981        &mut self,
12982        source: multi_buffer::Anchor,
12983        editor_snapshot: &EditorSnapshot,
12984        cx: &mut ViewContext<Self>,
12985    ) -> Option<gpui::Point<Pixels>> {
12986        let source_point = source.to_display_point(editor_snapshot);
12987        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12988    }
12989
12990    pub fn display_to_pixel_point(
12991        &self,
12992        source: DisplayPoint,
12993        editor_snapshot: &EditorSnapshot,
12994        cx: &WindowContext,
12995    ) -> Option<gpui::Point<Pixels>> {
12996        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12997        let text_layout_details = self.text_layout_details(cx);
12998        let scroll_top = text_layout_details
12999            .scroll_anchor
13000            .scroll_position(editor_snapshot)
13001            .y;
13002
13003        if source.row().as_f32() < scroll_top.floor() {
13004            return None;
13005        }
13006        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13007        let source_y = line_height * (source.row().as_f32() - scroll_top);
13008        Some(gpui::Point::new(source_x, source_y))
13009    }
13010
13011    pub fn has_active_completions_menu(&self) -> bool {
13012        self.context_menu.borrow().as_ref().map_or(false, |menu| {
13013            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13014        })
13015    }
13016
13017    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13018        self.addons
13019            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13020    }
13021
13022    pub fn unregister_addon<T: Addon>(&mut self) {
13023        self.addons.remove(&std::any::TypeId::of::<T>());
13024    }
13025
13026    pub fn addon<T: Addon>(&self) -> Option<&T> {
13027        let type_id = std::any::TypeId::of::<T>();
13028        self.addons
13029            .get(&type_id)
13030            .and_then(|item| item.to_any().downcast_ref::<T>())
13031    }
13032
13033    pub fn add_change_set(
13034        &mut self,
13035        change_set: Model<BufferChangeSet>,
13036        cx: &mut ViewContext<Self>,
13037    ) {
13038        self.diff_map.add_change_set(change_set, cx);
13039    }
13040
13041    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13042        let text_layout_details = self.text_layout_details(cx);
13043        let style = &text_layout_details.editor_style;
13044        let font_id = cx.text_system().resolve_font(&style.text.font());
13045        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13046        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13047
13048        let em_width = cx
13049            .text_system()
13050            .typographic_bounds(font_id, font_size, 'm')
13051            .unwrap()
13052            .size
13053            .width;
13054
13055        gpui::Point::new(em_width, line_height)
13056    }
13057}
13058
13059fn get_unstaged_changes_for_buffers(
13060    project: &Model<Project>,
13061    buffers: impl IntoIterator<Item = Model<Buffer>>,
13062    cx: &mut ViewContext<Editor>,
13063) {
13064    let mut tasks = Vec::new();
13065    project.update(cx, |project, cx| {
13066        for buffer in buffers {
13067            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13068        }
13069    });
13070    cx.spawn(|this, mut cx| async move {
13071        let change_sets = futures::future::join_all(tasks).await;
13072        this.update(&mut cx, |this, cx| {
13073            for change_set in change_sets {
13074                if let Some(change_set) = change_set.log_err() {
13075                    this.diff_map.add_change_set(change_set, cx);
13076                }
13077            }
13078        })
13079        .ok();
13080    })
13081    .detach();
13082}
13083
13084fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13085    let tab_size = tab_size.get() as usize;
13086    let mut width = offset;
13087
13088    for ch in text.chars() {
13089        width += if ch == '\t' {
13090            tab_size - (width % tab_size)
13091        } else {
13092            1
13093        };
13094    }
13095
13096    width - offset
13097}
13098
13099#[cfg(test)]
13100mod tests {
13101    use super::*;
13102
13103    #[test]
13104    fn test_string_size_with_expanded_tabs() {
13105        let nz = |val| NonZeroU32::new(val).unwrap();
13106        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13107        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13108        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13109        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13110        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13111        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13112        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13113        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13114    }
13115}
13116
13117/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13118struct WordBreakingTokenizer<'a> {
13119    input: &'a str,
13120}
13121
13122impl<'a> WordBreakingTokenizer<'a> {
13123    fn new(input: &'a str) -> Self {
13124        Self { input }
13125    }
13126}
13127
13128fn is_char_ideographic(ch: char) -> bool {
13129    use unicode_script::Script::*;
13130    use unicode_script::UnicodeScript;
13131    matches!(ch.script(), Han | Tangut | Yi)
13132}
13133
13134fn is_grapheme_ideographic(text: &str) -> bool {
13135    text.chars().any(is_char_ideographic)
13136}
13137
13138fn is_grapheme_whitespace(text: &str) -> bool {
13139    text.chars().any(|x| x.is_whitespace())
13140}
13141
13142fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13143    text.chars().next().map_or(false, |ch| {
13144        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13145    })
13146}
13147
13148#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13149struct WordBreakToken<'a> {
13150    token: &'a str,
13151    grapheme_len: usize,
13152    is_whitespace: bool,
13153}
13154
13155impl<'a> Iterator for WordBreakingTokenizer<'a> {
13156    /// Yields a span, the count of graphemes in the token, and whether it was
13157    /// whitespace. Note that it also breaks at word boundaries.
13158    type Item = WordBreakToken<'a>;
13159
13160    fn next(&mut self) -> Option<Self::Item> {
13161        use unicode_segmentation::UnicodeSegmentation;
13162        if self.input.is_empty() {
13163            return None;
13164        }
13165
13166        let mut iter = self.input.graphemes(true).peekable();
13167        let mut offset = 0;
13168        let mut graphemes = 0;
13169        if let Some(first_grapheme) = iter.next() {
13170            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13171            offset += first_grapheme.len();
13172            graphemes += 1;
13173            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13174                if let Some(grapheme) = iter.peek().copied() {
13175                    if should_stay_with_preceding_ideograph(grapheme) {
13176                        offset += grapheme.len();
13177                        graphemes += 1;
13178                    }
13179                }
13180            } else {
13181                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13182                let mut next_word_bound = words.peek().copied();
13183                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13184                    next_word_bound = words.next();
13185                }
13186                while let Some(grapheme) = iter.peek().copied() {
13187                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13188                        break;
13189                    };
13190                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13191                        break;
13192                    };
13193                    offset += grapheme.len();
13194                    graphemes += 1;
13195                    iter.next();
13196                }
13197            }
13198            let token = &self.input[..offset];
13199            self.input = &self.input[offset..];
13200            if is_whitespace {
13201                Some(WordBreakToken {
13202                    token: " ",
13203                    grapheme_len: 1,
13204                    is_whitespace: true,
13205                })
13206            } else {
13207                Some(WordBreakToken {
13208                    token,
13209                    grapheme_len: graphemes,
13210                    is_whitespace: false,
13211                })
13212            }
13213        } else {
13214            None
13215        }
13216    }
13217}
13218
13219#[test]
13220fn test_word_breaking_tokenizer() {
13221    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13222        ("", &[]),
13223        ("  ", &[(" ", 1, true)]),
13224        ("Ʒ", &[("Ʒ", 1, false)]),
13225        ("Ǽ", &[("Ǽ", 1, false)]),
13226        ("", &[("", 1, false)]),
13227        ("⋑⋑", &[("⋑⋑", 2, false)]),
13228        (
13229            "原理,进而",
13230            &[
13231                ("", 1, false),
13232                ("理,", 2, false),
13233                ("", 1, false),
13234                ("", 1, false),
13235            ],
13236        ),
13237        (
13238            "hello world",
13239            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13240        ),
13241        (
13242            "hello, world",
13243            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13244        ),
13245        (
13246            "  hello world",
13247            &[
13248                (" ", 1, true),
13249                ("hello", 5, false),
13250                (" ", 1, true),
13251                ("world", 5, false),
13252            ],
13253        ),
13254        (
13255            "这是什么 \n 钢笔",
13256            &[
13257                ("", 1, false),
13258                ("", 1, false),
13259                ("", 1, false),
13260                ("", 1, false),
13261                (" ", 1, true),
13262                ("", 1, false),
13263                ("", 1, false),
13264            ],
13265        ),
13266        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13267    ];
13268
13269    for (input, result) in tests {
13270        assert_eq!(
13271            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13272            result
13273                .iter()
13274                .copied()
13275                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13276                    token,
13277                    grapheme_len,
13278                    is_whitespace,
13279                })
13280                .collect::<Vec<_>>()
13281        );
13282    }
13283}
13284
13285fn wrap_with_prefix(
13286    line_prefix: String,
13287    unwrapped_text: String,
13288    wrap_column: usize,
13289    tab_size: NonZeroU32,
13290) -> String {
13291    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13292    let mut wrapped_text = String::new();
13293    let mut current_line = line_prefix.clone();
13294
13295    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13296    let mut current_line_len = line_prefix_len;
13297    for WordBreakToken {
13298        token,
13299        grapheme_len,
13300        is_whitespace,
13301    } in tokenizer
13302    {
13303        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13304            wrapped_text.push_str(current_line.trim_end());
13305            wrapped_text.push('\n');
13306            current_line.truncate(line_prefix.len());
13307            current_line_len = line_prefix_len;
13308            if !is_whitespace {
13309                current_line.push_str(token);
13310                current_line_len += grapheme_len;
13311            }
13312        } else if !is_whitespace {
13313            current_line.push_str(token);
13314            current_line_len += grapheme_len;
13315        } else if current_line_len != line_prefix_len {
13316            current_line.push(' ');
13317            current_line_len += 1;
13318        }
13319    }
13320
13321    if !current_line.is_empty() {
13322        wrapped_text.push_str(&current_line);
13323    }
13324    wrapped_text
13325}
13326
13327#[test]
13328fn test_wrap_with_prefix() {
13329    assert_eq!(
13330        wrap_with_prefix(
13331            "# ".to_string(),
13332            "abcdefg".to_string(),
13333            4,
13334            NonZeroU32::new(4).unwrap()
13335        ),
13336        "# abcdefg"
13337    );
13338    assert_eq!(
13339        wrap_with_prefix(
13340            "".to_string(),
13341            "\thello world".to_string(),
13342            8,
13343            NonZeroU32::new(4).unwrap()
13344        ),
13345        "hello\nworld"
13346    );
13347    assert_eq!(
13348        wrap_with_prefix(
13349            "// ".to_string(),
13350            "xx \nyy zz aa bb cc".to_string(),
13351            12,
13352            NonZeroU32::new(4).unwrap()
13353        ),
13354        "// xx yy zz\n// aa bb cc"
13355    );
13356    assert_eq!(
13357        wrap_with_prefix(
13358            String::new(),
13359            "这是什么 \n 钢笔".to_string(),
13360            3,
13361            NonZeroU32::new(4).unwrap()
13362        ),
13363        "这是什\n么 钢\n"
13364    );
13365}
13366
13367fn hunks_for_selections(
13368    snapshot: &EditorSnapshot,
13369    selections: &[Selection<Point>],
13370) -> Vec<MultiBufferDiffHunk> {
13371    hunks_for_ranges(
13372        selections.iter().map(|selection| selection.range()),
13373        snapshot,
13374    )
13375}
13376
13377pub fn hunks_for_ranges(
13378    ranges: impl Iterator<Item = Range<Point>>,
13379    snapshot: &EditorSnapshot,
13380) -> Vec<MultiBufferDiffHunk> {
13381    let mut hunks = Vec::new();
13382    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13383        HashMap::default();
13384    for query_range in ranges {
13385        let query_rows =
13386            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13387        for hunk in snapshot.diff_map.diff_hunks_in_range(
13388            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13389            &snapshot.buffer_snapshot,
13390        ) {
13391            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13392            // when the caret is just above or just below the deleted hunk.
13393            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13394            let related_to_selection = if allow_adjacent {
13395                hunk.row_range.overlaps(&query_rows)
13396                    || hunk.row_range.start == query_rows.end
13397                    || hunk.row_range.end == query_rows.start
13398            } else {
13399                hunk.row_range.overlaps(&query_rows)
13400            };
13401            if related_to_selection {
13402                if !processed_buffer_rows
13403                    .entry(hunk.buffer_id)
13404                    .or_default()
13405                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13406                {
13407                    continue;
13408                }
13409                hunks.push(hunk);
13410            }
13411        }
13412    }
13413
13414    hunks
13415}
13416
13417pub trait CollaborationHub {
13418    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13419    fn user_participant_indices<'a>(
13420        &self,
13421        cx: &'a AppContext,
13422    ) -> &'a HashMap<u64, ParticipantIndex>;
13423    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13424}
13425
13426impl CollaborationHub for Model<Project> {
13427    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13428        self.read(cx).collaborators()
13429    }
13430
13431    fn user_participant_indices<'a>(
13432        &self,
13433        cx: &'a AppContext,
13434    ) -> &'a HashMap<u64, ParticipantIndex> {
13435        self.read(cx).user_store().read(cx).participant_indices()
13436    }
13437
13438    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13439        let this = self.read(cx);
13440        let user_ids = this.collaborators().values().map(|c| c.user_id);
13441        this.user_store().read_with(cx, |user_store, cx| {
13442            user_store.participant_names(user_ids, cx)
13443        })
13444    }
13445}
13446
13447pub trait SemanticsProvider {
13448    fn hover(
13449        &self,
13450        buffer: &Model<Buffer>,
13451        position: text::Anchor,
13452        cx: &mut AppContext,
13453    ) -> Option<Task<Vec<project::Hover>>>;
13454
13455    fn inlay_hints(
13456        &self,
13457        buffer_handle: Model<Buffer>,
13458        range: Range<text::Anchor>,
13459        cx: &mut AppContext,
13460    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13461
13462    fn resolve_inlay_hint(
13463        &self,
13464        hint: InlayHint,
13465        buffer_handle: Model<Buffer>,
13466        server_id: LanguageServerId,
13467        cx: &mut AppContext,
13468    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13469
13470    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13471
13472    fn document_highlights(
13473        &self,
13474        buffer: &Model<Buffer>,
13475        position: text::Anchor,
13476        cx: &mut AppContext,
13477    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13478
13479    fn definitions(
13480        &self,
13481        buffer: &Model<Buffer>,
13482        position: text::Anchor,
13483        kind: GotoDefinitionKind,
13484        cx: &mut AppContext,
13485    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13486
13487    fn range_for_rename(
13488        &self,
13489        buffer: &Model<Buffer>,
13490        position: text::Anchor,
13491        cx: &mut AppContext,
13492    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13493
13494    fn perform_rename(
13495        &self,
13496        buffer: &Model<Buffer>,
13497        position: text::Anchor,
13498        new_name: String,
13499        cx: &mut AppContext,
13500    ) -> Option<Task<Result<ProjectTransaction>>>;
13501}
13502
13503pub trait CompletionProvider {
13504    fn completions(
13505        &self,
13506        buffer: &Model<Buffer>,
13507        buffer_position: text::Anchor,
13508        trigger: CompletionContext,
13509        cx: &mut ViewContext<Editor>,
13510    ) -> Task<Result<Vec<Completion>>>;
13511
13512    fn resolve_completions(
13513        &self,
13514        buffer: Model<Buffer>,
13515        completion_indices: Vec<usize>,
13516        completions: Rc<RefCell<Box<[Completion]>>>,
13517        cx: &mut ViewContext<Editor>,
13518    ) -> Task<Result<bool>>;
13519
13520    fn apply_additional_edits_for_completion(
13521        &self,
13522        _buffer: Model<Buffer>,
13523        _completions: Rc<RefCell<Box<[Completion]>>>,
13524        _completion_index: usize,
13525        _push_to_history: bool,
13526        _cx: &mut ViewContext<Editor>,
13527    ) -> Task<Result<Option<language::Transaction>>> {
13528        Task::ready(Ok(None))
13529    }
13530
13531    fn is_completion_trigger(
13532        &self,
13533        buffer: &Model<Buffer>,
13534        position: language::Anchor,
13535        text: &str,
13536        trigger_in_words: bool,
13537        cx: &mut ViewContext<Editor>,
13538    ) -> bool;
13539
13540    fn sort_completions(&self) -> bool {
13541        true
13542    }
13543}
13544
13545pub trait CodeActionProvider {
13546    fn id(&self) -> Arc<str>;
13547
13548    fn code_actions(
13549        &self,
13550        buffer: &Model<Buffer>,
13551        range: Range<text::Anchor>,
13552        cx: &mut WindowContext,
13553    ) -> Task<Result<Vec<CodeAction>>>;
13554
13555    fn apply_code_action(
13556        &self,
13557        buffer_handle: Model<Buffer>,
13558        action: CodeAction,
13559        excerpt_id: ExcerptId,
13560        push_to_history: bool,
13561        cx: &mut WindowContext,
13562    ) -> Task<Result<ProjectTransaction>>;
13563}
13564
13565impl CodeActionProvider for Model<Project> {
13566    fn id(&self) -> Arc<str> {
13567        "project".into()
13568    }
13569
13570    fn code_actions(
13571        &self,
13572        buffer: &Model<Buffer>,
13573        range: Range<text::Anchor>,
13574        cx: &mut WindowContext,
13575    ) -> Task<Result<Vec<CodeAction>>> {
13576        self.update(cx, |project, cx| {
13577            project.code_actions(buffer, range, None, cx)
13578        })
13579    }
13580
13581    fn apply_code_action(
13582        &self,
13583        buffer_handle: Model<Buffer>,
13584        action: CodeAction,
13585        _excerpt_id: ExcerptId,
13586        push_to_history: bool,
13587        cx: &mut WindowContext,
13588    ) -> Task<Result<ProjectTransaction>> {
13589        self.update(cx, |project, cx| {
13590            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13591        })
13592    }
13593}
13594
13595fn snippet_completions(
13596    project: &Project,
13597    buffer: &Model<Buffer>,
13598    buffer_position: text::Anchor,
13599    cx: &mut AppContext,
13600) -> Task<Result<Vec<Completion>>> {
13601    let language = buffer.read(cx).language_at(buffer_position);
13602    let language_name = language.as_ref().map(|language| language.lsp_id());
13603    let snippet_store = project.snippets().read(cx);
13604    let snippets = snippet_store.snippets_for(language_name, cx);
13605
13606    if snippets.is_empty() {
13607        return Task::ready(Ok(vec![]));
13608    }
13609    let snapshot = buffer.read(cx).text_snapshot();
13610    let chars: String = snapshot
13611        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13612        .collect();
13613
13614    let scope = language.map(|language| language.default_scope());
13615    let executor = cx.background_executor().clone();
13616
13617    cx.background_executor().spawn(async move {
13618        let classifier = CharClassifier::new(scope).for_completion(true);
13619        let mut last_word = chars
13620            .chars()
13621            .take_while(|c| classifier.is_word(*c))
13622            .collect::<String>();
13623        last_word = last_word.chars().rev().collect();
13624
13625        if last_word.is_empty() {
13626            return Ok(vec![]);
13627        }
13628
13629        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13630        let to_lsp = |point: &text::Anchor| {
13631            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13632            point_to_lsp(end)
13633        };
13634        let lsp_end = to_lsp(&buffer_position);
13635
13636        let candidates = snippets
13637            .iter()
13638            .enumerate()
13639            .flat_map(|(ix, snippet)| {
13640                snippet
13641                    .prefix
13642                    .iter()
13643                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13644            })
13645            .collect::<Vec<StringMatchCandidate>>();
13646
13647        let mut matches = fuzzy::match_strings(
13648            &candidates,
13649            &last_word,
13650            last_word.chars().any(|c| c.is_uppercase()),
13651            100,
13652            &Default::default(),
13653            executor,
13654        )
13655        .await;
13656
13657        // Remove all candidates where the query's start does not match the start of any word in the candidate
13658        if let Some(query_start) = last_word.chars().next() {
13659            matches.retain(|string_match| {
13660                split_words(&string_match.string).any(|word| {
13661                    // Check that the first codepoint of the word as lowercase matches the first
13662                    // codepoint of the query as lowercase
13663                    word.chars()
13664                        .flat_map(|codepoint| codepoint.to_lowercase())
13665                        .zip(query_start.to_lowercase())
13666                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13667                })
13668            });
13669        }
13670
13671        let matched_strings = matches
13672            .into_iter()
13673            .map(|m| m.string)
13674            .collect::<HashSet<_>>();
13675
13676        let result: Vec<Completion> = snippets
13677            .into_iter()
13678            .filter_map(|snippet| {
13679                let matching_prefix = snippet
13680                    .prefix
13681                    .iter()
13682                    .find(|prefix| matched_strings.contains(*prefix))?;
13683                let start = as_offset - last_word.len();
13684                let start = snapshot.anchor_before(start);
13685                let range = start..buffer_position;
13686                let lsp_start = to_lsp(&start);
13687                let lsp_range = lsp::Range {
13688                    start: lsp_start,
13689                    end: lsp_end,
13690                };
13691                Some(Completion {
13692                    old_range: range,
13693                    new_text: snippet.body.clone(),
13694                    resolved: false,
13695                    label: CodeLabel {
13696                        text: matching_prefix.clone(),
13697                        runs: vec![],
13698                        filter_range: 0..matching_prefix.len(),
13699                    },
13700                    server_id: LanguageServerId(usize::MAX),
13701                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13702                    lsp_completion: lsp::CompletionItem {
13703                        label: snippet.prefix.first().unwrap().clone(),
13704                        kind: Some(CompletionItemKind::SNIPPET),
13705                        label_details: snippet.description.as_ref().map(|description| {
13706                            lsp::CompletionItemLabelDetails {
13707                                detail: Some(description.clone()),
13708                                description: None,
13709                            }
13710                        }),
13711                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13712                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13713                            lsp::InsertReplaceEdit {
13714                                new_text: snippet.body.clone(),
13715                                insert: lsp_range,
13716                                replace: lsp_range,
13717                            },
13718                        )),
13719                        filter_text: Some(snippet.body.clone()),
13720                        sort_text: Some(char::MAX.to_string()),
13721                        ..Default::default()
13722                    },
13723                    confirm: None,
13724                })
13725            })
13726            .collect();
13727
13728        Ok(result)
13729    })
13730}
13731
13732impl CompletionProvider for Model<Project> {
13733    fn completions(
13734        &self,
13735        buffer: &Model<Buffer>,
13736        buffer_position: text::Anchor,
13737        options: CompletionContext,
13738        cx: &mut ViewContext<Editor>,
13739    ) -> Task<Result<Vec<Completion>>> {
13740        self.update(cx, |project, cx| {
13741            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13742            let project_completions = project.completions(buffer, buffer_position, options, cx);
13743            cx.background_executor().spawn(async move {
13744                let mut completions = project_completions.await?;
13745                let snippets_completions = snippets.await?;
13746                completions.extend(snippets_completions);
13747                Ok(completions)
13748            })
13749        })
13750    }
13751
13752    fn resolve_completions(
13753        &self,
13754        buffer: Model<Buffer>,
13755        completion_indices: Vec<usize>,
13756        completions: Rc<RefCell<Box<[Completion]>>>,
13757        cx: &mut ViewContext<Editor>,
13758    ) -> Task<Result<bool>> {
13759        self.update(cx, |project, cx| {
13760            project.lsp_store().update(cx, |lsp_store, cx| {
13761                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13762            })
13763        })
13764    }
13765
13766    fn apply_additional_edits_for_completion(
13767        &self,
13768        buffer: Model<Buffer>,
13769        completions: Rc<RefCell<Box<[Completion]>>>,
13770        completion_index: usize,
13771        push_to_history: bool,
13772        cx: &mut ViewContext<Editor>,
13773    ) -> Task<Result<Option<language::Transaction>>> {
13774        self.update(cx, |project, cx| {
13775            project.lsp_store().update(cx, |lsp_store, cx| {
13776                lsp_store.apply_additional_edits_for_completion(
13777                    buffer,
13778                    completions,
13779                    completion_index,
13780                    push_to_history,
13781                    cx,
13782                )
13783            })
13784        })
13785    }
13786
13787    fn is_completion_trigger(
13788        &self,
13789        buffer: &Model<Buffer>,
13790        position: language::Anchor,
13791        text: &str,
13792        trigger_in_words: bool,
13793        cx: &mut ViewContext<Editor>,
13794    ) -> bool {
13795        let mut chars = text.chars();
13796        let char = if let Some(char) = chars.next() {
13797            char
13798        } else {
13799            return false;
13800        };
13801        if chars.next().is_some() {
13802            return false;
13803        }
13804
13805        let buffer = buffer.read(cx);
13806        let snapshot = buffer.snapshot();
13807        if !snapshot.settings_at(position, cx).show_completions_on_input {
13808            return false;
13809        }
13810        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13811        if trigger_in_words && classifier.is_word(char) {
13812            return true;
13813        }
13814
13815        buffer.completion_triggers().contains(text)
13816    }
13817}
13818
13819impl SemanticsProvider for Model<Project> {
13820    fn hover(
13821        &self,
13822        buffer: &Model<Buffer>,
13823        position: text::Anchor,
13824        cx: &mut AppContext,
13825    ) -> Option<Task<Vec<project::Hover>>> {
13826        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13827    }
13828
13829    fn document_highlights(
13830        &self,
13831        buffer: &Model<Buffer>,
13832        position: text::Anchor,
13833        cx: &mut AppContext,
13834    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13835        Some(self.update(cx, |project, cx| {
13836            project.document_highlights(buffer, position, cx)
13837        }))
13838    }
13839
13840    fn definitions(
13841        &self,
13842        buffer: &Model<Buffer>,
13843        position: text::Anchor,
13844        kind: GotoDefinitionKind,
13845        cx: &mut AppContext,
13846    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13847        Some(self.update(cx, |project, cx| match kind {
13848            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13849            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13850            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13851            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13852        }))
13853    }
13854
13855    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13856        // TODO: make this work for remote projects
13857        self.read(cx)
13858            .language_servers_for_local_buffer(buffer.read(cx), cx)
13859            .any(
13860                |(_, server)| match server.capabilities().inlay_hint_provider {
13861                    Some(lsp::OneOf::Left(enabled)) => enabled,
13862                    Some(lsp::OneOf::Right(_)) => true,
13863                    None => false,
13864                },
13865            )
13866    }
13867
13868    fn inlay_hints(
13869        &self,
13870        buffer_handle: Model<Buffer>,
13871        range: Range<text::Anchor>,
13872        cx: &mut AppContext,
13873    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13874        Some(self.update(cx, |project, cx| {
13875            project.inlay_hints(buffer_handle, range, cx)
13876        }))
13877    }
13878
13879    fn resolve_inlay_hint(
13880        &self,
13881        hint: InlayHint,
13882        buffer_handle: Model<Buffer>,
13883        server_id: LanguageServerId,
13884        cx: &mut AppContext,
13885    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13886        Some(self.update(cx, |project, cx| {
13887            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13888        }))
13889    }
13890
13891    fn range_for_rename(
13892        &self,
13893        buffer: &Model<Buffer>,
13894        position: text::Anchor,
13895        cx: &mut AppContext,
13896    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13897        Some(self.update(cx, |project, cx| {
13898            project.prepare_rename(buffer.clone(), position, cx)
13899        }))
13900    }
13901
13902    fn perform_rename(
13903        &self,
13904        buffer: &Model<Buffer>,
13905        position: text::Anchor,
13906        new_name: String,
13907        cx: &mut AppContext,
13908    ) -> Option<Task<Result<ProjectTransaction>>> {
13909        Some(self.update(cx, |project, cx| {
13910            project.perform_rename(buffer.clone(), position, new_name, cx)
13911        }))
13912    }
13913}
13914
13915fn inlay_hint_settings(
13916    location: Anchor,
13917    snapshot: &MultiBufferSnapshot,
13918    cx: &mut ViewContext<Editor>,
13919) -> InlayHintSettings {
13920    let file = snapshot.file_at(location);
13921    let language = snapshot.language_at(location).map(|l| l.name());
13922    language_settings(language, file, cx).inlay_hints
13923}
13924
13925fn consume_contiguous_rows(
13926    contiguous_row_selections: &mut Vec<Selection<Point>>,
13927    selection: &Selection<Point>,
13928    display_map: &DisplaySnapshot,
13929    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13930) -> (MultiBufferRow, MultiBufferRow) {
13931    contiguous_row_selections.push(selection.clone());
13932    let start_row = MultiBufferRow(selection.start.row);
13933    let mut end_row = ending_row(selection, display_map);
13934
13935    while let Some(next_selection) = selections.peek() {
13936        if next_selection.start.row <= end_row.0 {
13937            end_row = ending_row(next_selection, display_map);
13938            contiguous_row_selections.push(selections.next().unwrap().clone());
13939        } else {
13940            break;
13941        }
13942    }
13943    (start_row, end_row)
13944}
13945
13946fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13947    if next_selection.end.column > 0 || next_selection.is_empty() {
13948        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13949    } else {
13950        MultiBufferRow(next_selection.end.row)
13951    }
13952}
13953
13954impl EditorSnapshot {
13955    pub fn remote_selections_in_range<'a>(
13956        &'a self,
13957        range: &'a Range<Anchor>,
13958        collaboration_hub: &dyn CollaborationHub,
13959        cx: &'a AppContext,
13960    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13961        let participant_names = collaboration_hub.user_names(cx);
13962        let participant_indices = collaboration_hub.user_participant_indices(cx);
13963        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13964        let collaborators_by_replica_id = collaborators_by_peer_id
13965            .iter()
13966            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13967            .collect::<HashMap<_, _>>();
13968        self.buffer_snapshot
13969            .selections_in_range(range, false)
13970            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13971                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13972                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13973                let user_name = participant_names.get(&collaborator.user_id).cloned();
13974                Some(RemoteSelection {
13975                    replica_id,
13976                    selection,
13977                    cursor_shape,
13978                    line_mode,
13979                    participant_index,
13980                    peer_id: collaborator.peer_id,
13981                    user_name,
13982                })
13983            })
13984    }
13985
13986    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13987        self.display_snapshot.buffer_snapshot.language_at(position)
13988    }
13989
13990    pub fn is_focused(&self) -> bool {
13991        self.is_focused
13992    }
13993
13994    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13995        self.placeholder_text.as_ref()
13996    }
13997
13998    pub fn scroll_position(&self) -> gpui::Point<f32> {
13999        self.scroll_anchor.scroll_position(&self.display_snapshot)
14000    }
14001
14002    fn gutter_dimensions(
14003        &self,
14004        font_id: FontId,
14005        font_size: Pixels,
14006        em_width: Pixels,
14007        em_advance: Pixels,
14008        max_line_number_width: Pixels,
14009        cx: &AppContext,
14010    ) -> GutterDimensions {
14011        if !self.show_gutter {
14012            return GutterDimensions::default();
14013        }
14014        let descent = cx.text_system().descent(font_id, font_size);
14015
14016        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14017            matches!(
14018                ProjectSettings::get_global(cx).git.git_gutter,
14019                Some(GitGutterSetting::TrackedFiles)
14020            )
14021        });
14022        let gutter_settings = EditorSettings::get_global(cx).gutter;
14023        let show_line_numbers = self
14024            .show_line_numbers
14025            .unwrap_or(gutter_settings.line_numbers);
14026        let line_gutter_width = if show_line_numbers {
14027            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14028            let min_width_for_number_on_gutter = em_advance * 4.0;
14029            max_line_number_width.max(min_width_for_number_on_gutter)
14030        } else {
14031            0.0.into()
14032        };
14033
14034        let show_code_actions = self
14035            .show_code_actions
14036            .unwrap_or(gutter_settings.code_actions);
14037
14038        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14039
14040        let git_blame_entries_width =
14041            self.git_blame_gutter_max_author_length
14042                .map(|max_author_length| {
14043                    // Length of the author name, but also space for the commit hash,
14044                    // the spacing and the timestamp.
14045                    let max_char_count = max_author_length
14046                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14047                        + 7 // length of commit sha
14048                        + 14 // length of max relative timestamp ("60 minutes ago")
14049                        + 4; // gaps and margins
14050
14051                    em_advance * max_char_count
14052                });
14053
14054        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14055        left_padding += if show_code_actions || show_runnables {
14056            em_width * 3.0
14057        } else if show_git_gutter && show_line_numbers {
14058            em_width * 2.0
14059        } else if show_git_gutter || show_line_numbers {
14060            em_width
14061        } else {
14062            px(0.)
14063        };
14064
14065        let right_padding = if gutter_settings.folds && show_line_numbers {
14066            em_width * 4.0
14067        } else if gutter_settings.folds {
14068            em_width * 3.0
14069        } else if show_line_numbers {
14070            em_width
14071        } else {
14072            px(0.)
14073        };
14074
14075        GutterDimensions {
14076            left_padding,
14077            right_padding,
14078            width: line_gutter_width + left_padding + right_padding,
14079            margin: -descent,
14080            git_blame_entries_width,
14081        }
14082    }
14083
14084    pub fn render_crease_toggle(
14085        &self,
14086        buffer_row: MultiBufferRow,
14087        row_contains_cursor: bool,
14088        editor: View<Editor>,
14089        cx: &mut WindowContext,
14090    ) -> Option<AnyElement> {
14091        let folded = self.is_line_folded(buffer_row);
14092        let mut is_foldable = false;
14093
14094        if let Some(crease) = self
14095            .crease_snapshot
14096            .query_row(buffer_row, &self.buffer_snapshot)
14097        {
14098            is_foldable = true;
14099            match crease {
14100                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14101                    if let Some(render_toggle) = render_toggle {
14102                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14103                            if folded {
14104                                editor.update(cx, |editor, cx| {
14105                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14106                                });
14107                            } else {
14108                                editor.update(cx, |editor, cx| {
14109                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14110                                });
14111                            }
14112                        });
14113                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14114                    }
14115                }
14116            }
14117        }
14118
14119        is_foldable |= self.starts_indent(buffer_row);
14120
14121        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14122            Some(
14123                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14124                    .toggle_state(folded)
14125                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14126                        if folded {
14127                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14128                        } else {
14129                            this.fold_at(&FoldAt { buffer_row }, cx);
14130                        }
14131                    }))
14132                    .into_any_element(),
14133            )
14134        } else {
14135            None
14136        }
14137    }
14138
14139    pub fn render_crease_trailer(
14140        &self,
14141        buffer_row: MultiBufferRow,
14142        cx: &mut WindowContext,
14143    ) -> Option<AnyElement> {
14144        let folded = self.is_line_folded(buffer_row);
14145        if let Crease::Inline { render_trailer, .. } = self
14146            .crease_snapshot
14147            .query_row(buffer_row, &self.buffer_snapshot)?
14148        {
14149            let render_trailer = render_trailer.as_ref()?;
14150            Some(render_trailer(buffer_row, folded, cx))
14151        } else {
14152            None
14153        }
14154    }
14155}
14156
14157impl Deref for EditorSnapshot {
14158    type Target = DisplaySnapshot;
14159
14160    fn deref(&self) -> &Self::Target {
14161        &self.display_snapshot
14162    }
14163}
14164
14165#[derive(Clone, Debug, PartialEq, Eq)]
14166pub enum EditorEvent {
14167    InputIgnored {
14168        text: Arc<str>,
14169    },
14170    InputHandled {
14171        utf16_range_to_replace: Option<Range<isize>>,
14172        text: Arc<str>,
14173    },
14174    ExcerptsAdded {
14175        buffer: Model<Buffer>,
14176        predecessor: ExcerptId,
14177        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14178    },
14179    ExcerptsRemoved {
14180        ids: Vec<ExcerptId>,
14181    },
14182    BufferFoldToggled {
14183        ids: Vec<ExcerptId>,
14184        folded: bool,
14185    },
14186    ExcerptsEdited {
14187        ids: Vec<ExcerptId>,
14188    },
14189    ExcerptsExpanded {
14190        ids: Vec<ExcerptId>,
14191    },
14192    BufferEdited,
14193    Edited {
14194        transaction_id: clock::Lamport,
14195    },
14196    Reparsed(BufferId),
14197    Focused,
14198    FocusedIn,
14199    Blurred,
14200    DirtyChanged,
14201    Saved,
14202    TitleChanged,
14203    DiffBaseChanged,
14204    SelectionsChanged {
14205        local: bool,
14206    },
14207    ScrollPositionChanged {
14208        local: bool,
14209        autoscroll: bool,
14210    },
14211    Closed,
14212    TransactionUndone {
14213        transaction_id: clock::Lamport,
14214    },
14215    TransactionBegun {
14216        transaction_id: clock::Lamport,
14217    },
14218    Reloaded,
14219    CursorShapeChanged,
14220}
14221
14222impl EventEmitter<EditorEvent> for Editor {}
14223
14224impl FocusableView for Editor {
14225    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14226        self.focus_handle.clone()
14227    }
14228}
14229
14230impl Render for Editor {
14231    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14232        let settings = ThemeSettings::get_global(cx);
14233
14234        let mut text_style = match self.mode {
14235            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14236                color: cx.theme().colors().editor_foreground,
14237                font_family: settings.ui_font.family.clone(),
14238                font_features: settings.ui_font.features.clone(),
14239                font_fallbacks: settings.ui_font.fallbacks.clone(),
14240                font_size: rems(0.875).into(),
14241                font_weight: settings.ui_font.weight,
14242                line_height: relative(settings.buffer_line_height.value()),
14243                ..Default::default()
14244            },
14245            EditorMode::Full => TextStyle {
14246                color: cx.theme().colors().editor_foreground,
14247                font_family: settings.buffer_font.family.clone(),
14248                font_features: settings.buffer_font.features.clone(),
14249                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14250                font_size: settings.buffer_font_size(cx).into(),
14251                font_weight: settings.buffer_font.weight,
14252                line_height: relative(settings.buffer_line_height.value()),
14253                ..Default::default()
14254            },
14255        };
14256        if let Some(text_style_refinement) = &self.text_style_refinement {
14257            text_style.refine(text_style_refinement)
14258        }
14259
14260        let background = match self.mode {
14261            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14262            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14263            EditorMode::Full => cx.theme().colors().editor_background,
14264        };
14265
14266        EditorElement::new(
14267            cx.view(),
14268            EditorStyle {
14269                background,
14270                local_player: cx.theme().players().local(),
14271                text: text_style,
14272                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14273                syntax: cx.theme().syntax().clone(),
14274                status: cx.theme().status().clone(),
14275                inlay_hints_style: make_inlay_hints_style(cx),
14276                inline_completion_styles: make_suggestion_styles(cx),
14277                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14278            },
14279        )
14280    }
14281}
14282
14283impl ViewInputHandler for Editor {
14284    fn text_for_range(
14285        &mut self,
14286        range_utf16: Range<usize>,
14287        adjusted_range: &mut Option<Range<usize>>,
14288        cx: &mut ViewContext<Self>,
14289    ) -> Option<String> {
14290        let snapshot = self.buffer.read(cx).read(cx);
14291        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14292        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14293        if (start.0..end.0) != range_utf16 {
14294            adjusted_range.replace(start.0..end.0);
14295        }
14296        Some(snapshot.text_for_range(start..end).collect())
14297    }
14298
14299    fn selected_text_range(
14300        &mut self,
14301        ignore_disabled_input: bool,
14302        cx: &mut ViewContext<Self>,
14303    ) -> Option<UTF16Selection> {
14304        // Prevent the IME menu from appearing when holding down an alphabetic key
14305        // while input is disabled.
14306        if !ignore_disabled_input && !self.input_enabled {
14307            return None;
14308        }
14309
14310        let selection = self.selections.newest::<OffsetUtf16>(cx);
14311        let range = selection.range();
14312
14313        Some(UTF16Selection {
14314            range: range.start.0..range.end.0,
14315            reversed: selection.reversed,
14316        })
14317    }
14318
14319    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14320        let snapshot = self.buffer.read(cx).read(cx);
14321        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14322        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14323    }
14324
14325    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14326        self.clear_highlights::<InputComposition>(cx);
14327        self.ime_transaction.take();
14328    }
14329
14330    fn replace_text_in_range(
14331        &mut self,
14332        range_utf16: Option<Range<usize>>,
14333        text: &str,
14334        cx: &mut ViewContext<Self>,
14335    ) {
14336        if !self.input_enabled {
14337            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14338            return;
14339        }
14340
14341        self.transact(cx, |this, cx| {
14342            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14343                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14344                Some(this.selection_replacement_ranges(range_utf16, cx))
14345            } else {
14346                this.marked_text_ranges(cx)
14347            };
14348
14349            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14350                let newest_selection_id = this.selections.newest_anchor().id;
14351                this.selections
14352                    .all::<OffsetUtf16>(cx)
14353                    .iter()
14354                    .zip(ranges_to_replace.iter())
14355                    .find_map(|(selection, range)| {
14356                        if selection.id == newest_selection_id {
14357                            Some(
14358                                (range.start.0 as isize - selection.head().0 as isize)
14359                                    ..(range.end.0 as isize - selection.head().0 as isize),
14360                            )
14361                        } else {
14362                            None
14363                        }
14364                    })
14365            });
14366
14367            cx.emit(EditorEvent::InputHandled {
14368                utf16_range_to_replace: range_to_replace,
14369                text: text.into(),
14370            });
14371
14372            if let Some(new_selected_ranges) = new_selected_ranges {
14373                this.change_selections(None, cx, |selections| {
14374                    selections.select_ranges(new_selected_ranges)
14375                });
14376                this.backspace(&Default::default(), cx);
14377            }
14378
14379            this.handle_input(text, cx);
14380        });
14381
14382        if let Some(transaction) = self.ime_transaction {
14383            self.buffer.update(cx, |buffer, cx| {
14384                buffer.group_until_transaction(transaction, cx);
14385            });
14386        }
14387
14388        self.unmark_text(cx);
14389    }
14390
14391    fn replace_and_mark_text_in_range(
14392        &mut self,
14393        range_utf16: Option<Range<usize>>,
14394        text: &str,
14395        new_selected_range_utf16: Option<Range<usize>>,
14396        cx: &mut ViewContext<Self>,
14397    ) {
14398        if !self.input_enabled {
14399            return;
14400        }
14401
14402        let transaction = self.transact(cx, |this, cx| {
14403            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14404                let snapshot = this.buffer.read(cx).read(cx);
14405                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14406                    for marked_range in &mut marked_ranges {
14407                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14408                        marked_range.start.0 += relative_range_utf16.start;
14409                        marked_range.start =
14410                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14411                        marked_range.end =
14412                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14413                    }
14414                }
14415                Some(marked_ranges)
14416            } else if let Some(range_utf16) = range_utf16 {
14417                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14418                Some(this.selection_replacement_ranges(range_utf16, cx))
14419            } else {
14420                None
14421            };
14422
14423            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14424                let newest_selection_id = this.selections.newest_anchor().id;
14425                this.selections
14426                    .all::<OffsetUtf16>(cx)
14427                    .iter()
14428                    .zip(ranges_to_replace.iter())
14429                    .find_map(|(selection, range)| {
14430                        if selection.id == newest_selection_id {
14431                            Some(
14432                                (range.start.0 as isize - selection.head().0 as isize)
14433                                    ..(range.end.0 as isize - selection.head().0 as isize),
14434                            )
14435                        } else {
14436                            None
14437                        }
14438                    })
14439            });
14440
14441            cx.emit(EditorEvent::InputHandled {
14442                utf16_range_to_replace: range_to_replace,
14443                text: text.into(),
14444            });
14445
14446            if let Some(ranges) = ranges_to_replace {
14447                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14448            }
14449
14450            let marked_ranges = {
14451                let snapshot = this.buffer.read(cx).read(cx);
14452                this.selections
14453                    .disjoint_anchors()
14454                    .iter()
14455                    .map(|selection| {
14456                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14457                    })
14458                    .collect::<Vec<_>>()
14459            };
14460
14461            if text.is_empty() {
14462                this.unmark_text(cx);
14463            } else {
14464                this.highlight_text::<InputComposition>(
14465                    marked_ranges.clone(),
14466                    HighlightStyle {
14467                        underline: Some(UnderlineStyle {
14468                            thickness: px(1.),
14469                            color: None,
14470                            wavy: false,
14471                        }),
14472                        ..Default::default()
14473                    },
14474                    cx,
14475                );
14476            }
14477
14478            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14479            let use_autoclose = this.use_autoclose;
14480            let use_auto_surround = this.use_auto_surround;
14481            this.set_use_autoclose(false);
14482            this.set_use_auto_surround(false);
14483            this.handle_input(text, cx);
14484            this.set_use_autoclose(use_autoclose);
14485            this.set_use_auto_surround(use_auto_surround);
14486
14487            if let Some(new_selected_range) = new_selected_range_utf16 {
14488                let snapshot = this.buffer.read(cx).read(cx);
14489                let new_selected_ranges = marked_ranges
14490                    .into_iter()
14491                    .map(|marked_range| {
14492                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14493                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14494                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14495                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14496                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14497                    })
14498                    .collect::<Vec<_>>();
14499
14500                drop(snapshot);
14501                this.change_selections(None, cx, |selections| {
14502                    selections.select_ranges(new_selected_ranges)
14503                });
14504            }
14505        });
14506
14507        self.ime_transaction = self.ime_transaction.or(transaction);
14508        if let Some(transaction) = self.ime_transaction {
14509            self.buffer.update(cx, |buffer, cx| {
14510                buffer.group_until_transaction(transaction, cx);
14511            });
14512        }
14513
14514        if self.text_highlights::<InputComposition>(cx).is_none() {
14515            self.ime_transaction.take();
14516        }
14517    }
14518
14519    fn bounds_for_range(
14520        &mut self,
14521        range_utf16: Range<usize>,
14522        element_bounds: gpui::Bounds<Pixels>,
14523        cx: &mut ViewContext<Self>,
14524    ) -> Option<gpui::Bounds<Pixels>> {
14525        let text_layout_details = self.text_layout_details(cx);
14526        let gpui::Point {
14527            x: em_width,
14528            y: line_height,
14529        } = self.character_size(cx);
14530
14531        let snapshot = self.snapshot(cx);
14532        let scroll_position = snapshot.scroll_position();
14533        let scroll_left = scroll_position.x * em_width;
14534
14535        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14536        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14537            + self.gutter_dimensions.width
14538            + self.gutter_dimensions.margin;
14539        let y = line_height * (start.row().as_f32() - scroll_position.y);
14540
14541        Some(Bounds {
14542            origin: element_bounds.origin + point(x, y),
14543            size: size(em_width, line_height),
14544        })
14545    }
14546}
14547
14548trait SelectionExt {
14549    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14550    fn spanned_rows(
14551        &self,
14552        include_end_if_at_line_start: bool,
14553        map: &DisplaySnapshot,
14554    ) -> Range<MultiBufferRow>;
14555}
14556
14557impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14558    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14559        let start = self
14560            .start
14561            .to_point(&map.buffer_snapshot)
14562            .to_display_point(map);
14563        let end = self
14564            .end
14565            .to_point(&map.buffer_snapshot)
14566            .to_display_point(map);
14567        if self.reversed {
14568            end..start
14569        } else {
14570            start..end
14571        }
14572    }
14573
14574    fn spanned_rows(
14575        &self,
14576        include_end_if_at_line_start: bool,
14577        map: &DisplaySnapshot,
14578    ) -> Range<MultiBufferRow> {
14579        let start = self.start.to_point(&map.buffer_snapshot);
14580        let mut end = self.end.to_point(&map.buffer_snapshot);
14581        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14582            end.row -= 1;
14583        }
14584
14585        let buffer_start = map.prev_line_boundary(start).0;
14586        let buffer_end = map.next_line_boundary(end).0;
14587        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14588    }
14589}
14590
14591impl<T: InvalidationRegion> InvalidationStack<T> {
14592    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14593    where
14594        S: Clone + ToOffset,
14595    {
14596        while let Some(region) = self.last() {
14597            let all_selections_inside_invalidation_ranges =
14598                if selections.len() == region.ranges().len() {
14599                    selections
14600                        .iter()
14601                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14602                        .all(|(selection, invalidation_range)| {
14603                            let head = selection.head().to_offset(buffer);
14604                            invalidation_range.start <= head && invalidation_range.end >= head
14605                        })
14606                } else {
14607                    false
14608                };
14609
14610            if all_selections_inside_invalidation_ranges {
14611                break;
14612            } else {
14613                self.pop();
14614            }
14615        }
14616    }
14617}
14618
14619impl<T> Default for InvalidationStack<T> {
14620    fn default() -> Self {
14621        Self(Default::default())
14622    }
14623}
14624
14625impl<T> Deref for InvalidationStack<T> {
14626    type Target = Vec<T>;
14627
14628    fn deref(&self) -> &Self::Target {
14629        &self.0
14630    }
14631}
14632
14633impl<T> DerefMut for InvalidationStack<T> {
14634    fn deref_mut(&mut self) -> &mut Self::Target {
14635        &mut self.0
14636    }
14637}
14638
14639impl InvalidationRegion for SnippetState {
14640    fn ranges(&self) -> &[Range<Anchor>] {
14641        &self.ranges[self.active_index]
14642    }
14643}
14644
14645pub fn diagnostic_block_renderer(
14646    diagnostic: Diagnostic,
14647    max_message_rows: Option<u8>,
14648    allow_closing: bool,
14649    _is_valid: bool,
14650) -> RenderBlock {
14651    let (text_without_backticks, code_ranges) =
14652        highlight_diagnostic_message(&diagnostic, max_message_rows);
14653
14654    Arc::new(move |cx: &mut BlockContext| {
14655        let group_id: SharedString = cx.block_id.to_string().into();
14656
14657        let mut text_style = cx.text_style().clone();
14658        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14659        let theme_settings = ThemeSettings::get_global(cx);
14660        text_style.font_family = theme_settings.buffer_font.family.clone();
14661        text_style.font_style = theme_settings.buffer_font.style;
14662        text_style.font_features = theme_settings.buffer_font.features.clone();
14663        text_style.font_weight = theme_settings.buffer_font.weight;
14664
14665        let multi_line_diagnostic = diagnostic.message.contains('\n');
14666
14667        let buttons = |diagnostic: &Diagnostic| {
14668            if multi_line_diagnostic {
14669                v_flex()
14670            } else {
14671                h_flex()
14672            }
14673            .when(allow_closing, |div| {
14674                div.children(diagnostic.is_primary.then(|| {
14675                    IconButton::new("close-block", IconName::XCircle)
14676                        .icon_color(Color::Muted)
14677                        .size(ButtonSize::Compact)
14678                        .style(ButtonStyle::Transparent)
14679                        .visible_on_hover(group_id.clone())
14680                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14681                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14682                }))
14683            })
14684            .child(
14685                IconButton::new("copy-block", IconName::Copy)
14686                    .icon_color(Color::Muted)
14687                    .size(ButtonSize::Compact)
14688                    .style(ButtonStyle::Transparent)
14689                    .visible_on_hover(group_id.clone())
14690                    .on_click({
14691                        let message = diagnostic.message.clone();
14692                        move |_click, cx| {
14693                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14694                        }
14695                    })
14696                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14697            )
14698        };
14699
14700        let icon_size = buttons(&diagnostic)
14701            .into_any_element()
14702            .layout_as_root(AvailableSpace::min_size(), cx);
14703
14704        h_flex()
14705            .id(cx.block_id)
14706            .group(group_id.clone())
14707            .relative()
14708            .size_full()
14709            .block_mouse_down()
14710            .pl(cx.gutter_dimensions.width)
14711            .w(cx.max_width - cx.gutter_dimensions.full_width())
14712            .child(
14713                div()
14714                    .flex()
14715                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14716                    .flex_shrink(),
14717            )
14718            .child(buttons(&diagnostic))
14719            .child(div().flex().flex_shrink_0().child(
14720                StyledText::new(text_without_backticks.clone()).with_highlights(
14721                    &text_style,
14722                    code_ranges.iter().map(|range| {
14723                        (
14724                            range.clone(),
14725                            HighlightStyle {
14726                                font_weight: Some(FontWeight::BOLD),
14727                                ..Default::default()
14728                            },
14729                        )
14730                    }),
14731                ),
14732            ))
14733            .into_any_element()
14734    })
14735}
14736
14737fn inline_completion_edit_text(
14738    editor_snapshot: &EditorSnapshot,
14739    edits: &Vec<(Range<Anchor>, String)>,
14740    include_deletions: bool,
14741    cx: &WindowContext,
14742) -> InlineCompletionText {
14743    let edit_start = edits
14744        .first()
14745        .unwrap()
14746        .0
14747        .start
14748        .to_display_point(editor_snapshot);
14749
14750    let mut text = String::new();
14751    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14752    let mut highlights = Vec::new();
14753    for (old_range, new_text) in edits {
14754        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14755        text.extend(
14756            editor_snapshot
14757                .buffer_snapshot
14758                .chunks(offset..old_offset_range.start, false)
14759                .map(|chunk| chunk.text),
14760        );
14761        offset = old_offset_range.end;
14762
14763        let start = text.len();
14764        let color = if include_deletions && new_text.is_empty() {
14765            text.extend(
14766                editor_snapshot
14767                    .buffer_snapshot
14768                    .chunks(old_offset_range.start..offset, false)
14769                    .map(|chunk| chunk.text),
14770            );
14771            cx.theme().status().deleted_background
14772        } else {
14773            text.push_str(new_text);
14774            cx.theme().status().created_background
14775        };
14776        let end = text.len();
14777
14778        highlights.push((
14779            start..end,
14780            HighlightStyle {
14781                background_color: Some(color),
14782                ..Default::default()
14783            },
14784        ));
14785    }
14786
14787    let edit_end = edits
14788        .last()
14789        .unwrap()
14790        .0
14791        .end
14792        .to_display_point(editor_snapshot);
14793    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14794        .to_offset(editor_snapshot, Bias::Right);
14795    text.extend(
14796        editor_snapshot
14797            .buffer_snapshot
14798            .chunks(offset..end_of_line, false)
14799            .map(|chunk| chunk.text),
14800    );
14801
14802    InlineCompletionText::Edit {
14803        text: text.into(),
14804        highlights,
14805    }
14806}
14807
14808pub fn highlight_diagnostic_message(
14809    diagnostic: &Diagnostic,
14810    mut max_message_rows: Option<u8>,
14811) -> (SharedString, Vec<Range<usize>>) {
14812    let mut text_without_backticks = String::new();
14813    let mut code_ranges = Vec::new();
14814
14815    if let Some(source) = &diagnostic.source {
14816        text_without_backticks.push_str(source);
14817        code_ranges.push(0..source.len());
14818        text_without_backticks.push_str(": ");
14819    }
14820
14821    let mut prev_offset = 0;
14822    let mut in_code_block = false;
14823    let has_row_limit = max_message_rows.is_some();
14824    let mut newline_indices = diagnostic
14825        .message
14826        .match_indices('\n')
14827        .filter(|_| has_row_limit)
14828        .map(|(ix, _)| ix)
14829        .fuse()
14830        .peekable();
14831
14832    for (quote_ix, _) in diagnostic
14833        .message
14834        .match_indices('`')
14835        .chain([(diagnostic.message.len(), "")])
14836    {
14837        let mut first_newline_ix = None;
14838        let mut last_newline_ix = None;
14839        while let Some(newline_ix) = newline_indices.peek() {
14840            if *newline_ix < quote_ix {
14841                if first_newline_ix.is_none() {
14842                    first_newline_ix = Some(*newline_ix);
14843                }
14844                last_newline_ix = Some(*newline_ix);
14845
14846                if let Some(rows_left) = &mut max_message_rows {
14847                    if *rows_left == 0 {
14848                        break;
14849                    } else {
14850                        *rows_left -= 1;
14851                    }
14852                }
14853                let _ = newline_indices.next();
14854            } else {
14855                break;
14856            }
14857        }
14858        let prev_len = text_without_backticks.len();
14859        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14860        text_without_backticks.push_str(new_text);
14861        if in_code_block {
14862            code_ranges.push(prev_len..text_without_backticks.len());
14863        }
14864        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14865        in_code_block = !in_code_block;
14866        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14867            text_without_backticks.push_str("...");
14868            break;
14869        }
14870    }
14871
14872    (text_without_backticks.into(), code_ranges)
14873}
14874
14875fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14876    match severity {
14877        DiagnosticSeverity::ERROR => colors.error,
14878        DiagnosticSeverity::WARNING => colors.warning,
14879        DiagnosticSeverity::INFORMATION => colors.info,
14880        DiagnosticSeverity::HINT => colors.info,
14881        _ => colors.ignored,
14882    }
14883}
14884
14885pub fn styled_runs_for_code_label<'a>(
14886    label: &'a CodeLabel,
14887    syntax_theme: &'a theme::SyntaxTheme,
14888) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14889    let fade_out = HighlightStyle {
14890        fade_out: Some(0.35),
14891        ..Default::default()
14892    };
14893
14894    let mut prev_end = label.filter_range.end;
14895    label
14896        .runs
14897        .iter()
14898        .enumerate()
14899        .flat_map(move |(ix, (range, highlight_id))| {
14900            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14901                style
14902            } else {
14903                return Default::default();
14904            };
14905            let mut muted_style = style;
14906            muted_style.highlight(fade_out);
14907
14908            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14909            if range.start >= label.filter_range.end {
14910                if range.start > prev_end {
14911                    runs.push((prev_end..range.start, fade_out));
14912                }
14913                runs.push((range.clone(), muted_style));
14914            } else if range.end <= label.filter_range.end {
14915                runs.push((range.clone(), style));
14916            } else {
14917                runs.push((range.start..label.filter_range.end, style));
14918                runs.push((label.filter_range.end..range.end, muted_style));
14919            }
14920            prev_end = cmp::max(prev_end, range.end);
14921
14922            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14923                runs.push((prev_end..label.text.len(), fade_out));
14924            }
14925
14926            runs
14927        })
14928}
14929
14930pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14931    let mut prev_index = 0;
14932    let mut prev_codepoint: Option<char> = None;
14933    text.char_indices()
14934        .chain([(text.len(), '\0')])
14935        .filter_map(move |(index, codepoint)| {
14936            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14937            let is_boundary = index == text.len()
14938                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14939                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14940            if is_boundary {
14941                let chunk = &text[prev_index..index];
14942                prev_index = index;
14943                Some(chunk)
14944            } else {
14945                None
14946            }
14947        })
14948}
14949
14950pub trait RangeToAnchorExt: Sized {
14951    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14952
14953    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14954        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14955        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14956    }
14957}
14958
14959impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14960    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14961        let start_offset = self.start.to_offset(snapshot);
14962        let end_offset = self.end.to_offset(snapshot);
14963        if start_offset == end_offset {
14964            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14965        } else {
14966            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14967        }
14968    }
14969}
14970
14971pub trait RowExt {
14972    fn as_f32(&self) -> f32;
14973
14974    fn next_row(&self) -> Self;
14975
14976    fn previous_row(&self) -> Self;
14977
14978    fn minus(&self, other: Self) -> u32;
14979}
14980
14981impl RowExt for DisplayRow {
14982    fn as_f32(&self) -> f32 {
14983        self.0 as f32
14984    }
14985
14986    fn next_row(&self) -> Self {
14987        Self(self.0 + 1)
14988    }
14989
14990    fn previous_row(&self) -> Self {
14991        Self(self.0.saturating_sub(1))
14992    }
14993
14994    fn minus(&self, other: Self) -> u32 {
14995        self.0 - other.0
14996    }
14997}
14998
14999impl RowExt for MultiBufferRow {
15000    fn as_f32(&self) -> f32 {
15001        self.0 as f32
15002    }
15003
15004    fn next_row(&self) -> Self {
15005        Self(self.0 + 1)
15006    }
15007
15008    fn previous_row(&self) -> Self {
15009        Self(self.0.saturating_sub(1))
15010    }
15011
15012    fn minus(&self, other: Self) -> u32 {
15013        self.0 - other.0
15014    }
15015}
15016
15017trait RowRangeExt {
15018    type Row;
15019
15020    fn len(&self) -> usize;
15021
15022    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15023}
15024
15025impl RowRangeExt for Range<MultiBufferRow> {
15026    type Row = MultiBufferRow;
15027
15028    fn len(&self) -> usize {
15029        (self.end.0 - self.start.0) as usize
15030    }
15031
15032    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15033        (self.start.0..self.end.0).map(MultiBufferRow)
15034    }
15035}
15036
15037impl RowRangeExt for Range<DisplayRow> {
15038    type Row = DisplayRow;
15039
15040    fn len(&self) -> usize {
15041        (self.end.0 - self.start.0) as usize
15042    }
15043
15044    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15045        (self.start.0..self.end.0).map(DisplayRow)
15046    }
15047}
15048
15049fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15050    if hunk.diff_base_byte_range.is_empty() {
15051        DiffHunkStatus::Added
15052    } else if hunk.row_range.is_empty() {
15053        DiffHunkStatus::Removed
15054    } else {
15055        DiffHunkStatus::Modified
15056    }
15057}
15058
15059/// If select range has more than one line, we
15060/// just point the cursor to range.start.
15061fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15062    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15063        range
15064    } else {
15065        range.start..range.start
15066    }
15067}
15068
15069pub struct KillRing(ClipboardItem);
15070impl Global for KillRing {}
15071
15072const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);