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::{FormatTrigger, LspFormatTarget, 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 enum FormatTarget {
  990    Buffers,
  991    Ranges(Vec<Range<MultiBufferPoint>>),
  992}
  993
  994pub(crate) struct FocusedBlock {
  995    id: BlockId,
  996    focus_handle: WeakFocusHandle,
  997}
  998
  999#[derive(Clone)]
 1000enum JumpData {
 1001    MultiBufferRow {
 1002        row: MultiBufferRow,
 1003        line_offset_from_top: u32,
 1004    },
 1005    MultiBufferPoint {
 1006        excerpt_id: ExcerptId,
 1007        position: Point,
 1008        anchor: text::Anchor,
 1009        line_offset_from_top: u32,
 1010    },
 1011}
 1012
 1013impl Editor {
 1014    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1015        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1016        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1017        Self::new(
 1018            EditorMode::SingleLine { auto_width: false },
 1019            buffer,
 1020            None,
 1021            false,
 1022            cx,
 1023        )
 1024    }
 1025
 1026    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1027        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1028        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1029        Self::new(EditorMode::Full, buffer, None, false, cx)
 1030    }
 1031
 1032    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1033        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1034        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1035        Self::new(
 1036            EditorMode::SingleLine { auto_width: true },
 1037            buffer,
 1038            None,
 1039            false,
 1040            cx,
 1041        )
 1042    }
 1043
 1044    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1045        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1046        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1047        Self::new(
 1048            EditorMode::AutoHeight { max_lines },
 1049            buffer,
 1050            None,
 1051            false,
 1052            cx,
 1053        )
 1054    }
 1055
 1056    pub fn for_buffer(
 1057        buffer: Model<Buffer>,
 1058        project: Option<Model<Project>>,
 1059        cx: &mut ViewContext<Self>,
 1060    ) -> Self {
 1061        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1062        Self::new(EditorMode::Full, buffer, project, false, cx)
 1063    }
 1064
 1065    pub fn for_multibuffer(
 1066        buffer: Model<MultiBuffer>,
 1067        project: Option<Model<Project>>,
 1068        show_excerpt_controls: bool,
 1069        cx: &mut ViewContext<Self>,
 1070    ) -> Self {
 1071        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1072    }
 1073
 1074    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1075        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1076        let mut clone = Self::new(
 1077            self.mode,
 1078            self.buffer.clone(),
 1079            self.project.clone(),
 1080            show_excerpt_controls,
 1081            cx,
 1082        );
 1083        self.display_map.update(cx, |display_map, cx| {
 1084            let snapshot = display_map.snapshot(cx);
 1085            clone.display_map.update(cx, |display_map, cx| {
 1086                display_map.set_state(&snapshot, cx);
 1087            });
 1088        });
 1089        clone.selections.clone_state(&self.selections);
 1090        clone.scroll_manager.clone_state(&self.scroll_manager);
 1091        clone.searchable = self.searchable;
 1092        clone
 1093    }
 1094
 1095    pub fn new(
 1096        mode: EditorMode,
 1097        buffer: Model<MultiBuffer>,
 1098        project: Option<Model<Project>>,
 1099        show_excerpt_controls: bool,
 1100        cx: &mut ViewContext<Self>,
 1101    ) -> Self {
 1102        let style = cx.text_style();
 1103        let font_size = style.font_size.to_pixels(cx.rem_size());
 1104        let editor = cx.view().downgrade();
 1105        let fold_placeholder = FoldPlaceholder {
 1106            constrain_width: true,
 1107            render: Arc::new(move |fold_id, fold_range, cx| {
 1108                let editor = editor.clone();
 1109                div()
 1110                    .id(fold_id)
 1111                    .bg(cx.theme().colors().ghost_element_background)
 1112                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1113                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1114                    .rounded_sm()
 1115                    .size_full()
 1116                    .cursor_pointer()
 1117                    .child("")
 1118                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1119                    .on_click(move |_, cx| {
 1120                        editor
 1121                            .update(cx, |editor, cx| {
 1122                                editor.unfold_ranges(
 1123                                    &[fold_range.start..fold_range.end],
 1124                                    true,
 1125                                    false,
 1126                                    cx,
 1127                                );
 1128                                cx.stop_propagation();
 1129                            })
 1130                            .ok();
 1131                    })
 1132                    .into_any()
 1133            }),
 1134            merge_adjacent: true,
 1135            ..Default::default()
 1136        };
 1137        let display_map = cx.new_model(|cx| {
 1138            DisplayMap::new(
 1139                buffer.clone(),
 1140                style.font(),
 1141                font_size,
 1142                None,
 1143                show_excerpt_controls,
 1144                FILE_HEADER_HEIGHT,
 1145                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1146                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1147                fold_placeholder,
 1148                cx,
 1149            )
 1150        });
 1151
 1152        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1153
 1154        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1155
 1156        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1157            .then(|| language_settings::SoftWrap::None);
 1158
 1159        let mut project_subscriptions = Vec::new();
 1160        if mode == EditorMode::Full {
 1161            if let Some(project) = project.as_ref() {
 1162                if buffer.read(cx).is_singleton() {
 1163                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1164                        cx.emit(EditorEvent::TitleChanged);
 1165                    }));
 1166                }
 1167                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1168                    if let project::Event::RefreshInlayHints = event {
 1169                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1170                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1171                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1172                            let focus_handle = editor.focus_handle(cx);
 1173                            if focus_handle.is_focused(cx) {
 1174                                let snapshot = buffer.read(cx).snapshot();
 1175                                for (range, snippet) in snippet_edits {
 1176                                    let editor_range =
 1177                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1178                                    editor
 1179                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1180                                        .ok();
 1181                                }
 1182                            }
 1183                        }
 1184                    }
 1185                }));
 1186                if let Some(task_inventory) = project
 1187                    .read(cx)
 1188                    .task_store()
 1189                    .read(cx)
 1190                    .task_inventory()
 1191                    .cloned()
 1192                {
 1193                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1194                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1195                    }));
 1196                }
 1197            }
 1198        }
 1199
 1200        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1201
 1202        let inlay_hint_settings =
 1203            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1204        let focus_handle = cx.focus_handle();
 1205        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1206        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1207            .detach();
 1208        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1209            .detach();
 1210        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1211
 1212        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1213            Some(false)
 1214        } else {
 1215            None
 1216        };
 1217
 1218        let mut code_action_providers = Vec::new();
 1219        if let Some(project) = project.clone() {
 1220            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1221            code_action_providers.push(Rc::new(project) as Rc<_>);
 1222        }
 1223
 1224        let mut this = Self {
 1225            focus_handle,
 1226            show_cursor_when_unfocused: false,
 1227            last_focused_descendant: None,
 1228            buffer: buffer.clone(),
 1229            display_map: display_map.clone(),
 1230            selections,
 1231            scroll_manager: ScrollManager::new(cx),
 1232            columnar_selection_tail: None,
 1233            add_selections_state: None,
 1234            select_next_state: None,
 1235            select_prev_state: None,
 1236            selection_history: Default::default(),
 1237            autoclose_regions: Default::default(),
 1238            snippet_stack: Default::default(),
 1239            select_larger_syntax_node_stack: Vec::new(),
 1240            ime_transaction: Default::default(),
 1241            active_diagnostics: None,
 1242            soft_wrap_mode_override,
 1243            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1244            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1245            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1246            project,
 1247            blink_manager: blink_manager.clone(),
 1248            show_local_selections: true,
 1249            show_scrollbars: true,
 1250            mode,
 1251            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1252            show_gutter: mode == EditorMode::Full,
 1253            show_line_numbers: None,
 1254            use_relative_line_numbers: None,
 1255            show_git_diff_gutter: None,
 1256            show_code_actions: None,
 1257            show_runnables: None,
 1258            show_wrap_guides: None,
 1259            show_indent_guides,
 1260            placeholder_text: None,
 1261            highlight_order: 0,
 1262            highlighted_rows: HashMap::default(),
 1263            background_highlights: Default::default(),
 1264            gutter_highlights: TreeMap::default(),
 1265            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1266            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1267            nav_history: None,
 1268            context_menu: RefCell::new(None),
 1269            mouse_context_menu: None,
 1270            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1271            completion_tasks: Default::default(),
 1272            signature_help_state: SignatureHelpState::default(),
 1273            auto_signature_help: None,
 1274            find_all_references_task_sources: Vec::new(),
 1275            next_completion_id: 0,
 1276            next_inlay_id: 0,
 1277            code_action_providers,
 1278            available_code_actions: Default::default(),
 1279            code_actions_task: Default::default(),
 1280            document_highlights_task: Default::default(),
 1281            linked_editing_range_task: Default::default(),
 1282            pending_rename: Default::default(),
 1283            searchable: true,
 1284            cursor_shape: EditorSettings::get_global(cx)
 1285                .cursor_shape
 1286                .unwrap_or_default(),
 1287            current_line_highlight: None,
 1288            autoindent_mode: Some(AutoindentMode::EachLine),
 1289            collapse_matches: false,
 1290            workspace: None,
 1291            input_enabled: true,
 1292            use_modal_editing: mode == EditorMode::Full,
 1293            read_only: false,
 1294            use_autoclose: true,
 1295            use_auto_surround: true,
 1296            auto_replace_emoji_shortcode: false,
 1297            leader_peer_id: None,
 1298            remote_id: None,
 1299            hover_state: Default::default(),
 1300            hovered_link_state: Default::default(),
 1301            inline_completion_provider: None,
 1302            active_inline_completion: None,
 1303            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1304            diff_map: DiffMap::default(),
 1305            gutter_hovered: false,
 1306            pixel_position_of_newest_cursor: None,
 1307            last_bounds: None,
 1308            expect_bounds_change: None,
 1309            gutter_dimensions: GutterDimensions::default(),
 1310            style: None,
 1311            show_cursor_names: false,
 1312            hovered_cursors: Default::default(),
 1313            next_editor_action_id: EditorActionId::default(),
 1314            editor_actions: Rc::default(),
 1315            show_inline_completions_override: None,
 1316            enable_inline_completions: true,
 1317            custom_context_menu: None,
 1318            show_git_blame_gutter: false,
 1319            show_git_blame_inline: false,
 1320            show_selection_menu: None,
 1321            show_git_blame_inline_delay_task: None,
 1322            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1323            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1324                .session
 1325                .restore_unsaved_buffers,
 1326            blame: None,
 1327            blame_subscription: None,
 1328            tasks: Default::default(),
 1329            _subscriptions: vec![
 1330                cx.observe(&buffer, Self::on_buffer_changed),
 1331                cx.subscribe(&buffer, Self::on_buffer_event),
 1332                cx.observe(&display_map, Self::on_display_map_changed),
 1333                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1334                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1335                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1336                cx.observe_window_activation(|editor, cx| {
 1337                    let active = cx.is_window_active();
 1338                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1339                        if active {
 1340                            blink_manager.enable(cx);
 1341                        } else {
 1342                            blink_manager.disable(cx);
 1343                        }
 1344                    });
 1345                }),
 1346            ],
 1347            tasks_update_task: None,
 1348            linked_edit_ranges: Default::default(),
 1349            previous_search_ranges: None,
 1350            breadcrumb_header: None,
 1351            focused_block: None,
 1352            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1353            addons: HashMap::default(),
 1354            registered_buffers: HashMap::default(),
 1355            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1356            toggle_fold_multiple_buffers: Task::ready(()),
 1357            text_style_refinement: None,
 1358        };
 1359        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1360        this._subscriptions.extend(project_subscriptions);
 1361
 1362        this.end_selection(cx);
 1363        this.scroll_manager.show_scrollbar(cx);
 1364
 1365        if mode == EditorMode::Full {
 1366            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1367            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1368
 1369            if this.git_blame_inline_enabled {
 1370                this.git_blame_inline_enabled = true;
 1371                this.start_git_blame_inline(false, cx);
 1372            }
 1373
 1374            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1375                if let Some(project) = this.project.as_ref() {
 1376                    let lsp_store = project.read(cx).lsp_store();
 1377                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1378                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1379                    });
 1380                    this.registered_buffers
 1381                        .insert(buffer.read(cx).remote_id(), handle);
 1382                }
 1383            }
 1384        }
 1385
 1386        this.report_editor_event("Editor Opened", None, cx);
 1387        this
 1388    }
 1389
 1390    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1391        self.mouse_context_menu
 1392            .as_ref()
 1393            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1394    }
 1395
 1396    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1397        let mut key_context = KeyContext::new_with_defaults();
 1398        key_context.add("Editor");
 1399        let mode = match self.mode {
 1400            EditorMode::SingleLine { .. } => "single_line",
 1401            EditorMode::AutoHeight { .. } => "auto_height",
 1402            EditorMode::Full => "full",
 1403        };
 1404
 1405        if EditorSettings::jupyter_enabled(cx) {
 1406            key_context.add("jupyter");
 1407        }
 1408
 1409        key_context.set("mode", mode);
 1410        if self.pending_rename.is_some() {
 1411            key_context.add("renaming");
 1412        }
 1413        match self.context_menu.borrow().as_ref() {
 1414            Some(CodeContextMenu::Completions(_)) => {
 1415                key_context.add("menu");
 1416                key_context.add("showing_completions")
 1417            }
 1418            Some(CodeContextMenu::CodeActions(_)) => {
 1419                key_context.add("menu");
 1420                key_context.add("showing_code_actions")
 1421            }
 1422            None => {}
 1423        }
 1424
 1425        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1426        if !self.focus_handle(cx).contains_focused(cx)
 1427            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1428        {
 1429            for addon in self.addons.values() {
 1430                addon.extend_key_context(&mut key_context, cx)
 1431            }
 1432        }
 1433
 1434        if let Some(extension) = self
 1435            .buffer
 1436            .read(cx)
 1437            .as_singleton()
 1438            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1439        {
 1440            key_context.set("extension", extension.to_string());
 1441        }
 1442
 1443        if self.has_active_inline_completion() {
 1444            key_context.add("copilot_suggestion");
 1445            key_context.add("inline_completion");
 1446        }
 1447
 1448        if !self
 1449            .selections
 1450            .disjoint
 1451            .iter()
 1452            .all(|selection| selection.start == selection.end)
 1453        {
 1454            key_context.add("selection");
 1455        }
 1456
 1457        key_context
 1458    }
 1459
 1460    pub fn new_file(
 1461        workspace: &mut Workspace,
 1462        _: &workspace::NewFile,
 1463        cx: &mut ViewContext<Workspace>,
 1464    ) {
 1465        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1466            "Failed to create buffer",
 1467            cx,
 1468            |e, _| match e.error_code() {
 1469                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1470                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1471                e.error_tag("required").unwrap_or("the latest version")
 1472            )),
 1473                _ => None,
 1474            },
 1475        );
 1476    }
 1477
 1478    pub fn new_in_workspace(
 1479        workspace: &mut Workspace,
 1480        cx: &mut ViewContext<Workspace>,
 1481    ) -> Task<Result<View<Editor>>> {
 1482        let project = workspace.project().clone();
 1483        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1484
 1485        cx.spawn(|workspace, mut cx| async move {
 1486            let buffer = create.await?;
 1487            workspace.update(&mut cx, |workspace, cx| {
 1488                let editor =
 1489                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1490                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1491                editor
 1492            })
 1493        })
 1494    }
 1495
 1496    fn new_file_vertical(
 1497        workspace: &mut Workspace,
 1498        _: &workspace::NewFileSplitVertical,
 1499        cx: &mut ViewContext<Workspace>,
 1500    ) {
 1501        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1502    }
 1503
 1504    fn new_file_horizontal(
 1505        workspace: &mut Workspace,
 1506        _: &workspace::NewFileSplitHorizontal,
 1507        cx: &mut ViewContext<Workspace>,
 1508    ) {
 1509        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1510    }
 1511
 1512    fn new_file_in_direction(
 1513        workspace: &mut Workspace,
 1514        direction: SplitDirection,
 1515        cx: &mut ViewContext<Workspace>,
 1516    ) {
 1517        let project = workspace.project().clone();
 1518        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1519
 1520        cx.spawn(|workspace, mut cx| async move {
 1521            let buffer = create.await?;
 1522            workspace.update(&mut cx, move |workspace, cx| {
 1523                workspace.split_item(
 1524                    direction,
 1525                    Box::new(
 1526                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1527                    ),
 1528                    cx,
 1529                )
 1530            })?;
 1531            anyhow::Ok(())
 1532        })
 1533        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1534            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1535                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1536                e.error_tag("required").unwrap_or("the latest version")
 1537            )),
 1538            _ => None,
 1539        });
 1540    }
 1541
 1542    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1543        self.leader_peer_id
 1544    }
 1545
 1546    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1547        &self.buffer
 1548    }
 1549
 1550    pub fn workspace(&self) -> Option<View<Workspace>> {
 1551        self.workspace.as_ref()?.0.upgrade()
 1552    }
 1553
 1554    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1555        self.buffer().read(cx).title(cx)
 1556    }
 1557
 1558    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1559        let git_blame_gutter_max_author_length = self
 1560            .render_git_blame_gutter(cx)
 1561            .then(|| {
 1562                if let Some(blame) = self.blame.as_ref() {
 1563                    let max_author_length =
 1564                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1565                    Some(max_author_length)
 1566                } else {
 1567                    None
 1568                }
 1569            })
 1570            .flatten();
 1571
 1572        EditorSnapshot {
 1573            mode: self.mode,
 1574            show_gutter: self.show_gutter,
 1575            show_line_numbers: self.show_line_numbers,
 1576            show_git_diff_gutter: self.show_git_diff_gutter,
 1577            show_code_actions: self.show_code_actions,
 1578            show_runnables: self.show_runnables,
 1579            git_blame_gutter_max_author_length,
 1580            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1581            scroll_anchor: self.scroll_manager.anchor(),
 1582            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1583            placeholder_text: self.placeholder_text.clone(),
 1584            diff_map: self.diff_map.snapshot(),
 1585            is_focused: self.focus_handle.is_focused(cx),
 1586            current_line_highlight: self
 1587                .current_line_highlight
 1588                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1589            gutter_hovered: self.gutter_hovered,
 1590        }
 1591    }
 1592
 1593    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1594        self.buffer.read(cx).language_at(point, cx)
 1595    }
 1596
 1597    pub fn file_at<T: ToOffset>(
 1598        &self,
 1599        point: T,
 1600        cx: &AppContext,
 1601    ) -> Option<Arc<dyn language::File>> {
 1602        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1603    }
 1604
 1605    pub fn active_excerpt(
 1606        &self,
 1607        cx: &AppContext,
 1608    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1609        self.buffer
 1610            .read(cx)
 1611            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1612    }
 1613
 1614    pub fn mode(&self) -> EditorMode {
 1615        self.mode
 1616    }
 1617
 1618    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1619        self.collaboration_hub.as_deref()
 1620    }
 1621
 1622    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1623        self.collaboration_hub = Some(hub);
 1624    }
 1625
 1626    pub fn set_custom_context_menu(
 1627        &mut self,
 1628        f: impl 'static
 1629            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1630    ) {
 1631        self.custom_context_menu = Some(Box::new(f))
 1632    }
 1633
 1634    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1635        self.completion_provider = provider;
 1636    }
 1637
 1638    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1639        self.semantics_provider.clone()
 1640    }
 1641
 1642    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1643        self.semantics_provider = provider;
 1644    }
 1645
 1646    pub fn set_inline_completion_provider<T>(
 1647        &mut self,
 1648        provider: Option<Model<T>>,
 1649        cx: &mut ViewContext<Self>,
 1650    ) where
 1651        T: InlineCompletionProvider,
 1652    {
 1653        self.inline_completion_provider =
 1654            provider.map(|provider| RegisteredInlineCompletionProvider {
 1655                _subscription: cx.observe(&provider, |this, _, cx| {
 1656                    if this.focus_handle.is_focused(cx) {
 1657                        this.update_visible_inline_completion(cx);
 1658                    }
 1659                }),
 1660                provider: Arc::new(provider),
 1661            });
 1662        self.refresh_inline_completion(false, false, cx);
 1663    }
 1664
 1665    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1666        self.placeholder_text.as_deref()
 1667    }
 1668
 1669    pub fn set_placeholder_text(
 1670        &mut self,
 1671        placeholder_text: impl Into<Arc<str>>,
 1672        cx: &mut ViewContext<Self>,
 1673    ) {
 1674        let placeholder_text = Some(placeholder_text.into());
 1675        if self.placeholder_text != placeholder_text {
 1676            self.placeholder_text = placeholder_text;
 1677            cx.notify();
 1678        }
 1679    }
 1680
 1681    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1682        self.cursor_shape = cursor_shape;
 1683
 1684        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1685        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1686
 1687        cx.notify();
 1688    }
 1689
 1690    pub fn set_current_line_highlight(
 1691        &mut self,
 1692        current_line_highlight: Option<CurrentLineHighlight>,
 1693    ) {
 1694        self.current_line_highlight = current_line_highlight;
 1695    }
 1696
 1697    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1698        self.collapse_matches = collapse_matches;
 1699    }
 1700
 1701    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1702        let buffers = self.buffer.read(cx).all_buffers();
 1703        let Some(lsp_store) = self.lsp_store(cx) else {
 1704            return;
 1705        };
 1706        lsp_store.update(cx, |lsp_store, cx| {
 1707            for buffer in buffers {
 1708                self.registered_buffers
 1709                    .entry(buffer.read(cx).remote_id())
 1710                    .or_insert_with(|| {
 1711                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1712                    });
 1713            }
 1714        })
 1715    }
 1716
 1717    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1718        if self.collapse_matches {
 1719            return range.start..range.start;
 1720        }
 1721        range.clone()
 1722    }
 1723
 1724    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1725        if self.display_map.read(cx).clip_at_line_ends != clip {
 1726            self.display_map
 1727                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1728        }
 1729    }
 1730
 1731    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1732        self.input_enabled = input_enabled;
 1733    }
 1734
 1735    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1736        self.enable_inline_completions = enabled;
 1737    }
 1738
 1739    pub fn set_autoindent(&mut self, autoindent: bool) {
 1740        if autoindent {
 1741            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1742        } else {
 1743            self.autoindent_mode = None;
 1744        }
 1745    }
 1746
 1747    pub fn read_only(&self, cx: &AppContext) -> bool {
 1748        self.read_only || self.buffer.read(cx).read_only()
 1749    }
 1750
 1751    pub fn set_read_only(&mut self, read_only: bool) {
 1752        self.read_only = read_only;
 1753    }
 1754
 1755    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1756        self.use_autoclose = autoclose;
 1757    }
 1758
 1759    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1760        self.use_auto_surround = auto_surround;
 1761    }
 1762
 1763    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1764        self.auto_replace_emoji_shortcode = auto_replace;
 1765    }
 1766
 1767    pub fn toggle_inline_completions(
 1768        &mut self,
 1769        _: &ToggleInlineCompletions,
 1770        cx: &mut ViewContext<Self>,
 1771    ) {
 1772        if self.show_inline_completions_override.is_some() {
 1773            self.set_show_inline_completions(None, cx);
 1774        } else {
 1775            let cursor = self.selections.newest_anchor().head();
 1776            if let Some((buffer, cursor_buffer_position)) =
 1777                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1778            {
 1779                let show_inline_completions =
 1780                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1781                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1782            }
 1783        }
 1784    }
 1785
 1786    pub fn set_show_inline_completions(
 1787        &mut self,
 1788        show_inline_completions: Option<bool>,
 1789        cx: &mut ViewContext<Self>,
 1790    ) {
 1791        self.show_inline_completions_override = show_inline_completions;
 1792        self.refresh_inline_completion(false, true, cx);
 1793    }
 1794
 1795    pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
 1796        let cursor = self.selections.newest_anchor().head();
 1797        if let Some((buffer, buffer_position)) =
 1798            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1799        {
 1800            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1801        } else {
 1802            false
 1803        }
 1804    }
 1805
 1806    fn should_show_inline_completions(
 1807        &self,
 1808        buffer: &Model<Buffer>,
 1809        buffer_position: language::Anchor,
 1810        cx: &AppContext,
 1811    ) -> bool {
 1812        if !self.snippet_stack.is_empty() {
 1813            return false;
 1814        }
 1815
 1816        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1817            return false;
 1818        }
 1819
 1820        if let Some(provider) = self.inline_completion_provider() {
 1821            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1822                show_inline_completions
 1823            } else {
 1824                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1825            }
 1826        } else {
 1827            false
 1828        }
 1829    }
 1830
 1831    fn inline_completions_disabled_in_scope(
 1832        &self,
 1833        buffer: &Model<Buffer>,
 1834        buffer_position: language::Anchor,
 1835        cx: &AppContext,
 1836    ) -> bool {
 1837        let snapshot = buffer.read(cx).snapshot();
 1838        let settings = snapshot.settings_at(buffer_position, cx);
 1839
 1840        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1841            return false;
 1842        };
 1843
 1844        scope.override_name().map_or(false, |scope_name| {
 1845            settings
 1846                .inline_completions_disabled_in
 1847                .iter()
 1848                .any(|s| s == scope_name)
 1849        })
 1850    }
 1851
 1852    pub fn set_use_modal_editing(&mut self, to: bool) {
 1853        self.use_modal_editing = to;
 1854    }
 1855
 1856    pub fn use_modal_editing(&self) -> bool {
 1857        self.use_modal_editing
 1858    }
 1859
 1860    fn selections_did_change(
 1861        &mut self,
 1862        local: bool,
 1863        old_cursor_position: &Anchor,
 1864        show_completions: bool,
 1865        cx: &mut ViewContext<Self>,
 1866    ) {
 1867        cx.invalidate_character_coordinates();
 1868
 1869        // Copy selections to primary selection buffer
 1870        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1871        if local {
 1872            let selections = self.selections.all::<usize>(cx);
 1873            let buffer_handle = self.buffer.read(cx).read(cx);
 1874
 1875            let mut text = String::new();
 1876            for (index, selection) in selections.iter().enumerate() {
 1877                let text_for_selection = buffer_handle
 1878                    .text_for_range(selection.start..selection.end)
 1879                    .collect::<String>();
 1880
 1881                text.push_str(&text_for_selection);
 1882                if index != selections.len() - 1 {
 1883                    text.push('\n');
 1884                }
 1885            }
 1886
 1887            if !text.is_empty() {
 1888                cx.write_to_primary(ClipboardItem::new_string(text));
 1889            }
 1890        }
 1891
 1892        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1893            self.buffer.update(cx, |buffer, cx| {
 1894                buffer.set_active_selections(
 1895                    &self.selections.disjoint_anchors(),
 1896                    self.selections.line_mode,
 1897                    self.cursor_shape,
 1898                    cx,
 1899                )
 1900            });
 1901        }
 1902        let display_map = self
 1903            .display_map
 1904            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1905        let buffer = &display_map.buffer_snapshot;
 1906        self.add_selections_state = None;
 1907        self.select_next_state = None;
 1908        self.select_prev_state = None;
 1909        self.select_larger_syntax_node_stack.clear();
 1910        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1911        self.snippet_stack
 1912            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1913        self.take_rename(false, cx);
 1914
 1915        let new_cursor_position = self.selections.newest_anchor().head();
 1916
 1917        self.push_to_nav_history(
 1918            *old_cursor_position,
 1919            Some(new_cursor_position.to_point(buffer)),
 1920            cx,
 1921        );
 1922
 1923        if local {
 1924            let new_cursor_position = self.selections.newest_anchor().head();
 1925            let mut context_menu = self.context_menu.borrow_mut();
 1926            let completion_menu = match context_menu.as_ref() {
 1927                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1928                _ => {
 1929                    *context_menu = None;
 1930                    None
 1931                }
 1932            };
 1933
 1934            if let Some(completion_menu) = completion_menu {
 1935                let cursor_position = new_cursor_position.to_offset(buffer);
 1936                let (word_range, kind) =
 1937                    buffer.surrounding_word(completion_menu.initial_position, true);
 1938                if kind == Some(CharKind::Word)
 1939                    && word_range.to_inclusive().contains(&cursor_position)
 1940                {
 1941                    let mut completion_menu = completion_menu.clone();
 1942                    drop(context_menu);
 1943
 1944                    let query = Self::completion_query(buffer, cursor_position);
 1945                    cx.spawn(move |this, mut cx| async move {
 1946                        completion_menu
 1947                            .filter(query.as_deref(), cx.background_executor().clone())
 1948                            .await;
 1949
 1950                        this.update(&mut cx, |this, cx| {
 1951                            let mut context_menu = this.context_menu.borrow_mut();
 1952                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1953                            else {
 1954                                return;
 1955                            };
 1956
 1957                            if menu.id > completion_menu.id {
 1958                                return;
 1959                            }
 1960
 1961                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1962                            drop(context_menu);
 1963                            cx.notify();
 1964                        })
 1965                    })
 1966                    .detach();
 1967
 1968                    if show_completions {
 1969                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1970                    }
 1971                } else {
 1972                    drop(context_menu);
 1973                    self.hide_context_menu(cx);
 1974                }
 1975            } else {
 1976                drop(context_menu);
 1977            }
 1978
 1979            hide_hover(self, cx);
 1980
 1981            if old_cursor_position.to_display_point(&display_map).row()
 1982                != new_cursor_position.to_display_point(&display_map).row()
 1983            {
 1984                self.available_code_actions.take();
 1985            }
 1986            self.refresh_code_actions(cx);
 1987            self.refresh_document_highlights(cx);
 1988            refresh_matching_bracket_highlights(self, cx);
 1989            self.update_visible_inline_completion(cx);
 1990            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1991            if self.git_blame_inline_enabled {
 1992                self.start_inline_blame_timer(cx);
 1993            }
 1994        }
 1995
 1996        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1997        cx.emit(EditorEvent::SelectionsChanged { local });
 1998
 1999        if self.selections.disjoint_anchors().len() == 1 {
 2000            cx.emit(SearchEvent::ActiveMatchChanged)
 2001        }
 2002        cx.notify();
 2003    }
 2004
 2005    pub fn change_selections<R>(
 2006        &mut self,
 2007        autoscroll: Option<Autoscroll>,
 2008        cx: &mut ViewContext<Self>,
 2009        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2010    ) -> R {
 2011        self.change_selections_inner(autoscroll, true, cx, change)
 2012    }
 2013
 2014    pub fn change_selections_inner<R>(
 2015        &mut self,
 2016        autoscroll: Option<Autoscroll>,
 2017        request_completions: bool,
 2018        cx: &mut ViewContext<Self>,
 2019        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2020    ) -> R {
 2021        let old_cursor_position = self.selections.newest_anchor().head();
 2022        self.push_to_selection_history();
 2023
 2024        let (changed, result) = self.selections.change_with(cx, change);
 2025
 2026        if changed {
 2027            if let Some(autoscroll) = autoscroll {
 2028                self.request_autoscroll(autoscroll, cx);
 2029            }
 2030            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2031
 2032            if self.should_open_signature_help_automatically(
 2033                &old_cursor_position,
 2034                self.signature_help_state.backspace_pressed(),
 2035                cx,
 2036            ) {
 2037                self.show_signature_help(&ShowSignatureHelp, cx);
 2038            }
 2039            self.signature_help_state.set_backspace_pressed(false);
 2040        }
 2041
 2042        result
 2043    }
 2044
 2045    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2046    where
 2047        I: IntoIterator<Item = (Range<S>, T)>,
 2048        S: ToOffset,
 2049        T: Into<Arc<str>>,
 2050    {
 2051        if self.read_only(cx) {
 2052            return;
 2053        }
 2054
 2055        self.buffer
 2056            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2057    }
 2058
 2059    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2060    where
 2061        I: IntoIterator<Item = (Range<S>, T)>,
 2062        S: ToOffset,
 2063        T: Into<Arc<str>>,
 2064    {
 2065        if self.read_only(cx) {
 2066            return;
 2067        }
 2068
 2069        self.buffer.update(cx, |buffer, cx| {
 2070            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2071        });
 2072    }
 2073
 2074    pub fn edit_with_block_indent<I, S, T>(
 2075        &mut self,
 2076        edits: I,
 2077        original_indent_columns: Vec<u32>,
 2078        cx: &mut ViewContext<Self>,
 2079    ) where
 2080        I: IntoIterator<Item = (Range<S>, T)>,
 2081        S: ToOffset,
 2082        T: Into<Arc<str>>,
 2083    {
 2084        if self.read_only(cx) {
 2085            return;
 2086        }
 2087
 2088        self.buffer.update(cx, |buffer, cx| {
 2089            buffer.edit(
 2090                edits,
 2091                Some(AutoindentMode::Block {
 2092                    original_indent_columns,
 2093                }),
 2094                cx,
 2095            )
 2096        });
 2097    }
 2098
 2099    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2100        self.hide_context_menu(cx);
 2101
 2102        match phase {
 2103            SelectPhase::Begin {
 2104                position,
 2105                add,
 2106                click_count,
 2107            } => self.begin_selection(position, add, click_count, cx),
 2108            SelectPhase::BeginColumnar {
 2109                position,
 2110                goal_column,
 2111                reset,
 2112            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2113            SelectPhase::Extend {
 2114                position,
 2115                click_count,
 2116            } => self.extend_selection(position, click_count, cx),
 2117            SelectPhase::Update {
 2118                position,
 2119                goal_column,
 2120                scroll_delta,
 2121            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2122            SelectPhase::End => self.end_selection(cx),
 2123        }
 2124    }
 2125
 2126    fn extend_selection(
 2127        &mut self,
 2128        position: DisplayPoint,
 2129        click_count: usize,
 2130        cx: &mut ViewContext<Self>,
 2131    ) {
 2132        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2133        let tail = self.selections.newest::<usize>(cx).tail();
 2134        self.begin_selection(position, false, click_count, cx);
 2135
 2136        let position = position.to_offset(&display_map, Bias::Left);
 2137        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2138
 2139        let mut pending_selection = self
 2140            .selections
 2141            .pending_anchor()
 2142            .expect("extend_selection not called with pending selection");
 2143        if position >= tail {
 2144            pending_selection.start = tail_anchor;
 2145        } else {
 2146            pending_selection.end = tail_anchor;
 2147            pending_selection.reversed = true;
 2148        }
 2149
 2150        let mut pending_mode = self.selections.pending_mode().unwrap();
 2151        match &mut pending_mode {
 2152            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2153            _ => {}
 2154        }
 2155
 2156        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2157            s.set_pending(pending_selection, pending_mode)
 2158        });
 2159    }
 2160
 2161    fn begin_selection(
 2162        &mut self,
 2163        position: DisplayPoint,
 2164        add: bool,
 2165        click_count: usize,
 2166        cx: &mut ViewContext<Self>,
 2167    ) {
 2168        if !self.focus_handle.is_focused(cx) {
 2169            self.last_focused_descendant = None;
 2170            cx.focus(&self.focus_handle);
 2171        }
 2172
 2173        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2174        let buffer = &display_map.buffer_snapshot;
 2175        let newest_selection = self.selections.newest_anchor().clone();
 2176        let position = display_map.clip_point(position, Bias::Left);
 2177
 2178        let start;
 2179        let end;
 2180        let mode;
 2181        let mut auto_scroll;
 2182        match click_count {
 2183            1 => {
 2184                start = buffer.anchor_before(position.to_point(&display_map));
 2185                end = start;
 2186                mode = SelectMode::Character;
 2187                auto_scroll = true;
 2188            }
 2189            2 => {
 2190                let range = movement::surrounding_word(&display_map, position);
 2191                start = buffer.anchor_before(range.start.to_point(&display_map));
 2192                end = buffer.anchor_before(range.end.to_point(&display_map));
 2193                mode = SelectMode::Word(start..end);
 2194                auto_scroll = true;
 2195            }
 2196            3 => {
 2197                let position = display_map
 2198                    .clip_point(position, Bias::Left)
 2199                    .to_point(&display_map);
 2200                let line_start = display_map.prev_line_boundary(position).0;
 2201                let next_line_start = buffer.clip_point(
 2202                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2203                    Bias::Left,
 2204                );
 2205                start = buffer.anchor_before(line_start);
 2206                end = buffer.anchor_before(next_line_start);
 2207                mode = SelectMode::Line(start..end);
 2208                auto_scroll = true;
 2209            }
 2210            _ => {
 2211                start = buffer.anchor_before(0);
 2212                end = buffer.anchor_before(buffer.len());
 2213                mode = SelectMode::All;
 2214                auto_scroll = false;
 2215            }
 2216        }
 2217        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2218
 2219        let point_to_delete: Option<usize> = {
 2220            let selected_points: Vec<Selection<Point>> =
 2221                self.selections.disjoint_in_range(start..end, cx);
 2222
 2223            if !add || click_count > 1 {
 2224                None
 2225            } else if !selected_points.is_empty() {
 2226                Some(selected_points[0].id)
 2227            } else {
 2228                let clicked_point_already_selected =
 2229                    self.selections.disjoint.iter().find(|selection| {
 2230                        selection.start.to_point(buffer) == start.to_point(buffer)
 2231                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2232                    });
 2233
 2234                clicked_point_already_selected.map(|selection| selection.id)
 2235            }
 2236        };
 2237
 2238        let selections_count = self.selections.count();
 2239
 2240        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2241            if let Some(point_to_delete) = point_to_delete {
 2242                s.delete(point_to_delete);
 2243
 2244                if selections_count == 1 {
 2245                    s.set_pending_anchor_range(start..end, mode);
 2246                }
 2247            } else {
 2248                if !add {
 2249                    s.clear_disjoint();
 2250                } else if click_count > 1 {
 2251                    s.delete(newest_selection.id)
 2252                }
 2253
 2254                s.set_pending_anchor_range(start..end, mode);
 2255            }
 2256        });
 2257    }
 2258
 2259    fn begin_columnar_selection(
 2260        &mut self,
 2261        position: DisplayPoint,
 2262        goal_column: u32,
 2263        reset: bool,
 2264        cx: &mut ViewContext<Self>,
 2265    ) {
 2266        if !self.focus_handle.is_focused(cx) {
 2267            self.last_focused_descendant = None;
 2268            cx.focus(&self.focus_handle);
 2269        }
 2270
 2271        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2272
 2273        if reset {
 2274            let pointer_position = display_map
 2275                .buffer_snapshot
 2276                .anchor_before(position.to_point(&display_map));
 2277
 2278            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2279                s.clear_disjoint();
 2280                s.set_pending_anchor_range(
 2281                    pointer_position..pointer_position,
 2282                    SelectMode::Character,
 2283                );
 2284            });
 2285        }
 2286
 2287        let tail = self.selections.newest::<Point>(cx).tail();
 2288        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2289
 2290        if !reset {
 2291            self.select_columns(
 2292                tail.to_display_point(&display_map),
 2293                position,
 2294                goal_column,
 2295                &display_map,
 2296                cx,
 2297            );
 2298        }
 2299    }
 2300
 2301    fn update_selection(
 2302        &mut self,
 2303        position: DisplayPoint,
 2304        goal_column: u32,
 2305        scroll_delta: gpui::Point<f32>,
 2306        cx: &mut ViewContext<Self>,
 2307    ) {
 2308        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2309
 2310        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2311            let tail = tail.to_display_point(&display_map);
 2312            self.select_columns(tail, position, goal_column, &display_map, cx);
 2313        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2314            let buffer = self.buffer.read(cx).snapshot(cx);
 2315            let head;
 2316            let tail;
 2317            let mode = self.selections.pending_mode().unwrap();
 2318            match &mode {
 2319                SelectMode::Character => {
 2320                    head = position.to_point(&display_map);
 2321                    tail = pending.tail().to_point(&buffer);
 2322                }
 2323                SelectMode::Word(original_range) => {
 2324                    let original_display_range = original_range.start.to_display_point(&display_map)
 2325                        ..original_range.end.to_display_point(&display_map);
 2326                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2327                        ..original_display_range.end.to_point(&display_map);
 2328                    if movement::is_inside_word(&display_map, position)
 2329                        || original_display_range.contains(&position)
 2330                    {
 2331                        let word_range = movement::surrounding_word(&display_map, position);
 2332                        if word_range.start < original_display_range.start {
 2333                            head = word_range.start.to_point(&display_map);
 2334                        } else {
 2335                            head = word_range.end.to_point(&display_map);
 2336                        }
 2337                    } else {
 2338                        head = position.to_point(&display_map);
 2339                    }
 2340
 2341                    if head <= original_buffer_range.start {
 2342                        tail = original_buffer_range.end;
 2343                    } else {
 2344                        tail = original_buffer_range.start;
 2345                    }
 2346                }
 2347                SelectMode::Line(original_range) => {
 2348                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2349
 2350                    let position = display_map
 2351                        .clip_point(position, Bias::Left)
 2352                        .to_point(&display_map);
 2353                    let line_start = display_map.prev_line_boundary(position).0;
 2354                    let next_line_start = buffer.clip_point(
 2355                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2356                        Bias::Left,
 2357                    );
 2358
 2359                    if line_start < original_range.start {
 2360                        head = line_start
 2361                    } else {
 2362                        head = next_line_start
 2363                    }
 2364
 2365                    if head <= original_range.start {
 2366                        tail = original_range.end;
 2367                    } else {
 2368                        tail = original_range.start;
 2369                    }
 2370                }
 2371                SelectMode::All => {
 2372                    return;
 2373                }
 2374            };
 2375
 2376            if head < tail {
 2377                pending.start = buffer.anchor_before(head);
 2378                pending.end = buffer.anchor_before(tail);
 2379                pending.reversed = true;
 2380            } else {
 2381                pending.start = buffer.anchor_before(tail);
 2382                pending.end = buffer.anchor_before(head);
 2383                pending.reversed = false;
 2384            }
 2385
 2386            self.change_selections(None, cx, |s| {
 2387                s.set_pending(pending, mode);
 2388            });
 2389        } else {
 2390            log::error!("update_selection dispatched with no pending selection");
 2391            return;
 2392        }
 2393
 2394        self.apply_scroll_delta(scroll_delta, cx);
 2395        cx.notify();
 2396    }
 2397
 2398    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2399        self.columnar_selection_tail.take();
 2400        if self.selections.pending_anchor().is_some() {
 2401            let selections = self.selections.all::<usize>(cx);
 2402            self.change_selections(None, cx, |s| {
 2403                s.select(selections);
 2404                s.clear_pending();
 2405            });
 2406        }
 2407    }
 2408
 2409    fn select_columns(
 2410        &mut self,
 2411        tail: DisplayPoint,
 2412        head: DisplayPoint,
 2413        goal_column: u32,
 2414        display_map: &DisplaySnapshot,
 2415        cx: &mut ViewContext<Self>,
 2416    ) {
 2417        let start_row = cmp::min(tail.row(), head.row());
 2418        let end_row = cmp::max(tail.row(), head.row());
 2419        let start_column = cmp::min(tail.column(), goal_column);
 2420        let end_column = cmp::max(tail.column(), goal_column);
 2421        let reversed = start_column < tail.column();
 2422
 2423        let selection_ranges = (start_row.0..=end_row.0)
 2424            .map(DisplayRow)
 2425            .filter_map(|row| {
 2426                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2427                    let start = display_map
 2428                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2429                        .to_point(display_map);
 2430                    let end = display_map
 2431                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2432                        .to_point(display_map);
 2433                    if reversed {
 2434                        Some(end..start)
 2435                    } else {
 2436                        Some(start..end)
 2437                    }
 2438                } else {
 2439                    None
 2440                }
 2441            })
 2442            .collect::<Vec<_>>();
 2443
 2444        self.change_selections(None, cx, |s| {
 2445            s.select_ranges(selection_ranges);
 2446        });
 2447        cx.notify();
 2448    }
 2449
 2450    pub fn has_pending_nonempty_selection(&self) -> bool {
 2451        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2452            Some(Selection { start, end, .. }) => start != end,
 2453            None => false,
 2454        };
 2455
 2456        pending_nonempty_selection
 2457            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2458    }
 2459
 2460    pub fn has_pending_selection(&self) -> bool {
 2461        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2462    }
 2463
 2464    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2465        if self.clear_expanded_diff_hunks(cx) {
 2466            cx.notify();
 2467            return;
 2468        }
 2469        if self.dismiss_menus_and_popups(true, cx) {
 2470            return;
 2471        }
 2472
 2473        if self.mode == EditorMode::Full
 2474            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2475        {
 2476            return;
 2477        }
 2478
 2479        cx.propagate();
 2480    }
 2481
 2482    pub fn dismiss_menus_and_popups(
 2483        &mut self,
 2484        should_report_inline_completion_event: bool,
 2485        cx: &mut ViewContext<Self>,
 2486    ) -> bool {
 2487        if self.take_rename(false, cx).is_some() {
 2488            return true;
 2489        }
 2490
 2491        if hide_hover(self, cx) {
 2492            return true;
 2493        }
 2494
 2495        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2496            return true;
 2497        }
 2498
 2499        if self.hide_context_menu(cx).is_some() {
 2500            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2501                self.update_visible_inline_completion(cx);
 2502            }
 2503            return true;
 2504        }
 2505
 2506        if self.mouse_context_menu.take().is_some() {
 2507            return true;
 2508        }
 2509
 2510        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2511            return true;
 2512        }
 2513
 2514        if self.snippet_stack.pop().is_some() {
 2515            return true;
 2516        }
 2517
 2518        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2519            self.dismiss_diagnostics(cx);
 2520            return true;
 2521        }
 2522
 2523        false
 2524    }
 2525
 2526    fn linked_editing_ranges_for(
 2527        &self,
 2528        selection: Range<text::Anchor>,
 2529        cx: &AppContext,
 2530    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2531        if self.linked_edit_ranges.is_empty() {
 2532            return None;
 2533        }
 2534        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2535            selection.end.buffer_id.and_then(|end_buffer_id| {
 2536                if selection.start.buffer_id != Some(end_buffer_id) {
 2537                    return None;
 2538                }
 2539                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2540                let snapshot = buffer.read(cx).snapshot();
 2541                self.linked_edit_ranges
 2542                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2543                    .map(|ranges| (ranges, snapshot, buffer))
 2544            })?;
 2545        use text::ToOffset as TO;
 2546        // find offset from the start of current range to current cursor position
 2547        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2548
 2549        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2550        let start_difference = start_offset - start_byte_offset;
 2551        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2552        let end_difference = end_offset - start_byte_offset;
 2553        // Current range has associated linked ranges.
 2554        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2555        for range in linked_ranges.iter() {
 2556            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2557            let end_offset = start_offset + end_difference;
 2558            let start_offset = start_offset + start_difference;
 2559            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2560                continue;
 2561            }
 2562            if self.selections.disjoint_anchor_ranges().any(|s| {
 2563                if s.start.buffer_id != selection.start.buffer_id
 2564                    || s.end.buffer_id != selection.end.buffer_id
 2565                {
 2566                    return false;
 2567                }
 2568                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2569                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2570            }) {
 2571                continue;
 2572            }
 2573            let start = buffer_snapshot.anchor_after(start_offset);
 2574            let end = buffer_snapshot.anchor_after(end_offset);
 2575            linked_edits
 2576                .entry(buffer.clone())
 2577                .or_default()
 2578                .push(start..end);
 2579        }
 2580        Some(linked_edits)
 2581    }
 2582
 2583    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2584        let text: Arc<str> = text.into();
 2585
 2586        if self.read_only(cx) {
 2587            return;
 2588        }
 2589
 2590        let selections = self.selections.all_adjusted(cx);
 2591        let mut bracket_inserted = false;
 2592        let mut edits = Vec::new();
 2593        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2594        let mut new_selections = Vec::with_capacity(selections.len());
 2595        let mut new_autoclose_regions = Vec::new();
 2596        let snapshot = self.buffer.read(cx).read(cx);
 2597
 2598        for (selection, autoclose_region) in
 2599            self.selections_with_autoclose_regions(selections, &snapshot)
 2600        {
 2601            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2602                // Determine if the inserted text matches the opening or closing
 2603                // bracket of any of this language's bracket pairs.
 2604                let mut bracket_pair = None;
 2605                let mut is_bracket_pair_start = false;
 2606                let mut is_bracket_pair_end = false;
 2607                if !text.is_empty() {
 2608                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2609                    //  and they are removing the character that triggered IME popup.
 2610                    for (pair, enabled) in scope.brackets() {
 2611                        if !pair.close && !pair.surround {
 2612                            continue;
 2613                        }
 2614
 2615                        if enabled && pair.start.ends_with(text.as_ref()) {
 2616                            let prefix_len = pair.start.len() - text.len();
 2617                            let preceding_text_matches_prefix = prefix_len == 0
 2618                                || (selection.start.column >= (prefix_len as u32)
 2619                                    && snapshot.contains_str_at(
 2620                                        Point::new(
 2621                                            selection.start.row,
 2622                                            selection.start.column - (prefix_len as u32),
 2623                                        ),
 2624                                        &pair.start[..prefix_len],
 2625                                    ));
 2626                            if preceding_text_matches_prefix {
 2627                                bracket_pair = Some(pair.clone());
 2628                                is_bracket_pair_start = true;
 2629                                break;
 2630                            }
 2631                        }
 2632                        if pair.end.as_str() == text.as_ref() {
 2633                            bracket_pair = Some(pair.clone());
 2634                            is_bracket_pair_end = true;
 2635                            break;
 2636                        }
 2637                    }
 2638                }
 2639
 2640                if let Some(bracket_pair) = bracket_pair {
 2641                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2642                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2643                    let auto_surround =
 2644                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2645                    if selection.is_empty() {
 2646                        if is_bracket_pair_start {
 2647                            // If the inserted text is a suffix of an opening bracket and the
 2648                            // selection is preceded by the rest of the opening bracket, then
 2649                            // insert the closing bracket.
 2650                            let following_text_allows_autoclose = snapshot
 2651                                .chars_at(selection.start)
 2652                                .next()
 2653                                .map_or(true, |c| scope.should_autoclose_before(c));
 2654
 2655                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2656                                && bracket_pair.start.len() == 1
 2657                            {
 2658                                let target = bracket_pair.start.chars().next().unwrap();
 2659                                let current_line_count = snapshot
 2660                                    .reversed_chars_at(selection.start)
 2661                                    .take_while(|&c| c != '\n')
 2662                                    .filter(|&c| c == target)
 2663                                    .count();
 2664                                current_line_count % 2 == 1
 2665                            } else {
 2666                                false
 2667                            };
 2668
 2669                            if autoclose
 2670                                && bracket_pair.close
 2671                                && following_text_allows_autoclose
 2672                                && !is_closing_quote
 2673                            {
 2674                                let anchor = snapshot.anchor_before(selection.end);
 2675                                new_selections.push((selection.map(|_| anchor), text.len()));
 2676                                new_autoclose_regions.push((
 2677                                    anchor,
 2678                                    text.len(),
 2679                                    selection.id,
 2680                                    bracket_pair.clone(),
 2681                                ));
 2682                                edits.push((
 2683                                    selection.range(),
 2684                                    format!("{}{}", text, bracket_pair.end).into(),
 2685                                ));
 2686                                bracket_inserted = true;
 2687                                continue;
 2688                            }
 2689                        }
 2690
 2691                        if let Some(region) = autoclose_region {
 2692                            // If the selection is followed by an auto-inserted closing bracket,
 2693                            // then don't insert that closing bracket again; just move the selection
 2694                            // past the closing bracket.
 2695                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2696                                && text.as_ref() == region.pair.end.as_str();
 2697                            if should_skip {
 2698                                let anchor = snapshot.anchor_after(selection.end);
 2699                                new_selections
 2700                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2701                                continue;
 2702                            }
 2703                        }
 2704
 2705                        let always_treat_brackets_as_autoclosed = snapshot
 2706                            .settings_at(selection.start, cx)
 2707                            .always_treat_brackets_as_autoclosed;
 2708                        if always_treat_brackets_as_autoclosed
 2709                            && is_bracket_pair_end
 2710                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2711                        {
 2712                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2713                            // and the inserted text is a closing bracket and the selection is followed
 2714                            // by the closing bracket then move the selection past the closing bracket.
 2715                            let anchor = snapshot.anchor_after(selection.end);
 2716                            new_selections.push((selection.map(|_| anchor), text.len()));
 2717                            continue;
 2718                        }
 2719                    }
 2720                    // If an opening bracket is 1 character long and is typed while
 2721                    // text is selected, then surround that text with the bracket pair.
 2722                    else if auto_surround
 2723                        && bracket_pair.surround
 2724                        && is_bracket_pair_start
 2725                        && bracket_pair.start.chars().count() == 1
 2726                    {
 2727                        edits.push((selection.start..selection.start, text.clone()));
 2728                        edits.push((
 2729                            selection.end..selection.end,
 2730                            bracket_pair.end.as_str().into(),
 2731                        ));
 2732                        bracket_inserted = true;
 2733                        new_selections.push((
 2734                            Selection {
 2735                                id: selection.id,
 2736                                start: snapshot.anchor_after(selection.start),
 2737                                end: snapshot.anchor_before(selection.end),
 2738                                reversed: selection.reversed,
 2739                                goal: selection.goal,
 2740                            },
 2741                            0,
 2742                        ));
 2743                        continue;
 2744                    }
 2745                }
 2746            }
 2747
 2748            if self.auto_replace_emoji_shortcode
 2749                && selection.is_empty()
 2750                && text.as_ref().ends_with(':')
 2751            {
 2752                if let Some(possible_emoji_short_code) =
 2753                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2754                {
 2755                    if !possible_emoji_short_code.is_empty() {
 2756                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2757                            let emoji_shortcode_start = Point::new(
 2758                                selection.start.row,
 2759                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2760                            );
 2761
 2762                            // Remove shortcode from buffer
 2763                            edits.push((
 2764                                emoji_shortcode_start..selection.start,
 2765                                "".to_string().into(),
 2766                            ));
 2767                            new_selections.push((
 2768                                Selection {
 2769                                    id: selection.id,
 2770                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2771                                    end: snapshot.anchor_before(selection.start),
 2772                                    reversed: selection.reversed,
 2773                                    goal: selection.goal,
 2774                                },
 2775                                0,
 2776                            ));
 2777
 2778                            // Insert emoji
 2779                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2780                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2781                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2782
 2783                            continue;
 2784                        }
 2785                    }
 2786                }
 2787            }
 2788
 2789            // If not handling any auto-close operation, then just replace the selected
 2790            // text with the given input and move the selection to the end of the
 2791            // newly inserted text.
 2792            let anchor = snapshot.anchor_after(selection.end);
 2793            if !self.linked_edit_ranges.is_empty() {
 2794                let start_anchor = snapshot.anchor_before(selection.start);
 2795
 2796                let is_word_char = text.chars().next().map_or(true, |char| {
 2797                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2798                    classifier.is_word(char)
 2799                });
 2800
 2801                if is_word_char {
 2802                    if let Some(ranges) = self
 2803                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2804                    {
 2805                        for (buffer, edits) in ranges {
 2806                            linked_edits
 2807                                .entry(buffer.clone())
 2808                                .or_default()
 2809                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2810                        }
 2811                    }
 2812                }
 2813            }
 2814
 2815            new_selections.push((selection.map(|_| anchor), 0));
 2816            edits.push((selection.start..selection.end, text.clone()));
 2817        }
 2818
 2819        drop(snapshot);
 2820
 2821        self.transact(cx, |this, cx| {
 2822            this.buffer.update(cx, |buffer, cx| {
 2823                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2824            });
 2825            for (buffer, edits) in linked_edits {
 2826                buffer.update(cx, |buffer, cx| {
 2827                    let snapshot = buffer.snapshot();
 2828                    let edits = edits
 2829                        .into_iter()
 2830                        .map(|(range, text)| {
 2831                            use text::ToPoint as TP;
 2832                            let end_point = TP::to_point(&range.end, &snapshot);
 2833                            let start_point = TP::to_point(&range.start, &snapshot);
 2834                            (start_point..end_point, text)
 2835                        })
 2836                        .sorted_by_key(|(range, _)| range.start)
 2837                        .collect::<Vec<_>>();
 2838                    buffer.edit(edits, None, cx);
 2839                })
 2840            }
 2841            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2842            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2843            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2844            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2845                .zip(new_selection_deltas)
 2846                .map(|(selection, delta)| Selection {
 2847                    id: selection.id,
 2848                    start: selection.start + delta,
 2849                    end: selection.end + delta,
 2850                    reversed: selection.reversed,
 2851                    goal: SelectionGoal::None,
 2852                })
 2853                .collect::<Vec<_>>();
 2854
 2855            let mut i = 0;
 2856            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2857                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2858                let start = map.buffer_snapshot.anchor_before(position);
 2859                let end = map.buffer_snapshot.anchor_after(position);
 2860                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2861                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2862                        Ordering::Less => i += 1,
 2863                        Ordering::Greater => break,
 2864                        Ordering::Equal => {
 2865                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2866                                Ordering::Less => i += 1,
 2867                                Ordering::Equal => break,
 2868                                Ordering::Greater => break,
 2869                            }
 2870                        }
 2871                    }
 2872                }
 2873                this.autoclose_regions.insert(
 2874                    i,
 2875                    AutocloseRegion {
 2876                        selection_id,
 2877                        range: start..end,
 2878                        pair,
 2879                    },
 2880                );
 2881            }
 2882
 2883            let had_active_inline_completion = this.has_active_inline_completion();
 2884            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2885                s.select(new_selections)
 2886            });
 2887
 2888            if !bracket_inserted {
 2889                if let Some(on_type_format_task) =
 2890                    this.trigger_on_type_formatting(text.to_string(), cx)
 2891                {
 2892                    on_type_format_task.detach_and_log_err(cx);
 2893                }
 2894            }
 2895
 2896            let editor_settings = EditorSettings::get_global(cx);
 2897            if bracket_inserted
 2898                && (editor_settings.auto_signature_help
 2899                    || editor_settings.show_signature_help_after_edits)
 2900            {
 2901                this.show_signature_help(&ShowSignatureHelp, cx);
 2902            }
 2903
 2904            let trigger_in_words =
 2905                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2906            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2907            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2908            this.refresh_inline_completion(true, false, cx);
 2909        });
 2910    }
 2911
 2912    fn find_possible_emoji_shortcode_at_position(
 2913        snapshot: &MultiBufferSnapshot,
 2914        position: Point,
 2915    ) -> Option<String> {
 2916        let mut chars = Vec::new();
 2917        let mut found_colon = false;
 2918        for char in snapshot.reversed_chars_at(position).take(100) {
 2919            // Found a possible emoji shortcode in the middle of the buffer
 2920            if found_colon {
 2921                if char.is_whitespace() {
 2922                    chars.reverse();
 2923                    return Some(chars.iter().collect());
 2924                }
 2925                // If the previous character is not a whitespace, we are in the middle of a word
 2926                // and we only want to complete the shortcode if the word is made up of other emojis
 2927                let mut containing_word = String::new();
 2928                for ch in snapshot
 2929                    .reversed_chars_at(position)
 2930                    .skip(chars.len() + 1)
 2931                    .take(100)
 2932                {
 2933                    if ch.is_whitespace() {
 2934                        break;
 2935                    }
 2936                    containing_word.push(ch);
 2937                }
 2938                let containing_word = containing_word.chars().rev().collect::<String>();
 2939                if util::word_consists_of_emojis(containing_word.as_str()) {
 2940                    chars.reverse();
 2941                    return Some(chars.iter().collect());
 2942                }
 2943            }
 2944
 2945            if char.is_whitespace() || !char.is_ascii() {
 2946                return None;
 2947            }
 2948            if char == ':' {
 2949                found_colon = true;
 2950            } else {
 2951                chars.push(char);
 2952            }
 2953        }
 2954        // Found a possible emoji shortcode at the beginning of the buffer
 2955        chars.reverse();
 2956        Some(chars.iter().collect())
 2957    }
 2958
 2959    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2960        self.transact(cx, |this, cx| {
 2961            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2962                let selections = this.selections.all::<usize>(cx);
 2963                let multi_buffer = this.buffer.read(cx);
 2964                let buffer = multi_buffer.snapshot(cx);
 2965                selections
 2966                    .iter()
 2967                    .map(|selection| {
 2968                        let start_point = selection.start.to_point(&buffer);
 2969                        let mut indent =
 2970                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2971                        indent.len = cmp::min(indent.len, start_point.column);
 2972                        let start = selection.start;
 2973                        let end = selection.end;
 2974                        let selection_is_empty = start == end;
 2975                        let language_scope = buffer.language_scope_at(start);
 2976                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2977                            &language_scope
 2978                        {
 2979                            let leading_whitespace_len = buffer
 2980                                .reversed_chars_at(start)
 2981                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2982                                .map(|c| c.len_utf8())
 2983                                .sum::<usize>();
 2984
 2985                            let trailing_whitespace_len = buffer
 2986                                .chars_at(end)
 2987                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2988                                .map(|c| c.len_utf8())
 2989                                .sum::<usize>();
 2990
 2991                            let insert_extra_newline =
 2992                                language.brackets().any(|(pair, enabled)| {
 2993                                    let pair_start = pair.start.trim_end();
 2994                                    let pair_end = pair.end.trim_start();
 2995
 2996                                    enabled
 2997                                        && pair.newline
 2998                                        && buffer.contains_str_at(
 2999                                            end + trailing_whitespace_len,
 3000                                            pair_end,
 3001                                        )
 3002                                        && buffer.contains_str_at(
 3003                                            (start - leading_whitespace_len)
 3004                                                .saturating_sub(pair_start.len()),
 3005                                            pair_start,
 3006                                        )
 3007                                });
 3008
 3009                            // Comment extension on newline is allowed only for cursor selections
 3010                            let comment_delimiter = maybe!({
 3011                                if !selection_is_empty {
 3012                                    return None;
 3013                                }
 3014
 3015                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3016                                    return None;
 3017                                }
 3018
 3019                                let delimiters = language.line_comment_prefixes();
 3020                                let max_len_of_delimiter =
 3021                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3022                                let (snapshot, range) =
 3023                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3024
 3025                                let mut index_of_first_non_whitespace = 0;
 3026                                let comment_candidate = snapshot
 3027                                    .chars_for_range(range)
 3028                                    .skip_while(|c| {
 3029                                        let should_skip = c.is_whitespace();
 3030                                        if should_skip {
 3031                                            index_of_first_non_whitespace += 1;
 3032                                        }
 3033                                        should_skip
 3034                                    })
 3035                                    .take(max_len_of_delimiter)
 3036                                    .collect::<String>();
 3037                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3038                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3039                                })?;
 3040                                let cursor_is_placed_after_comment_marker =
 3041                                    index_of_first_non_whitespace + comment_prefix.len()
 3042                                        <= start_point.column as usize;
 3043                                if cursor_is_placed_after_comment_marker {
 3044                                    Some(comment_prefix.clone())
 3045                                } else {
 3046                                    None
 3047                                }
 3048                            });
 3049                            (comment_delimiter, insert_extra_newline)
 3050                        } else {
 3051                            (None, false)
 3052                        };
 3053
 3054                        let capacity_for_delimiter = comment_delimiter
 3055                            .as_deref()
 3056                            .map(str::len)
 3057                            .unwrap_or_default();
 3058                        let mut new_text =
 3059                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3060                        new_text.push('\n');
 3061                        new_text.extend(indent.chars());
 3062                        if let Some(delimiter) = &comment_delimiter {
 3063                            new_text.push_str(delimiter);
 3064                        }
 3065                        if insert_extra_newline {
 3066                            new_text = new_text.repeat(2);
 3067                        }
 3068
 3069                        let anchor = buffer.anchor_after(end);
 3070                        let new_selection = selection.map(|_| anchor);
 3071                        (
 3072                            (start..end, new_text),
 3073                            (insert_extra_newline, new_selection),
 3074                        )
 3075                    })
 3076                    .unzip()
 3077            };
 3078
 3079            this.edit_with_autoindent(edits, cx);
 3080            let buffer = this.buffer.read(cx).snapshot(cx);
 3081            let new_selections = selection_fixup_info
 3082                .into_iter()
 3083                .map(|(extra_newline_inserted, new_selection)| {
 3084                    let mut cursor = new_selection.end.to_point(&buffer);
 3085                    if extra_newline_inserted {
 3086                        cursor.row -= 1;
 3087                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3088                    }
 3089                    new_selection.map(|_| cursor)
 3090                })
 3091                .collect();
 3092
 3093            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3094            this.refresh_inline_completion(true, false, cx);
 3095        });
 3096    }
 3097
 3098    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3099        let buffer = self.buffer.read(cx);
 3100        let snapshot = buffer.snapshot(cx);
 3101
 3102        let mut edits = Vec::new();
 3103        let mut rows = Vec::new();
 3104
 3105        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3106            let cursor = selection.head();
 3107            let row = cursor.row;
 3108
 3109            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3110
 3111            let newline = "\n".to_string();
 3112            edits.push((start_of_line..start_of_line, newline));
 3113
 3114            rows.push(row + rows_inserted as u32);
 3115        }
 3116
 3117        self.transact(cx, |editor, cx| {
 3118            editor.edit(edits, cx);
 3119
 3120            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3121                let mut index = 0;
 3122                s.move_cursors_with(|map, _, _| {
 3123                    let row = rows[index];
 3124                    index += 1;
 3125
 3126                    let point = Point::new(row, 0);
 3127                    let boundary = map.next_line_boundary(point).1;
 3128                    let clipped = map.clip_point(boundary, Bias::Left);
 3129
 3130                    (clipped, SelectionGoal::None)
 3131                });
 3132            });
 3133
 3134            let mut indent_edits = Vec::new();
 3135            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3136            for row in rows {
 3137                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3138                for (row, indent) in indents {
 3139                    if indent.len == 0 {
 3140                        continue;
 3141                    }
 3142
 3143                    let text = match indent.kind {
 3144                        IndentKind::Space => " ".repeat(indent.len as usize),
 3145                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3146                    };
 3147                    let point = Point::new(row.0, 0);
 3148                    indent_edits.push((point..point, text));
 3149                }
 3150            }
 3151            editor.edit(indent_edits, cx);
 3152        });
 3153    }
 3154
 3155    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3156        let buffer = self.buffer.read(cx);
 3157        let snapshot = buffer.snapshot(cx);
 3158
 3159        let mut edits = Vec::new();
 3160        let mut rows = Vec::new();
 3161        let mut rows_inserted = 0;
 3162
 3163        for selection in self.selections.all_adjusted(cx) {
 3164            let cursor = selection.head();
 3165            let row = cursor.row;
 3166
 3167            let point = Point::new(row + 1, 0);
 3168            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3169
 3170            let newline = "\n".to_string();
 3171            edits.push((start_of_line..start_of_line, newline));
 3172
 3173            rows_inserted += 1;
 3174            rows.push(row + rows_inserted);
 3175        }
 3176
 3177        self.transact(cx, |editor, cx| {
 3178            editor.edit(edits, cx);
 3179
 3180            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3181                let mut index = 0;
 3182                s.move_cursors_with(|map, _, _| {
 3183                    let row = rows[index];
 3184                    index += 1;
 3185
 3186                    let point = Point::new(row, 0);
 3187                    let boundary = map.next_line_boundary(point).1;
 3188                    let clipped = map.clip_point(boundary, Bias::Left);
 3189
 3190                    (clipped, SelectionGoal::None)
 3191                });
 3192            });
 3193
 3194            let mut indent_edits = Vec::new();
 3195            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3196            for row in rows {
 3197                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3198                for (row, indent) in indents {
 3199                    if indent.len == 0 {
 3200                        continue;
 3201                    }
 3202
 3203                    let text = match indent.kind {
 3204                        IndentKind::Space => " ".repeat(indent.len as usize),
 3205                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3206                    };
 3207                    let point = Point::new(row.0, 0);
 3208                    indent_edits.push((point..point, text));
 3209                }
 3210            }
 3211            editor.edit(indent_edits, cx);
 3212        });
 3213    }
 3214
 3215    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3216        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3217            original_indent_columns: Vec::new(),
 3218        });
 3219        self.insert_with_autoindent_mode(text, autoindent, cx);
 3220    }
 3221
 3222    fn insert_with_autoindent_mode(
 3223        &mut self,
 3224        text: &str,
 3225        autoindent_mode: Option<AutoindentMode>,
 3226        cx: &mut ViewContext<Self>,
 3227    ) {
 3228        if self.read_only(cx) {
 3229            return;
 3230        }
 3231
 3232        let text: Arc<str> = text.into();
 3233        self.transact(cx, |this, cx| {
 3234            let old_selections = this.selections.all_adjusted(cx);
 3235            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3236                let anchors = {
 3237                    let snapshot = buffer.read(cx);
 3238                    old_selections
 3239                        .iter()
 3240                        .map(|s| {
 3241                            let anchor = snapshot.anchor_after(s.head());
 3242                            s.map(|_| anchor)
 3243                        })
 3244                        .collect::<Vec<_>>()
 3245                };
 3246                buffer.edit(
 3247                    old_selections
 3248                        .iter()
 3249                        .map(|s| (s.start..s.end, text.clone())),
 3250                    autoindent_mode,
 3251                    cx,
 3252                );
 3253                anchors
 3254            });
 3255
 3256            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3257                s.select_anchors(selection_anchors);
 3258            })
 3259        });
 3260    }
 3261
 3262    fn trigger_completion_on_input(
 3263        &mut self,
 3264        text: &str,
 3265        trigger_in_words: bool,
 3266        cx: &mut ViewContext<Self>,
 3267    ) {
 3268        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3269            self.show_completions(
 3270                &ShowCompletions {
 3271                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3272                },
 3273                cx,
 3274            );
 3275        } else {
 3276            self.hide_context_menu(cx);
 3277        }
 3278    }
 3279
 3280    fn is_completion_trigger(
 3281        &self,
 3282        text: &str,
 3283        trigger_in_words: bool,
 3284        cx: &mut ViewContext<Self>,
 3285    ) -> bool {
 3286        let position = self.selections.newest_anchor().head();
 3287        let multibuffer = self.buffer.read(cx);
 3288        let Some(buffer) = position
 3289            .buffer_id
 3290            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3291        else {
 3292            return false;
 3293        };
 3294
 3295        if let Some(completion_provider) = &self.completion_provider {
 3296            completion_provider.is_completion_trigger(
 3297                &buffer,
 3298                position.text_anchor,
 3299                text,
 3300                trigger_in_words,
 3301                cx,
 3302            )
 3303        } else {
 3304            false
 3305        }
 3306    }
 3307
 3308    /// If any empty selections is touching the start of its innermost containing autoclose
 3309    /// region, expand it to select the brackets.
 3310    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3311        let selections = self.selections.all::<usize>(cx);
 3312        let buffer = self.buffer.read(cx).read(cx);
 3313        let new_selections = self
 3314            .selections_with_autoclose_regions(selections, &buffer)
 3315            .map(|(mut selection, region)| {
 3316                if !selection.is_empty() {
 3317                    return selection;
 3318                }
 3319
 3320                if let Some(region) = region {
 3321                    let mut range = region.range.to_offset(&buffer);
 3322                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3323                        range.start -= region.pair.start.len();
 3324                        if buffer.contains_str_at(range.start, &region.pair.start)
 3325                            && buffer.contains_str_at(range.end, &region.pair.end)
 3326                        {
 3327                            range.end += region.pair.end.len();
 3328                            selection.start = range.start;
 3329                            selection.end = range.end;
 3330
 3331                            return selection;
 3332                        }
 3333                    }
 3334                }
 3335
 3336                let always_treat_brackets_as_autoclosed = buffer
 3337                    .settings_at(selection.start, cx)
 3338                    .always_treat_brackets_as_autoclosed;
 3339
 3340                if !always_treat_brackets_as_autoclosed {
 3341                    return selection;
 3342                }
 3343
 3344                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3345                    for (pair, enabled) in scope.brackets() {
 3346                        if !enabled || !pair.close {
 3347                            continue;
 3348                        }
 3349
 3350                        if buffer.contains_str_at(selection.start, &pair.end) {
 3351                            let pair_start_len = pair.start.len();
 3352                            if buffer.contains_str_at(
 3353                                selection.start.saturating_sub(pair_start_len),
 3354                                &pair.start,
 3355                            ) {
 3356                                selection.start -= pair_start_len;
 3357                                selection.end += pair.end.len();
 3358
 3359                                return selection;
 3360                            }
 3361                        }
 3362                    }
 3363                }
 3364
 3365                selection
 3366            })
 3367            .collect();
 3368
 3369        drop(buffer);
 3370        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3371    }
 3372
 3373    /// Iterate the given selections, and for each one, find the smallest surrounding
 3374    /// autoclose region. This uses the ordering of the selections and the autoclose
 3375    /// regions to avoid repeated comparisons.
 3376    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3377        &'a self,
 3378        selections: impl IntoIterator<Item = Selection<D>>,
 3379        buffer: &'a MultiBufferSnapshot,
 3380    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3381        let mut i = 0;
 3382        let mut regions = self.autoclose_regions.as_slice();
 3383        selections.into_iter().map(move |selection| {
 3384            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3385
 3386            let mut enclosing = None;
 3387            while let Some(pair_state) = regions.get(i) {
 3388                if pair_state.range.end.to_offset(buffer) < range.start {
 3389                    regions = &regions[i + 1..];
 3390                    i = 0;
 3391                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3392                    break;
 3393                } else {
 3394                    if pair_state.selection_id == selection.id {
 3395                        enclosing = Some(pair_state);
 3396                    }
 3397                    i += 1;
 3398                }
 3399            }
 3400
 3401            (selection, enclosing)
 3402        })
 3403    }
 3404
 3405    /// Remove any autoclose regions that no longer contain their selection.
 3406    fn invalidate_autoclose_regions(
 3407        &mut self,
 3408        mut selections: &[Selection<Anchor>],
 3409        buffer: &MultiBufferSnapshot,
 3410    ) {
 3411        self.autoclose_regions.retain(|state| {
 3412            let mut i = 0;
 3413            while let Some(selection) = selections.get(i) {
 3414                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3415                    selections = &selections[1..];
 3416                    continue;
 3417                }
 3418                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3419                    break;
 3420                }
 3421                if selection.id == state.selection_id {
 3422                    return true;
 3423                } else {
 3424                    i += 1;
 3425                }
 3426            }
 3427            false
 3428        });
 3429    }
 3430
 3431    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3432        let offset = position.to_offset(buffer);
 3433        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3434        if offset > word_range.start && kind == Some(CharKind::Word) {
 3435            Some(
 3436                buffer
 3437                    .text_for_range(word_range.start..offset)
 3438                    .collect::<String>(),
 3439            )
 3440        } else {
 3441            None
 3442        }
 3443    }
 3444
 3445    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3446        self.refresh_inlay_hints(
 3447            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3448            cx,
 3449        );
 3450    }
 3451
 3452    pub fn inlay_hints_enabled(&self) -> bool {
 3453        self.inlay_hint_cache.enabled
 3454    }
 3455
 3456    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3457        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3458            return;
 3459        }
 3460
 3461        let reason_description = reason.description();
 3462        let ignore_debounce = matches!(
 3463            reason,
 3464            InlayHintRefreshReason::SettingsChange(_)
 3465                | InlayHintRefreshReason::Toggle(_)
 3466                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3467        );
 3468        let (invalidate_cache, required_languages) = match reason {
 3469            InlayHintRefreshReason::Toggle(enabled) => {
 3470                self.inlay_hint_cache.enabled = enabled;
 3471                if enabled {
 3472                    (InvalidationStrategy::RefreshRequested, None)
 3473                } else {
 3474                    self.inlay_hint_cache.clear();
 3475                    self.splice_inlays(
 3476                        self.visible_inlay_hints(cx)
 3477                            .iter()
 3478                            .map(|inlay| inlay.id)
 3479                            .collect(),
 3480                        Vec::new(),
 3481                        cx,
 3482                    );
 3483                    return;
 3484                }
 3485            }
 3486            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3487                match self.inlay_hint_cache.update_settings(
 3488                    &self.buffer,
 3489                    new_settings,
 3490                    self.visible_inlay_hints(cx),
 3491                    cx,
 3492                ) {
 3493                    ControlFlow::Break(Some(InlaySplice {
 3494                        to_remove,
 3495                        to_insert,
 3496                    })) => {
 3497                        self.splice_inlays(to_remove, to_insert, cx);
 3498                        return;
 3499                    }
 3500                    ControlFlow::Break(None) => return,
 3501                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3502                }
 3503            }
 3504            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3505                if let Some(InlaySplice {
 3506                    to_remove,
 3507                    to_insert,
 3508                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3509                {
 3510                    self.splice_inlays(to_remove, to_insert, cx);
 3511                }
 3512                return;
 3513            }
 3514            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3515            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3516                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3517            }
 3518            InlayHintRefreshReason::RefreshRequested => {
 3519                (InvalidationStrategy::RefreshRequested, None)
 3520            }
 3521        };
 3522
 3523        if let Some(InlaySplice {
 3524            to_remove,
 3525            to_insert,
 3526        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3527            reason_description,
 3528            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3529            invalidate_cache,
 3530            ignore_debounce,
 3531            cx,
 3532        ) {
 3533            self.splice_inlays(to_remove, to_insert, cx);
 3534        }
 3535    }
 3536
 3537    fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
 3538        self.display_map
 3539            .read(cx)
 3540            .current_inlays()
 3541            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3542            .cloned()
 3543            .collect()
 3544    }
 3545
 3546    pub fn excerpts_for_inlay_hints_query(
 3547        &self,
 3548        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3549        cx: &mut ViewContext<Editor>,
 3550    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3551        let Some(project) = self.project.as_ref() else {
 3552            return HashMap::default();
 3553        };
 3554        let project = project.read(cx);
 3555        let multi_buffer = self.buffer().read(cx);
 3556        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3557        let multi_buffer_visible_start = self
 3558            .scroll_manager
 3559            .anchor()
 3560            .anchor
 3561            .to_point(&multi_buffer_snapshot);
 3562        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3563            multi_buffer_visible_start
 3564                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3565            Bias::Left,
 3566        );
 3567        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3568        multi_buffer_snapshot
 3569            .range_to_buffer_ranges(multi_buffer_visible_range)
 3570            .into_iter()
 3571            .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
 3572            .filter_map(|(excerpt, excerpt_visible_range)| {
 3573                let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
 3574                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3575                let worktree_entry = buffer_worktree
 3576                    .read(cx)
 3577                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3578                if worktree_entry.is_ignored {
 3579                    return None;
 3580                }
 3581
 3582                let language = excerpt.buffer().language()?;
 3583                if let Some(restrict_to_languages) = restrict_to_languages {
 3584                    if !restrict_to_languages.contains(language) {
 3585                        return None;
 3586                    }
 3587                }
 3588                Some((
 3589                    excerpt.id(),
 3590                    (
 3591                        multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
 3592                        excerpt.buffer().version().clone(),
 3593                        excerpt_visible_range,
 3594                    ),
 3595                ))
 3596            })
 3597            .collect()
 3598    }
 3599
 3600    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3601        TextLayoutDetails {
 3602            text_system: cx.text_system().clone(),
 3603            editor_style: self.style.clone().unwrap(),
 3604            rem_size: cx.rem_size(),
 3605            scroll_anchor: self.scroll_manager.anchor(),
 3606            visible_rows: self.visible_line_count(),
 3607            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3608        }
 3609    }
 3610
 3611    pub fn splice_inlays(
 3612        &self,
 3613        to_remove: Vec<InlayId>,
 3614        to_insert: Vec<Inlay>,
 3615        cx: &mut ViewContext<Self>,
 3616    ) {
 3617        self.display_map.update(cx, |display_map, cx| {
 3618            display_map.splice_inlays(to_remove, to_insert, cx)
 3619        });
 3620        cx.notify();
 3621    }
 3622
 3623    fn trigger_on_type_formatting(
 3624        &self,
 3625        input: String,
 3626        cx: &mut ViewContext<Self>,
 3627    ) -> Option<Task<Result<()>>> {
 3628        if input.len() != 1 {
 3629            return None;
 3630        }
 3631
 3632        let project = self.project.as_ref()?;
 3633        let position = self.selections.newest_anchor().head();
 3634        let (buffer, buffer_position) = self
 3635            .buffer
 3636            .read(cx)
 3637            .text_anchor_for_position(position, cx)?;
 3638
 3639        let settings = language_settings::language_settings(
 3640            buffer
 3641                .read(cx)
 3642                .language_at(buffer_position)
 3643                .map(|l| l.name()),
 3644            buffer.read(cx).file(),
 3645            cx,
 3646        );
 3647        if !settings.use_on_type_format {
 3648            return None;
 3649        }
 3650
 3651        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3652        // hence we do LSP request & edit on host side only — add formats to host's history.
 3653        let push_to_lsp_host_history = true;
 3654        // If this is not the host, append its history with new edits.
 3655        let push_to_client_history = project.read(cx).is_via_collab();
 3656
 3657        let on_type_formatting = project.update(cx, |project, cx| {
 3658            project.on_type_format(
 3659                buffer.clone(),
 3660                buffer_position,
 3661                input,
 3662                push_to_lsp_host_history,
 3663                cx,
 3664            )
 3665        });
 3666        Some(cx.spawn(|editor, mut cx| async move {
 3667            if let Some(transaction) = on_type_formatting.await? {
 3668                if push_to_client_history {
 3669                    buffer
 3670                        .update(&mut cx, |buffer, _| {
 3671                            buffer.push_transaction(transaction, Instant::now());
 3672                        })
 3673                        .ok();
 3674                }
 3675                editor.update(&mut cx, |editor, cx| {
 3676                    editor.refresh_document_highlights(cx);
 3677                })?;
 3678            }
 3679            Ok(())
 3680        }))
 3681    }
 3682
 3683    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3684        if self.pending_rename.is_some() {
 3685            return;
 3686        }
 3687
 3688        let Some(provider) = self.completion_provider.as_ref() else {
 3689            return;
 3690        };
 3691
 3692        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3693            return;
 3694        }
 3695
 3696        let position = self.selections.newest_anchor().head();
 3697        let (buffer, buffer_position) =
 3698            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3699                output
 3700            } else {
 3701                return;
 3702            };
 3703        let show_completion_documentation = buffer
 3704            .read(cx)
 3705            .snapshot()
 3706            .settings_at(buffer_position, cx)
 3707            .show_completion_documentation;
 3708
 3709        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3710
 3711        let trigger_kind = match &options.trigger {
 3712            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3713                CompletionTriggerKind::TRIGGER_CHARACTER
 3714            }
 3715            _ => CompletionTriggerKind::INVOKED,
 3716        };
 3717        let completion_context = CompletionContext {
 3718            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3719                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3720                    Some(String::from(trigger))
 3721                } else {
 3722                    None
 3723                }
 3724            }),
 3725            trigger_kind,
 3726        };
 3727        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3728        let sort_completions = provider.sort_completions();
 3729
 3730        let id = post_inc(&mut self.next_completion_id);
 3731        let task = cx.spawn(|editor, mut cx| {
 3732            async move {
 3733                editor.update(&mut cx, |this, _| {
 3734                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3735                })?;
 3736                let completions = completions.await.log_err();
 3737                let menu = if let Some(completions) = completions {
 3738                    let mut menu = CompletionsMenu::new(
 3739                        id,
 3740                        sort_completions,
 3741                        show_completion_documentation,
 3742                        position,
 3743                        buffer.clone(),
 3744                        completions.into(),
 3745                    );
 3746
 3747                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3748                        .await;
 3749
 3750                    menu.visible().then_some(menu)
 3751                } else {
 3752                    None
 3753                };
 3754
 3755                editor.update(&mut cx, |editor, cx| {
 3756                    match editor.context_menu.borrow().as_ref() {
 3757                        None => {}
 3758                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3759                            if prev_menu.id > id {
 3760                                return;
 3761                            }
 3762                        }
 3763                        _ => return,
 3764                    }
 3765
 3766                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3767                        let mut menu = menu.unwrap();
 3768                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3769
 3770                        if editor.show_inline_completions_in_menu(cx) {
 3771                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3772                                menu.show_inline_completion_hint(hint);
 3773                            }
 3774                        } else {
 3775                            editor.discard_inline_completion(false, cx);
 3776                        }
 3777
 3778                        *editor.context_menu.borrow_mut() =
 3779                            Some(CodeContextMenu::Completions(menu));
 3780
 3781                        cx.notify();
 3782                    } else if editor.completion_tasks.len() <= 1 {
 3783                        // If there are no more completion tasks and the last menu was
 3784                        // empty, we should hide it.
 3785                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3786                        // If it was already hidden and we don't show inline
 3787                        // completions in the menu, we should also show the
 3788                        // inline-completion when available.
 3789                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3790                            editor.update_visible_inline_completion(cx);
 3791                        }
 3792                    }
 3793                })?;
 3794
 3795                Ok::<_, anyhow::Error>(())
 3796            }
 3797            .log_err()
 3798        });
 3799
 3800        self.completion_tasks.push((id, task));
 3801    }
 3802
 3803    pub fn confirm_completion(
 3804        &mut self,
 3805        action: &ConfirmCompletion,
 3806        cx: &mut ViewContext<Self>,
 3807    ) -> Option<Task<Result<()>>> {
 3808        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3809    }
 3810
 3811    pub fn compose_completion(
 3812        &mut self,
 3813        action: &ComposeCompletion,
 3814        cx: &mut ViewContext<Self>,
 3815    ) -> Option<Task<Result<()>>> {
 3816        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3817    }
 3818
 3819    fn do_completion(
 3820        &mut self,
 3821        item_ix: Option<usize>,
 3822        intent: CompletionIntent,
 3823        cx: &mut ViewContext<Editor>,
 3824    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3825        use language::ToOffset as _;
 3826
 3827        let completions_menu =
 3828            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3829                menu
 3830            } else {
 3831                return None;
 3832            };
 3833
 3834        let entries = completions_menu.entries.borrow();
 3835        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3836        let mat = match mat {
 3837            CompletionEntry::InlineCompletionHint { .. } => {
 3838                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3839                cx.stop_propagation();
 3840                return Some(Task::ready(Ok(())));
 3841            }
 3842            CompletionEntry::Match(mat) => {
 3843                if self.show_inline_completions_in_menu(cx) {
 3844                    self.discard_inline_completion(true, cx);
 3845                }
 3846                mat
 3847            }
 3848        };
 3849        let candidate_id = mat.candidate_id;
 3850        drop(entries);
 3851
 3852        let buffer_handle = completions_menu.buffer;
 3853        let completion = completions_menu
 3854            .completions
 3855            .borrow()
 3856            .get(candidate_id)?
 3857            .clone();
 3858        cx.stop_propagation();
 3859
 3860        let snippet;
 3861        let text;
 3862
 3863        if completion.is_snippet() {
 3864            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3865            text = snippet.as_ref().unwrap().text.clone();
 3866        } else {
 3867            snippet = None;
 3868            text = completion.new_text.clone();
 3869        };
 3870        let selections = self.selections.all::<usize>(cx);
 3871        let buffer = buffer_handle.read(cx);
 3872        let old_range = completion.old_range.to_offset(buffer);
 3873        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3874
 3875        let newest_selection = self.selections.newest_anchor();
 3876        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3877            return None;
 3878        }
 3879
 3880        let lookbehind = newest_selection
 3881            .start
 3882            .text_anchor
 3883            .to_offset(buffer)
 3884            .saturating_sub(old_range.start);
 3885        let lookahead = old_range
 3886            .end
 3887            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3888        let mut common_prefix_len = old_text
 3889            .bytes()
 3890            .zip(text.bytes())
 3891            .take_while(|(a, b)| a == b)
 3892            .count();
 3893
 3894        let snapshot = self.buffer.read(cx).snapshot(cx);
 3895        let mut range_to_replace: Option<Range<isize>> = None;
 3896        let mut ranges = Vec::new();
 3897        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3898        for selection in &selections {
 3899            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3900                let start = selection.start.saturating_sub(lookbehind);
 3901                let end = selection.end + lookahead;
 3902                if selection.id == newest_selection.id {
 3903                    range_to_replace = Some(
 3904                        ((start + common_prefix_len) as isize - selection.start as isize)
 3905                            ..(end as isize - selection.start as isize),
 3906                    );
 3907                }
 3908                ranges.push(start + common_prefix_len..end);
 3909            } else {
 3910                common_prefix_len = 0;
 3911                ranges.clear();
 3912                ranges.extend(selections.iter().map(|s| {
 3913                    if s.id == newest_selection.id {
 3914                        range_to_replace = Some(
 3915                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3916                                - selection.start as isize
 3917                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3918                                    - selection.start as isize,
 3919                        );
 3920                        old_range.clone()
 3921                    } else {
 3922                        s.start..s.end
 3923                    }
 3924                }));
 3925                break;
 3926            }
 3927            if !self.linked_edit_ranges.is_empty() {
 3928                let start_anchor = snapshot.anchor_before(selection.head());
 3929                let end_anchor = snapshot.anchor_after(selection.tail());
 3930                if let Some(ranges) = self
 3931                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3932                {
 3933                    for (buffer, edits) in ranges {
 3934                        linked_edits.entry(buffer.clone()).or_default().extend(
 3935                            edits
 3936                                .into_iter()
 3937                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3938                        );
 3939                    }
 3940                }
 3941            }
 3942        }
 3943        let text = &text[common_prefix_len..];
 3944
 3945        cx.emit(EditorEvent::InputHandled {
 3946            utf16_range_to_replace: range_to_replace,
 3947            text: text.into(),
 3948        });
 3949
 3950        self.transact(cx, |this, cx| {
 3951            if let Some(mut snippet) = snippet {
 3952                snippet.text = text.to_string();
 3953                for tabstop in snippet
 3954                    .tabstops
 3955                    .iter_mut()
 3956                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3957                {
 3958                    tabstop.start -= common_prefix_len as isize;
 3959                    tabstop.end -= common_prefix_len as isize;
 3960                }
 3961
 3962                this.insert_snippet(&ranges, snippet, cx).log_err();
 3963            } else {
 3964                this.buffer.update(cx, |buffer, cx| {
 3965                    buffer.edit(
 3966                        ranges.iter().map(|range| (range.clone(), text)),
 3967                        this.autoindent_mode.clone(),
 3968                        cx,
 3969                    );
 3970                });
 3971            }
 3972            for (buffer, edits) in linked_edits {
 3973                buffer.update(cx, |buffer, cx| {
 3974                    let snapshot = buffer.snapshot();
 3975                    let edits = edits
 3976                        .into_iter()
 3977                        .map(|(range, text)| {
 3978                            use text::ToPoint as TP;
 3979                            let end_point = TP::to_point(&range.end, &snapshot);
 3980                            let start_point = TP::to_point(&range.start, &snapshot);
 3981                            (start_point..end_point, text)
 3982                        })
 3983                        .sorted_by_key(|(range, _)| range.start)
 3984                        .collect::<Vec<_>>();
 3985                    buffer.edit(edits, None, cx);
 3986                })
 3987            }
 3988
 3989            this.refresh_inline_completion(true, false, cx);
 3990        });
 3991
 3992        let show_new_completions_on_confirm = completion
 3993            .confirm
 3994            .as_ref()
 3995            .map_or(false, |confirm| confirm(intent, cx));
 3996        if show_new_completions_on_confirm {
 3997            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3998        }
 3999
 4000        let provider = self.completion_provider.as_ref()?;
 4001        drop(completion);
 4002        let apply_edits = provider.apply_additional_edits_for_completion(
 4003            buffer_handle,
 4004            completions_menu.completions.clone(),
 4005            candidate_id,
 4006            true,
 4007            cx,
 4008        );
 4009
 4010        let editor_settings = EditorSettings::get_global(cx);
 4011        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4012            // After the code completion is finished, users often want to know what signatures are needed.
 4013            // so we should automatically call signature_help
 4014            self.show_signature_help(&ShowSignatureHelp, cx);
 4015        }
 4016
 4017        Some(cx.foreground_executor().spawn(async move {
 4018            apply_edits.await?;
 4019            Ok(())
 4020        }))
 4021    }
 4022
 4023    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4024        let mut context_menu = self.context_menu.borrow_mut();
 4025        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4026            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4027                // Toggle if we're selecting the same one
 4028                *context_menu = None;
 4029                cx.notify();
 4030                return;
 4031            } else {
 4032                // Otherwise, clear it and start a new one
 4033                *context_menu = None;
 4034                cx.notify();
 4035            }
 4036        }
 4037        drop(context_menu);
 4038        let snapshot = self.snapshot(cx);
 4039        let deployed_from_indicator = action.deployed_from_indicator;
 4040        let mut task = self.code_actions_task.take();
 4041        let action = action.clone();
 4042        cx.spawn(|editor, mut cx| async move {
 4043            while let Some(prev_task) = task {
 4044                prev_task.await.log_err();
 4045                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4046            }
 4047
 4048            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4049                if editor.focus_handle.is_focused(cx) {
 4050                    let multibuffer_point = action
 4051                        .deployed_from_indicator
 4052                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4053                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4054                    let (buffer, buffer_row) = snapshot
 4055                        .buffer_snapshot
 4056                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4057                        .and_then(|(buffer_snapshot, range)| {
 4058                            editor
 4059                                .buffer
 4060                                .read(cx)
 4061                                .buffer(buffer_snapshot.remote_id())
 4062                                .map(|buffer| (buffer, range.start.row))
 4063                        })?;
 4064                    let (_, code_actions) = editor
 4065                        .available_code_actions
 4066                        .clone()
 4067                        .and_then(|(location, code_actions)| {
 4068                            let snapshot = location.buffer.read(cx).snapshot();
 4069                            let point_range = location.range.to_point(&snapshot);
 4070                            let point_range = point_range.start.row..=point_range.end.row;
 4071                            if point_range.contains(&buffer_row) {
 4072                                Some((location, code_actions))
 4073                            } else {
 4074                                None
 4075                            }
 4076                        })
 4077                        .unzip();
 4078                    let buffer_id = buffer.read(cx).remote_id();
 4079                    let tasks = editor
 4080                        .tasks
 4081                        .get(&(buffer_id, buffer_row))
 4082                        .map(|t| Arc::new(t.to_owned()));
 4083                    if tasks.is_none() && code_actions.is_none() {
 4084                        return None;
 4085                    }
 4086
 4087                    editor.completion_tasks.clear();
 4088                    editor.discard_inline_completion(false, cx);
 4089                    let task_context =
 4090                        tasks
 4091                            .as_ref()
 4092                            .zip(editor.project.clone())
 4093                            .map(|(tasks, project)| {
 4094                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4095                            });
 4096
 4097                    Some(cx.spawn(|editor, mut cx| async move {
 4098                        let task_context = match task_context {
 4099                            Some(task_context) => task_context.await,
 4100                            None => None,
 4101                        };
 4102                        let resolved_tasks =
 4103                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4104                                Rc::new(ResolvedTasks {
 4105                                    templates: tasks.resolve(&task_context).collect(),
 4106                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4107                                        multibuffer_point.row,
 4108                                        tasks.column,
 4109                                    )),
 4110                                })
 4111                            });
 4112                        let spawn_straight_away = resolved_tasks
 4113                            .as_ref()
 4114                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4115                            && code_actions
 4116                                .as_ref()
 4117                                .map_or(true, |actions| actions.is_empty());
 4118                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4119                            *editor.context_menu.borrow_mut() =
 4120                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4121                                    buffer,
 4122                                    actions: CodeActionContents {
 4123                                        tasks: resolved_tasks,
 4124                                        actions: code_actions,
 4125                                    },
 4126                                    selected_item: Default::default(),
 4127                                    scroll_handle: UniformListScrollHandle::default(),
 4128                                    deployed_from_indicator,
 4129                                }));
 4130                            if spawn_straight_away {
 4131                                if let Some(task) = editor.confirm_code_action(
 4132                                    &ConfirmCodeAction { item_ix: Some(0) },
 4133                                    cx,
 4134                                ) {
 4135                                    cx.notify();
 4136                                    return task;
 4137                                }
 4138                            }
 4139                            cx.notify();
 4140                            Task::ready(Ok(()))
 4141                        }) {
 4142                            task.await
 4143                        } else {
 4144                            Ok(())
 4145                        }
 4146                    }))
 4147                } else {
 4148                    Some(Task::ready(Ok(())))
 4149                }
 4150            })?;
 4151            if let Some(task) = spawned_test_task {
 4152                task.await?;
 4153            }
 4154
 4155            Ok::<_, anyhow::Error>(())
 4156        })
 4157        .detach_and_log_err(cx);
 4158    }
 4159
 4160    pub fn confirm_code_action(
 4161        &mut self,
 4162        action: &ConfirmCodeAction,
 4163        cx: &mut ViewContext<Self>,
 4164    ) -> Option<Task<Result<()>>> {
 4165        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4166            menu
 4167        } else {
 4168            return None;
 4169        };
 4170        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4171        let action = actions_menu.actions.get(action_ix)?;
 4172        let title = action.label();
 4173        let buffer = actions_menu.buffer;
 4174        let workspace = self.workspace()?;
 4175
 4176        match action {
 4177            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4178                workspace.update(cx, |workspace, cx| {
 4179                    workspace::tasks::schedule_resolved_task(
 4180                        workspace,
 4181                        task_source_kind,
 4182                        resolved_task,
 4183                        false,
 4184                        cx,
 4185                    );
 4186
 4187                    Some(Task::ready(Ok(())))
 4188                })
 4189            }
 4190            CodeActionsItem::CodeAction {
 4191                excerpt_id,
 4192                action,
 4193                provider,
 4194            } => {
 4195                let apply_code_action =
 4196                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4197                let workspace = workspace.downgrade();
 4198                Some(cx.spawn(|editor, cx| async move {
 4199                    let project_transaction = apply_code_action.await?;
 4200                    Self::open_project_transaction(
 4201                        &editor,
 4202                        workspace,
 4203                        project_transaction,
 4204                        title,
 4205                        cx,
 4206                    )
 4207                    .await
 4208                }))
 4209            }
 4210        }
 4211    }
 4212
 4213    pub async fn open_project_transaction(
 4214        this: &WeakView<Editor>,
 4215        workspace: WeakView<Workspace>,
 4216        transaction: ProjectTransaction,
 4217        title: String,
 4218        mut cx: AsyncWindowContext,
 4219    ) -> Result<()> {
 4220        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4221        cx.update(|cx| {
 4222            entries.sort_unstable_by_key(|(buffer, _)| {
 4223                buffer.read(cx).file().map(|f| f.path().clone())
 4224            });
 4225        })?;
 4226
 4227        // If the project transaction's edits are all contained within this editor, then
 4228        // avoid opening a new editor to display them.
 4229
 4230        if let Some((buffer, transaction)) = entries.first() {
 4231            if entries.len() == 1 {
 4232                let excerpt = this.update(&mut cx, |editor, cx| {
 4233                    editor
 4234                        .buffer()
 4235                        .read(cx)
 4236                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4237                })?;
 4238                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4239                    if excerpted_buffer == *buffer {
 4240                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4241                            let excerpt_range = excerpt_range.to_offset(buffer);
 4242                            buffer
 4243                                .edited_ranges_for_transaction::<usize>(transaction)
 4244                                .all(|range| {
 4245                                    excerpt_range.start <= range.start
 4246                                        && excerpt_range.end >= range.end
 4247                                })
 4248                        })?;
 4249
 4250                        if all_edits_within_excerpt {
 4251                            return Ok(());
 4252                        }
 4253                    }
 4254                }
 4255            }
 4256        } else {
 4257            return Ok(());
 4258        }
 4259
 4260        let mut ranges_to_highlight = Vec::new();
 4261        let excerpt_buffer = cx.new_model(|cx| {
 4262            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4263            for (buffer_handle, transaction) in &entries {
 4264                let buffer = buffer_handle.read(cx);
 4265                ranges_to_highlight.extend(
 4266                    multibuffer.push_excerpts_with_context_lines(
 4267                        buffer_handle.clone(),
 4268                        buffer
 4269                            .edited_ranges_for_transaction::<usize>(transaction)
 4270                            .collect(),
 4271                        DEFAULT_MULTIBUFFER_CONTEXT,
 4272                        cx,
 4273                    ),
 4274                );
 4275            }
 4276            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4277            multibuffer
 4278        })?;
 4279
 4280        workspace.update(&mut cx, |workspace, cx| {
 4281            let project = workspace.project().clone();
 4282            let editor =
 4283                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4284            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4285            editor.update(cx, |editor, cx| {
 4286                editor.highlight_background::<Self>(
 4287                    &ranges_to_highlight,
 4288                    |theme| theme.editor_highlighted_line_background,
 4289                    cx,
 4290                );
 4291            });
 4292        })?;
 4293
 4294        Ok(())
 4295    }
 4296
 4297    pub fn clear_code_action_providers(&mut self) {
 4298        self.code_action_providers.clear();
 4299        self.available_code_actions.take();
 4300    }
 4301
 4302    pub fn push_code_action_provider(
 4303        &mut self,
 4304        provider: Rc<dyn CodeActionProvider>,
 4305        cx: &mut ViewContext<Self>,
 4306    ) {
 4307        self.code_action_providers.push(provider);
 4308        self.refresh_code_actions(cx);
 4309    }
 4310
 4311    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4312        let buffer = self.buffer.read(cx);
 4313        let newest_selection = self.selections.newest_anchor().clone();
 4314        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4315        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4316        if start_buffer != end_buffer {
 4317            return None;
 4318        }
 4319
 4320        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4321            cx.background_executor()
 4322                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4323                .await;
 4324
 4325            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4326                let providers = this.code_action_providers.clone();
 4327                let tasks = this
 4328                    .code_action_providers
 4329                    .iter()
 4330                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4331                    .collect::<Vec<_>>();
 4332                (providers, tasks)
 4333            })?;
 4334
 4335            let mut actions = Vec::new();
 4336            for (provider, provider_actions) in
 4337                providers.into_iter().zip(future::join_all(tasks).await)
 4338            {
 4339                if let Some(provider_actions) = provider_actions.log_err() {
 4340                    actions.extend(provider_actions.into_iter().map(|action| {
 4341                        AvailableCodeAction {
 4342                            excerpt_id: newest_selection.start.excerpt_id,
 4343                            action,
 4344                            provider: provider.clone(),
 4345                        }
 4346                    }));
 4347                }
 4348            }
 4349
 4350            this.update(&mut cx, |this, cx| {
 4351                this.available_code_actions = if actions.is_empty() {
 4352                    None
 4353                } else {
 4354                    Some((
 4355                        Location {
 4356                            buffer: start_buffer,
 4357                            range: start..end,
 4358                        },
 4359                        actions.into(),
 4360                    ))
 4361                };
 4362                cx.notify();
 4363            })
 4364        }));
 4365        None
 4366    }
 4367
 4368    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4369        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4370            self.show_git_blame_inline = false;
 4371
 4372            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4373                cx.background_executor().timer(delay).await;
 4374
 4375                this.update(&mut cx, |this, cx| {
 4376                    this.show_git_blame_inline = true;
 4377                    cx.notify();
 4378                })
 4379                .log_err();
 4380            }));
 4381        }
 4382    }
 4383
 4384    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4385        if self.pending_rename.is_some() {
 4386            return None;
 4387        }
 4388
 4389        let provider = self.semantics_provider.clone()?;
 4390        let buffer = self.buffer.read(cx);
 4391        let newest_selection = self.selections.newest_anchor().clone();
 4392        let cursor_position = newest_selection.head();
 4393        let (cursor_buffer, cursor_buffer_position) =
 4394            buffer.text_anchor_for_position(cursor_position, cx)?;
 4395        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4396        if cursor_buffer != tail_buffer {
 4397            return None;
 4398        }
 4399        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4400        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4401            cx.background_executor()
 4402                .timer(Duration::from_millis(debounce))
 4403                .await;
 4404
 4405            let highlights = if let Some(highlights) = cx
 4406                .update(|cx| {
 4407                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4408                })
 4409                .ok()
 4410                .flatten()
 4411            {
 4412                highlights.await.log_err()
 4413            } else {
 4414                None
 4415            };
 4416
 4417            if let Some(highlights) = highlights {
 4418                this.update(&mut cx, |this, cx| {
 4419                    if this.pending_rename.is_some() {
 4420                        return;
 4421                    }
 4422
 4423                    let buffer_id = cursor_position.buffer_id;
 4424                    let buffer = this.buffer.read(cx);
 4425                    if !buffer
 4426                        .text_anchor_for_position(cursor_position, cx)
 4427                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4428                    {
 4429                        return;
 4430                    }
 4431
 4432                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4433                    let mut write_ranges = Vec::new();
 4434                    let mut read_ranges = Vec::new();
 4435                    for highlight in highlights {
 4436                        for (excerpt_id, excerpt_range) in
 4437                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4438                        {
 4439                            let start = highlight
 4440                                .range
 4441                                .start
 4442                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4443                            let end = highlight
 4444                                .range
 4445                                .end
 4446                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4447                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4448                                continue;
 4449                            }
 4450
 4451                            let range = Anchor {
 4452                                buffer_id,
 4453                                excerpt_id,
 4454                                text_anchor: start,
 4455                            }..Anchor {
 4456                                buffer_id,
 4457                                excerpt_id,
 4458                                text_anchor: end,
 4459                            };
 4460                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4461                                write_ranges.push(range);
 4462                            } else {
 4463                                read_ranges.push(range);
 4464                            }
 4465                        }
 4466                    }
 4467
 4468                    this.highlight_background::<DocumentHighlightRead>(
 4469                        &read_ranges,
 4470                        |theme| theme.editor_document_highlight_read_background,
 4471                        cx,
 4472                    );
 4473                    this.highlight_background::<DocumentHighlightWrite>(
 4474                        &write_ranges,
 4475                        |theme| theme.editor_document_highlight_write_background,
 4476                        cx,
 4477                    );
 4478                    cx.notify();
 4479                })
 4480                .log_err();
 4481            }
 4482        }));
 4483        None
 4484    }
 4485
 4486    pub fn refresh_inline_completion(
 4487        &mut self,
 4488        debounce: bool,
 4489        user_requested: bool,
 4490        cx: &mut ViewContext<Self>,
 4491    ) -> Option<()> {
 4492        let provider = self.inline_completion_provider()?;
 4493        let cursor = self.selections.newest_anchor().head();
 4494        let (buffer, cursor_buffer_position) =
 4495            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4496
 4497        if !user_requested
 4498            && (!self.enable_inline_completions
 4499                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4500                || !self.is_focused(cx))
 4501        {
 4502            self.discard_inline_completion(false, cx);
 4503            return None;
 4504        }
 4505
 4506        self.update_visible_inline_completion(cx);
 4507        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4508        Some(())
 4509    }
 4510
 4511    fn cycle_inline_completion(
 4512        &mut self,
 4513        direction: Direction,
 4514        cx: &mut ViewContext<Self>,
 4515    ) -> Option<()> {
 4516        let provider = self.inline_completion_provider()?;
 4517        let cursor = self.selections.newest_anchor().head();
 4518        let (buffer, cursor_buffer_position) =
 4519            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4520        if !self.enable_inline_completions
 4521            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4522        {
 4523            return None;
 4524        }
 4525
 4526        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4527        self.update_visible_inline_completion(cx);
 4528
 4529        Some(())
 4530    }
 4531
 4532    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4533        if !self.has_active_inline_completion() {
 4534            self.refresh_inline_completion(false, true, cx);
 4535            return;
 4536        }
 4537
 4538        self.update_visible_inline_completion(cx);
 4539    }
 4540
 4541    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4542        self.show_cursor_names(cx);
 4543    }
 4544
 4545    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4546        self.show_cursor_names = true;
 4547        cx.notify();
 4548        cx.spawn(|this, mut cx| async move {
 4549            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4550            this.update(&mut cx, |this, cx| {
 4551                this.show_cursor_names = false;
 4552                cx.notify()
 4553            })
 4554            .ok()
 4555        })
 4556        .detach();
 4557    }
 4558
 4559    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4560        if self.has_active_inline_completion() {
 4561            self.cycle_inline_completion(Direction::Next, cx);
 4562        } else {
 4563            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4564            if is_copilot_disabled {
 4565                cx.propagate();
 4566            }
 4567        }
 4568    }
 4569
 4570    pub fn previous_inline_completion(
 4571        &mut self,
 4572        _: &PreviousInlineCompletion,
 4573        cx: &mut ViewContext<Self>,
 4574    ) {
 4575        if self.has_active_inline_completion() {
 4576            self.cycle_inline_completion(Direction::Prev, cx);
 4577        } else {
 4578            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4579            if is_copilot_disabled {
 4580                cx.propagate();
 4581            }
 4582        }
 4583    }
 4584
 4585    pub fn accept_inline_completion(
 4586        &mut self,
 4587        _: &AcceptInlineCompletion,
 4588        cx: &mut ViewContext<Self>,
 4589    ) {
 4590        let buffer = self.buffer.read(cx);
 4591        let snapshot = buffer.snapshot(cx);
 4592        let selection = self.selections.newest_adjusted(cx);
 4593        let cursor = selection.head();
 4594        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4595        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4596        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4597        {
 4598            if cursor.column < suggested_indent.len
 4599                && cursor.column <= current_indent.len
 4600                && current_indent.len <= suggested_indent.len
 4601            {
 4602                self.tab(&Default::default(), cx);
 4603                return;
 4604            }
 4605        }
 4606
 4607        if self.show_inline_completions_in_menu(cx) {
 4608            self.hide_context_menu(cx);
 4609        }
 4610
 4611        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4612            return;
 4613        };
 4614
 4615        self.report_inline_completion_event(true, cx);
 4616
 4617        match &active_inline_completion.completion {
 4618            InlineCompletion::Move(position) => {
 4619                let position = *position;
 4620                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4621                    selections.select_anchor_ranges([position..position]);
 4622                });
 4623            }
 4624            InlineCompletion::Edit(edits) => {
 4625                if let Some(provider) = self.inline_completion_provider() {
 4626                    provider.accept(cx);
 4627                }
 4628
 4629                let snapshot = self.buffer.read(cx).snapshot(cx);
 4630                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4631
 4632                self.buffer.update(cx, |buffer, cx| {
 4633                    buffer.edit(edits.iter().cloned(), None, cx)
 4634                });
 4635
 4636                self.change_selections(None, cx, |s| {
 4637                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4638                });
 4639
 4640                self.update_visible_inline_completion(cx);
 4641                if self.active_inline_completion.is_none() {
 4642                    self.refresh_inline_completion(true, true, cx);
 4643                }
 4644
 4645                cx.notify();
 4646            }
 4647        }
 4648    }
 4649
 4650    pub fn accept_partial_inline_completion(
 4651        &mut self,
 4652        _: &AcceptPartialInlineCompletion,
 4653        cx: &mut ViewContext<Self>,
 4654    ) {
 4655        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4656            return;
 4657        };
 4658        if self.selections.count() != 1 {
 4659            return;
 4660        }
 4661
 4662        self.report_inline_completion_event(true, cx);
 4663
 4664        match &active_inline_completion.completion {
 4665            InlineCompletion::Move(position) => {
 4666                let position = *position;
 4667                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4668                    selections.select_anchor_ranges([position..position]);
 4669                });
 4670            }
 4671            InlineCompletion::Edit(edits) => {
 4672                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4673                    let text = edits[0].1.as_str();
 4674                    let mut partial_completion = text
 4675                        .chars()
 4676                        .by_ref()
 4677                        .take_while(|c| c.is_alphabetic())
 4678                        .collect::<String>();
 4679                    if partial_completion.is_empty() {
 4680                        partial_completion = text
 4681                            .chars()
 4682                            .by_ref()
 4683                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4684                            .collect::<String>();
 4685                    }
 4686
 4687                    cx.emit(EditorEvent::InputHandled {
 4688                        utf16_range_to_replace: None,
 4689                        text: partial_completion.clone().into(),
 4690                    });
 4691
 4692                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4693
 4694                    self.refresh_inline_completion(true, true, cx);
 4695                    cx.notify();
 4696                }
 4697            }
 4698        }
 4699    }
 4700
 4701    fn discard_inline_completion(
 4702        &mut self,
 4703        should_report_inline_completion_event: bool,
 4704        cx: &mut ViewContext<Self>,
 4705    ) -> bool {
 4706        if should_report_inline_completion_event {
 4707            self.report_inline_completion_event(false, cx);
 4708        }
 4709
 4710        if let Some(provider) = self.inline_completion_provider() {
 4711            provider.discard(cx);
 4712        }
 4713
 4714        self.take_active_inline_completion(cx).is_some()
 4715    }
 4716
 4717    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4718        let Some(provider) = self.inline_completion_provider() else {
 4719            return;
 4720        };
 4721        let Some(project) = self.project.as_ref() else {
 4722            return;
 4723        };
 4724        let Some((_, buffer, _)) = self
 4725            .buffer
 4726            .read(cx)
 4727            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4728        else {
 4729            return;
 4730        };
 4731
 4732        let project = project.read(cx);
 4733        let extension = buffer
 4734            .read(cx)
 4735            .file()
 4736            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4737        project.client().telemetry().report_inline_completion_event(
 4738            provider.name().into(),
 4739            accepted,
 4740            extension,
 4741        );
 4742    }
 4743
 4744    pub fn has_active_inline_completion(&self) -> bool {
 4745        self.active_inline_completion.is_some()
 4746    }
 4747
 4748    fn take_active_inline_completion(
 4749        &mut self,
 4750        cx: &mut ViewContext<Self>,
 4751    ) -> Option<InlineCompletion> {
 4752        let active_inline_completion = self.active_inline_completion.take()?;
 4753        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4754        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4755        Some(active_inline_completion.completion)
 4756    }
 4757
 4758    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4759        let selection = self.selections.newest_anchor();
 4760        let cursor = selection.head();
 4761        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4762        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4763        let excerpt_id = cursor.excerpt_id;
 4764
 4765        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4766            && (self.context_menu.borrow().is_some()
 4767                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4768        if completions_menu_has_precedence
 4769            || !offset_selection.is_empty()
 4770            || self
 4771                .active_inline_completion
 4772                .as_ref()
 4773                .map_or(false, |completion| {
 4774                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4775                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4776                    !invalidation_range.contains(&offset_selection.head())
 4777                })
 4778        {
 4779            self.discard_inline_completion(false, cx);
 4780            return None;
 4781        }
 4782
 4783        self.take_active_inline_completion(cx);
 4784        let provider = self.inline_completion_provider()?;
 4785
 4786        let (buffer, cursor_buffer_position) =
 4787            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4788
 4789        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4790        let edits = completion
 4791            .edits
 4792            .into_iter()
 4793            .flat_map(|(range, new_text)| {
 4794                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4795                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4796                Some((start..end, new_text))
 4797            })
 4798            .collect::<Vec<_>>();
 4799        if edits.is_empty() {
 4800            return None;
 4801        }
 4802
 4803        let first_edit_start = edits.first().unwrap().0.start;
 4804        let edit_start_row = first_edit_start
 4805            .to_point(&multibuffer)
 4806            .row
 4807            .saturating_sub(2);
 4808
 4809        let last_edit_end = edits.last().unwrap().0.end;
 4810        let edit_end_row = cmp::min(
 4811            multibuffer.max_point().row,
 4812            last_edit_end.to_point(&multibuffer).row + 2,
 4813        );
 4814
 4815        let cursor_row = cursor.to_point(&multibuffer).row;
 4816
 4817        let mut inlay_ids = Vec::new();
 4818        let invalidation_row_range;
 4819        let completion;
 4820        if cursor_row < edit_start_row {
 4821            invalidation_row_range = cursor_row..edit_end_row;
 4822            completion = InlineCompletion::Move(first_edit_start);
 4823        } else if cursor_row > edit_end_row {
 4824            invalidation_row_range = edit_start_row..cursor_row;
 4825            completion = InlineCompletion::Move(first_edit_start);
 4826        } else {
 4827            if edits
 4828                .iter()
 4829                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4830            {
 4831                let mut inlays = Vec::new();
 4832                for (range, new_text) in &edits {
 4833                    let inlay = Inlay::inline_completion(
 4834                        post_inc(&mut self.next_inlay_id),
 4835                        range.start,
 4836                        new_text.as_str(),
 4837                    );
 4838                    inlay_ids.push(inlay.id);
 4839                    inlays.push(inlay);
 4840                }
 4841
 4842                self.splice_inlays(vec![], inlays, cx);
 4843            } else {
 4844                let background_color = cx.theme().status().deleted_background;
 4845                self.highlight_text::<InlineCompletionHighlight>(
 4846                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4847                    HighlightStyle {
 4848                        background_color: Some(background_color),
 4849                        ..Default::default()
 4850                    },
 4851                    cx,
 4852                );
 4853            }
 4854
 4855            invalidation_row_range = edit_start_row..edit_end_row;
 4856            completion = InlineCompletion::Edit(edits);
 4857        };
 4858
 4859        let invalidation_range = multibuffer
 4860            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4861            ..multibuffer.anchor_after(Point::new(
 4862                invalidation_row_range.end,
 4863                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4864            ));
 4865
 4866        self.active_inline_completion = Some(InlineCompletionState {
 4867            inlay_ids,
 4868            completion,
 4869            invalidation_range,
 4870        });
 4871
 4872        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4873            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4874                match self.context_menu.borrow_mut().as_mut() {
 4875                    Some(CodeContextMenu::Completions(menu)) => {
 4876                        menu.show_inline_completion_hint(hint);
 4877                    }
 4878                    _ => {}
 4879                }
 4880            }
 4881        }
 4882
 4883        cx.notify();
 4884
 4885        Some(())
 4886    }
 4887
 4888    fn inline_completion_menu_hint(
 4889        &mut self,
 4890        cx: &mut ViewContext<Self>,
 4891    ) -> Option<InlineCompletionMenuHint> {
 4892        if self.has_active_inline_completion() {
 4893            let provider_name = self.inline_completion_provider()?.display_name();
 4894            let editor_snapshot = self.snapshot(cx);
 4895
 4896            let text = match &self.active_inline_completion.as_ref()?.completion {
 4897                InlineCompletion::Edit(edits) => {
 4898                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4899                }
 4900                InlineCompletion::Move(target) => {
 4901                    let target_point =
 4902                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4903                    let target_line = target_point.row + 1;
 4904                    InlineCompletionText::Move(
 4905                        format!("Jump to edit in line {}", target_line).into(),
 4906                    )
 4907                }
 4908            };
 4909
 4910            Some(InlineCompletionMenuHint {
 4911                provider_name,
 4912                text,
 4913            })
 4914        } else {
 4915            None
 4916        }
 4917    }
 4918
 4919    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4920        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4921    }
 4922
 4923    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4924        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4925            && self
 4926                .inline_completion_provider()
 4927                .map_or(false, |provider| provider.show_completions_in_menu())
 4928    }
 4929
 4930    fn render_code_actions_indicator(
 4931        &self,
 4932        _style: &EditorStyle,
 4933        row: DisplayRow,
 4934        is_active: bool,
 4935        cx: &mut ViewContext<Self>,
 4936    ) -> Option<IconButton> {
 4937        if self.available_code_actions.is_some() {
 4938            Some(
 4939                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4940                    .shape(ui::IconButtonShape::Square)
 4941                    .icon_size(IconSize::XSmall)
 4942                    .icon_color(Color::Muted)
 4943                    .toggle_state(is_active)
 4944                    .tooltip({
 4945                        let focus_handle = self.focus_handle.clone();
 4946                        move |cx| {
 4947                            Tooltip::for_action_in(
 4948                                "Toggle Code Actions",
 4949                                &ToggleCodeActions {
 4950                                    deployed_from_indicator: None,
 4951                                },
 4952                                &focus_handle,
 4953                                cx,
 4954                            )
 4955                        }
 4956                    })
 4957                    .on_click(cx.listener(move |editor, _e, cx| {
 4958                        editor.focus(cx);
 4959                        editor.toggle_code_actions(
 4960                            &ToggleCodeActions {
 4961                                deployed_from_indicator: Some(row),
 4962                            },
 4963                            cx,
 4964                        );
 4965                    })),
 4966            )
 4967        } else {
 4968            None
 4969        }
 4970    }
 4971
 4972    fn clear_tasks(&mut self) {
 4973        self.tasks.clear()
 4974    }
 4975
 4976    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4977        if self.tasks.insert(key, value).is_some() {
 4978            // This case should hopefully be rare, but just in case...
 4979            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4980        }
 4981    }
 4982
 4983    fn build_tasks_context(
 4984        project: &Model<Project>,
 4985        buffer: &Model<Buffer>,
 4986        buffer_row: u32,
 4987        tasks: &Arc<RunnableTasks>,
 4988        cx: &mut ViewContext<Self>,
 4989    ) -> Task<Option<task::TaskContext>> {
 4990        let position = Point::new(buffer_row, tasks.column);
 4991        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4992        let location = Location {
 4993            buffer: buffer.clone(),
 4994            range: range_start..range_start,
 4995        };
 4996        // Fill in the environmental variables from the tree-sitter captures
 4997        let mut captured_task_variables = TaskVariables::default();
 4998        for (capture_name, value) in tasks.extra_variables.clone() {
 4999            captured_task_variables.insert(
 5000                task::VariableName::Custom(capture_name.into()),
 5001                value.clone(),
 5002            );
 5003        }
 5004        project.update(cx, |project, cx| {
 5005            project.task_store().update(cx, |task_store, cx| {
 5006                task_store.task_context_for_location(captured_task_variables, location, cx)
 5007            })
 5008        })
 5009    }
 5010
 5011    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5012        let Some((workspace, _)) = self.workspace.clone() else {
 5013            return;
 5014        };
 5015        let Some(project) = self.project.clone() else {
 5016            return;
 5017        };
 5018
 5019        // Try to find a closest, enclosing node using tree-sitter that has a
 5020        // task
 5021        let Some((buffer, buffer_row, tasks)) = self
 5022            .find_enclosing_node_task(cx)
 5023            // Or find the task that's closest in row-distance.
 5024            .or_else(|| self.find_closest_task(cx))
 5025        else {
 5026            return;
 5027        };
 5028
 5029        let reveal_strategy = action.reveal;
 5030        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5031        cx.spawn(|_, mut cx| async move {
 5032            let context = task_context.await?;
 5033            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5034
 5035            let resolved = resolved_task.resolved.as_mut()?;
 5036            resolved.reveal = reveal_strategy;
 5037
 5038            workspace
 5039                .update(&mut cx, |workspace, cx| {
 5040                    workspace::tasks::schedule_resolved_task(
 5041                        workspace,
 5042                        task_source_kind,
 5043                        resolved_task,
 5044                        false,
 5045                        cx,
 5046                    );
 5047                })
 5048                .ok()
 5049        })
 5050        .detach();
 5051    }
 5052
 5053    fn find_closest_task(
 5054        &mut self,
 5055        cx: &mut ViewContext<Self>,
 5056    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5057        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5058
 5059        let ((buffer_id, row), tasks) = self
 5060            .tasks
 5061            .iter()
 5062            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5063
 5064        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5065        let tasks = Arc::new(tasks.to_owned());
 5066        Some((buffer, *row, tasks))
 5067    }
 5068
 5069    fn find_enclosing_node_task(
 5070        &mut self,
 5071        cx: &mut ViewContext<Self>,
 5072    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5073        let snapshot = self.buffer.read(cx).snapshot(cx);
 5074        let offset = self.selections.newest::<usize>(cx).head();
 5075        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5076        let buffer_id = excerpt.buffer().remote_id();
 5077
 5078        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5079        let mut cursor = layer.node().walk();
 5080
 5081        while cursor.goto_first_child_for_byte(offset).is_some() {
 5082            if cursor.node().end_byte() == offset {
 5083                cursor.goto_next_sibling();
 5084            }
 5085        }
 5086
 5087        // Ascend to the smallest ancestor that contains the range and has a task.
 5088        loop {
 5089            let node = cursor.node();
 5090            let node_range = node.byte_range();
 5091            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5092
 5093            // Check if this node contains our offset
 5094            if node_range.start <= offset && node_range.end >= offset {
 5095                // If it contains offset, check for task
 5096                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5097                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5098                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5099                }
 5100            }
 5101
 5102            if !cursor.goto_parent() {
 5103                break;
 5104            }
 5105        }
 5106        None
 5107    }
 5108
 5109    fn render_run_indicator(
 5110        &self,
 5111        _style: &EditorStyle,
 5112        is_active: bool,
 5113        row: DisplayRow,
 5114        cx: &mut ViewContext<Self>,
 5115    ) -> IconButton {
 5116        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5117            .shape(ui::IconButtonShape::Square)
 5118            .icon_size(IconSize::XSmall)
 5119            .icon_color(Color::Muted)
 5120            .toggle_state(is_active)
 5121            .on_click(cx.listener(move |editor, _e, cx| {
 5122                editor.focus(cx);
 5123                editor.toggle_code_actions(
 5124                    &ToggleCodeActions {
 5125                        deployed_from_indicator: Some(row),
 5126                    },
 5127                    cx,
 5128                );
 5129            }))
 5130    }
 5131
 5132    #[cfg(any(feature = "test-support", test))]
 5133    pub fn context_menu_visible(&self) -> bool {
 5134        self.context_menu
 5135            .borrow()
 5136            .as_ref()
 5137            .map_or(false, |menu| menu.visible())
 5138    }
 5139
 5140    #[cfg(feature = "test-support")]
 5141    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5142        self.context_menu
 5143            .borrow()
 5144            .as_ref()
 5145            .map_or(false, |menu| match menu {
 5146                CodeContextMenu::Completions(menu) => {
 5147                    menu.entries.borrow().first().map_or(false, |entry| {
 5148                        matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5149                    })
 5150                }
 5151                CodeContextMenu::CodeActions(_) => false,
 5152            })
 5153    }
 5154
 5155    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5156        self.context_menu
 5157            .borrow()
 5158            .as_ref()
 5159            .map(|menu| menu.origin(cursor_position))
 5160    }
 5161
 5162    fn render_context_menu(
 5163        &self,
 5164        style: &EditorStyle,
 5165        max_height_in_lines: u32,
 5166        cx: &mut ViewContext<Editor>,
 5167    ) -> Option<AnyElement> {
 5168        self.context_menu.borrow().as_ref().and_then(|menu| {
 5169            if menu.visible() {
 5170                Some(menu.render(style, max_height_in_lines, cx))
 5171            } else {
 5172                None
 5173            }
 5174        })
 5175    }
 5176
 5177    fn render_context_menu_aside(
 5178        &self,
 5179        style: &EditorStyle,
 5180        max_size: Size<Pixels>,
 5181        cx: &mut ViewContext<Editor>,
 5182    ) -> Option<AnyElement> {
 5183        self.context_menu.borrow().as_ref().and_then(|menu| {
 5184            if menu.visible() {
 5185                menu.render_aside(
 5186                    style,
 5187                    max_size,
 5188                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5189                    cx,
 5190                )
 5191            } else {
 5192                None
 5193            }
 5194        })
 5195    }
 5196
 5197    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5198        cx.notify();
 5199        self.completion_tasks.clear();
 5200        let context_menu = self.context_menu.borrow_mut().take();
 5201        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5202            self.update_visible_inline_completion(cx);
 5203        }
 5204        context_menu
 5205    }
 5206
 5207    fn show_snippet_choices(
 5208        &mut self,
 5209        choices: &Vec<String>,
 5210        selection: Range<Anchor>,
 5211        cx: &mut ViewContext<Self>,
 5212    ) {
 5213        if selection.start.buffer_id.is_none() {
 5214            return;
 5215        }
 5216        let buffer_id = selection.start.buffer_id.unwrap();
 5217        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5218        let id = post_inc(&mut self.next_completion_id);
 5219
 5220        if let Some(buffer) = buffer {
 5221            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5222                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5223            ));
 5224        }
 5225    }
 5226
 5227    pub fn insert_snippet(
 5228        &mut self,
 5229        insertion_ranges: &[Range<usize>],
 5230        snippet: Snippet,
 5231        cx: &mut ViewContext<Self>,
 5232    ) -> Result<()> {
 5233        struct Tabstop<T> {
 5234            is_end_tabstop: bool,
 5235            ranges: Vec<Range<T>>,
 5236            choices: Option<Vec<String>>,
 5237        }
 5238
 5239        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5240            let snippet_text: Arc<str> = snippet.text.clone().into();
 5241            buffer.edit(
 5242                insertion_ranges
 5243                    .iter()
 5244                    .cloned()
 5245                    .map(|range| (range, snippet_text.clone())),
 5246                Some(AutoindentMode::EachLine),
 5247                cx,
 5248            );
 5249
 5250            let snapshot = &*buffer.read(cx);
 5251            let snippet = &snippet;
 5252            snippet
 5253                .tabstops
 5254                .iter()
 5255                .map(|tabstop| {
 5256                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5257                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5258                    });
 5259                    let mut tabstop_ranges = tabstop
 5260                        .ranges
 5261                        .iter()
 5262                        .flat_map(|tabstop_range| {
 5263                            let mut delta = 0_isize;
 5264                            insertion_ranges.iter().map(move |insertion_range| {
 5265                                let insertion_start = insertion_range.start as isize + delta;
 5266                                delta +=
 5267                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5268
 5269                                let start = ((insertion_start + tabstop_range.start) as usize)
 5270                                    .min(snapshot.len());
 5271                                let end = ((insertion_start + tabstop_range.end) as usize)
 5272                                    .min(snapshot.len());
 5273                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5274                            })
 5275                        })
 5276                        .collect::<Vec<_>>();
 5277                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5278
 5279                    Tabstop {
 5280                        is_end_tabstop,
 5281                        ranges: tabstop_ranges,
 5282                        choices: tabstop.choices.clone(),
 5283                    }
 5284                })
 5285                .collect::<Vec<_>>()
 5286        });
 5287        if let Some(tabstop) = tabstops.first() {
 5288            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5289                s.select_ranges(tabstop.ranges.iter().cloned());
 5290            });
 5291
 5292            if let Some(choices) = &tabstop.choices {
 5293                if let Some(selection) = tabstop.ranges.first() {
 5294                    self.show_snippet_choices(choices, selection.clone(), cx)
 5295                }
 5296            }
 5297
 5298            // If we're already at the last tabstop and it's at the end of the snippet,
 5299            // we're done, we don't need to keep the state around.
 5300            if !tabstop.is_end_tabstop {
 5301                let choices = tabstops
 5302                    .iter()
 5303                    .map(|tabstop| tabstop.choices.clone())
 5304                    .collect();
 5305
 5306                let ranges = tabstops
 5307                    .into_iter()
 5308                    .map(|tabstop| tabstop.ranges)
 5309                    .collect::<Vec<_>>();
 5310
 5311                self.snippet_stack.push(SnippetState {
 5312                    active_index: 0,
 5313                    ranges,
 5314                    choices,
 5315                });
 5316            }
 5317
 5318            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5319            if self.autoclose_regions.is_empty() {
 5320                let snapshot = self.buffer.read(cx).snapshot(cx);
 5321                for selection in &mut self.selections.all::<Point>(cx) {
 5322                    let selection_head = selection.head();
 5323                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5324                        continue;
 5325                    };
 5326
 5327                    let mut bracket_pair = None;
 5328                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5329                    let prev_chars = snapshot
 5330                        .reversed_chars_at(selection_head)
 5331                        .collect::<String>();
 5332                    for (pair, enabled) in scope.brackets() {
 5333                        if enabled
 5334                            && pair.close
 5335                            && prev_chars.starts_with(pair.start.as_str())
 5336                            && next_chars.starts_with(pair.end.as_str())
 5337                        {
 5338                            bracket_pair = Some(pair.clone());
 5339                            break;
 5340                        }
 5341                    }
 5342                    if let Some(pair) = bracket_pair {
 5343                        let start = snapshot.anchor_after(selection_head);
 5344                        let end = snapshot.anchor_after(selection_head);
 5345                        self.autoclose_regions.push(AutocloseRegion {
 5346                            selection_id: selection.id,
 5347                            range: start..end,
 5348                            pair,
 5349                        });
 5350                    }
 5351                }
 5352            }
 5353        }
 5354        Ok(())
 5355    }
 5356
 5357    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5358        self.move_to_snippet_tabstop(Bias::Right, cx)
 5359    }
 5360
 5361    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5362        self.move_to_snippet_tabstop(Bias::Left, cx)
 5363    }
 5364
 5365    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5366        if let Some(mut snippet) = self.snippet_stack.pop() {
 5367            match bias {
 5368                Bias::Left => {
 5369                    if snippet.active_index > 0 {
 5370                        snippet.active_index -= 1;
 5371                    } else {
 5372                        self.snippet_stack.push(snippet);
 5373                        return false;
 5374                    }
 5375                }
 5376                Bias::Right => {
 5377                    if snippet.active_index + 1 < snippet.ranges.len() {
 5378                        snippet.active_index += 1;
 5379                    } else {
 5380                        self.snippet_stack.push(snippet);
 5381                        return false;
 5382                    }
 5383                }
 5384            }
 5385            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5386                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5387                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5388                });
 5389
 5390                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5391                    if let Some(selection) = current_ranges.first() {
 5392                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5393                    }
 5394                }
 5395
 5396                // If snippet state is not at the last tabstop, push it back on the stack
 5397                if snippet.active_index + 1 < snippet.ranges.len() {
 5398                    self.snippet_stack.push(snippet);
 5399                }
 5400                return true;
 5401            }
 5402        }
 5403
 5404        false
 5405    }
 5406
 5407    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5408        self.transact(cx, |this, cx| {
 5409            this.select_all(&SelectAll, cx);
 5410            this.insert("", cx);
 5411        });
 5412    }
 5413
 5414    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5415        self.transact(cx, |this, cx| {
 5416            this.select_autoclose_pair(cx);
 5417            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5418            if !this.linked_edit_ranges.is_empty() {
 5419                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5420                let snapshot = this.buffer.read(cx).snapshot(cx);
 5421
 5422                for selection in selections.iter() {
 5423                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5424                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5425                    if selection_start.buffer_id != selection_end.buffer_id {
 5426                        continue;
 5427                    }
 5428                    if let Some(ranges) =
 5429                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5430                    {
 5431                        for (buffer, entries) in ranges {
 5432                            linked_ranges.entry(buffer).or_default().extend(entries);
 5433                        }
 5434                    }
 5435                }
 5436            }
 5437
 5438            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5439            if !this.selections.line_mode {
 5440                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5441                for selection in &mut selections {
 5442                    if selection.is_empty() {
 5443                        let old_head = selection.head();
 5444                        let mut new_head =
 5445                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5446                                .to_point(&display_map);
 5447                        if let Some((buffer, line_buffer_range)) = display_map
 5448                            .buffer_snapshot
 5449                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5450                        {
 5451                            let indent_size =
 5452                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5453                            let indent_len = match indent_size.kind {
 5454                                IndentKind::Space => {
 5455                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5456                                }
 5457                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5458                            };
 5459                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5460                                let indent_len = indent_len.get();
 5461                                new_head = cmp::min(
 5462                                    new_head,
 5463                                    MultiBufferPoint::new(
 5464                                        old_head.row,
 5465                                        ((old_head.column - 1) / indent_len) * indent_len,
 5466                                    ),
 5467                                );
 5468                            }
 5469                        }
 5470
 5471                        selection.set_head(new_head, SelectionGoal::None);
 5472                    }
 5473                }
 5474            }
 5475
 5476            this.signature_help_state.set_backspace_pressed(true);
 5477            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5478            this.insert("", cx);
 5479            let empty_str: Arc<str> = Arc::from("");
 5480            for (buffer, edits) in linked_ranges {
 5481                let snapshot = buffer.read(cx).snapshot();
 5482                use text::ToPoint as TP;
 5483
 5484                let edits = edits
 5485                    .into_iter()
 5486                    .map(|range| {
 5487                        let end_point = TP::to_point(&range.end, &snapshot);
 5488                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5489
 5490                        if end_point == start_point {
 5491                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5492                                .saturating_sub(1);
 5493                            start_point =
 5494                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5495                        };
 5496
 5497                        (start_point..end_point, empty_str.clone())
 5498                    })
 5499                    .sorted_by_key(|(range, _)| range.start)
 5500                    .collect::<Vec<_>>();
 5501                buffer.update(cx, |this, cx| {
 5502                    this.edit(edits, None, cx);
 5503                })
 5504            }
 5505            this.refresh_inline_completion(true, false, cx);
 5506            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5507        });
 5508    }
 5509
 5510    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5511        self.transact(cx, |this, cx| {
 5512            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5513                let line_mode = s.line_mode;
 5514                s.move_with(|map, selection| {
 5515                    if selection.is_empty() && !line_mode {
 5516                        let cursor = movement::right(map, selection.head());
 5517                        selection.end = cursor;
 5518                        selection.reversed = true;
 5519                        selection.goal = SelectionGoal::None;
 5520                    }
 5521                })
 5522            });
 5523            this.insert("", cx);
 5524            this.refresh_inline_completion(true, false, cx);
 5525        });
 5526    }
 5527
 5528    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5529        if self.move_to_prev_snippet_tabstop(cx) {
 5530            return;
 5531        }
 5532
 5533        self.outdent(&Outdent, cx);
 5534    }
 5535
 5536    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5537        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5538            return;
 5539        }
 5540
 5541        let mut selections = self.selections.all_adjusted(cx);
 5542        let buffer = self.buffer.read(cx);
 5543        let snapshot = buffer.snapshot(cx);
 5544        let rows_iter = selections.iter().map(|s| s.head().row);
 5545        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5546
 5547        let mut edits = Vec::new();
 5548        let mut prev_edited_row = 0;
 5549        let mut row_delta = 0;
 5550        for selection in &mut selections {
 5551            if selection.start.row != prev_edited_row {
 5552                row_delta = 0;
 5553            }
 5554            prev_edited_row = selection.end.row;
 5555
 5556            // If the selection is non-empty, then increase the indentation of the selected lines.
 5557            if !selection.is_empty() {
 5558                row_delta =
 5559                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5560                continue;
 5561            }
 5562
 5563            // If the selection is empty and the cursor is in the leading whitespace before the
 5564            // suggested indentation, then auto-indent the line.
 5565            let cursor = selection.head();
 5566            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5567            if let Some(suggested_indent) =
 5568                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5569            {
 5570                if cursor.column < suggested_indent.len
 5571                    && cursor.column <= current_indent.len
 5572                    && current_indent.len <= suggested_indent.len
 5573                {
 5574                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5575                    selection.end = selection.start;
 5576                    if row_delta == 0 {
 5577                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5578                            cursor.row,
 5579                            current_indent,
 5580                            suggested_indent,
 5581                        ));
 5582                        row_delta = suggested_indent.len - current_indent.len;
 5583                    }
 5584                    continue;
 5585                }
 5586            }
 5587
 5588            // Otherwise, insert a hard or soft tab.
 5589            let settings = buffer.settings_at(cursor, cx);
 5590            let tab_size = if settings.hard_tabs {
 5591                IndentSize::tab()
 5592            } else {
 5593                let tab_size = settings.tab_size.get();
 5594                let char_column = snapshot
 5595                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5596                    .flat_map(str::chars)
 5597                    .count()
 5598                    + row_delta as usize;
 5599                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5600                IndentSize::spaces(chars_to_next_tab_stop)
 5601            };
 5602            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5603            selection.end = selection.start;
 5604            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5605            row_delta += tab_size.len;
 5606        }
 5607
 5608        self.transact(cx, |this, cx| {
 5609            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5610            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5611            this.refresh_inline_completion(true, false, cx);
 5612        });
 5613    }
 5614
 5615    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5616        if self.read_only(cx) {
 5617            return;
 5618        }
 5619        let mut selections = self.selections.all::<Point>(cx);
 5620        let mut prev_edited_row = 0;
 5621        let mut row_delta = 0;
 5622        let mut edits = Vec::new();
 5623        let buffer = self.buffer.read(cx);
 5624        let snapshot = buffer.snapshot(cx);
 5625        for selection in &mut selections {
 5626            if selection.start.row != prev_edited_row {
 5627                row_delta = 0;
 5628            }
 5629            prev_edited_row = selection.end.row;
 5630
 5631            row_delta =
 5632                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5633        }
 5634
 5635        self.transact(cx, |this, cx| {
 5636            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5637            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5638        });
 5639    }
 5640
 5641    fn indent_selection(
 5642        buffer: &MultiBuffer,
 5643        snapshot: &MultiBufferSnapshot,
 5644        selection: &mut Selection<Point>,
 5645        edits: &mut Vec<(Range<Point>, String)>,
 5646        delta_for_start_row: u32,
 5647        cx: &AppContext,
 5648    ) -> u32 {
 5649        let settings = buffer.settings_at(selection.start, cx);
 5650        let tab_size = settings.tab_size.get();
 5651        let indent_kind = if settings.hard_tabs {
 5652            IndentKind::Tab
 5653        } else {
 5654            IndentKind::Space
 5655        };
 5656        let mut start_row = selection.start.row;
 5657        let mut end_row = selection.end.row + 1;
 5658
 5659        // If a selection ends at the beginning of a line, don't indent
 5660        // that last line.
 5661        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5662            end_row -= 1;
 5663        }
 5664
 5665        // Avoid re-indenting a row that has already been indented by a
 5666        // previous selection, but still update this selection's column
 5667        // to reflect that indentation.
 5668        if delta_for_start_row > 0 {
 5669            start_row += 1;
 5670            selection.start.column += delta_for_start_row;
 5671            if selection.end.row == selection.start.row {
 5672                selection.end.column += delta_for_start_row;
 5673            }
 5674        }
 5675
 5676        let mut delta_for_end_row = 0;
 5677        let has_multiple_rows = start_row + 1 != end_row;
 5678        for row in start_row..end_row {
 5679            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5680            let indent_delta = match (current_indent.kind, indent_kind) {
 5681                (IndentKind::Space, IndentKind::Space) => {
 5682                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5683                    IndentSize::spaces(columns_to_next_tab_stop)
 5684                }
 5685                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5686                (_, IndentKind::Tab) => IndentSize::tab(),
 5687            };
 5688
 5689            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5690                0
 5691            } else {
 5692                selection.start.column
 5693            };
 5694            let row_start = Point::new(row, start);
 5695            edits.push((
 5696                row_start..row_start,
 5697                indent_delta.chars().collect::<String>(),
 5698            ));
 5699
 5700            // Update this selection's endpoints to reflect the indentation.
 5701            if row == selection.start.row {
 5702                selection.start.column += indent_delta.len;
 5703            }
 5704            if row == selection.end.row {
 5705                selection.end.column += indent_delta.len;
 5706                delta_for_end_row = indent_delta.len;
 5707            }
 5708        }
 5709
 5710        if selection.start.row == selection.end.row {
 5711            delta_for_start_row + delta_for_end_row
 5712        } else {
 5713            delta_for_end_row
 5714        }
 5715    }
 5716
 5717    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5718        if self.read_only(cx) {
 5719            return;
 5720        }
 5721        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5722        let selections = self.selections.all::<Point>(cx);
 5723        let mut deletion_ranges = Vec::new();
 5724        let mut last_outdent = None;
 5725        {
 5726            let buffer = self.buffer.read(cx);
 5727            let snapshot = buffer.snapshot(cx);
 5728            for selection in &selections {
 5729                let settings = buffer.settings_at(selection.start, cx);
 5730                let tab_size = settings.tab_size.get();
 5731                let mut rows = selection.spanned_rows(false, &display_map);
 5732
 5733                // Avoid re-outdenting a row that has already been outdented by a
 5734                // previous selection.
 5735                if let Some(last_row) = last_outdent {
 5736                    if last_row == rows.start {
 5737                        rows.start = rows.start.next_row();
 5738                    }
 5739                }
 5740                let has_multiple_rows = rows.len() > 1;
 5741                for row in rows.iter_rows() {
 5742                    let indent_size = snapshot.indent_size_for_line(row);
 5743                    if indent_size.len > 0 {
 5744                        let deletion_len = match indent_size.kind {
 5745                            IndentKind::Space => {
 5746                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5747                                if columns_to_prev_tab_stop == 0 {
 5748                                    tab_size
 5749                                } else {
 5750                                    columns_to_prev_tab_stop
 5751                                }
 5752                            }
 5753                            IndentKind::Tab => 1,
 5754                        };
 5755                        let start = if has_multiple_rows
 5756                            || deletion_len > selection.start.column
 5757                            || indent_size.len < selection.start.column
 5758                        {
 5759                            0
 5760                        } else {
 5761                            selection.start.column - deletion_len
 5762                        };
 5763                        deletion_ranges.push(
 5764                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5765                        );
 5766                        last_outdent = Some(row);
 5767                    }
 5768                }
 5769            }
 5770        }
 5771
 5772        self.transact(cx, |this, cx| {
 5773            this.buffer.update(cx, |buffer, cx| {
 5774                let empty_str: Arc<str> = Arc::default();
 5775                buffer.edit(
 5776                    deletion_ranges
 5777                        .into_iter()
 5778                        .map(|range| (range, empty_str.clone())),
 5779                    None,
 5780                    cx,
 5781                );
 5782            });
 5783            let selections = this.selections.all::<usize>(cx);
 5784            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5785        });
 5786    }
 5787
 5788    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5789        if self.read_only(cx) {
 5790            return;
 5791        }
 5792        let selections = self
 5793            .selections
 5794            .all::<usize>(cx)
 5795            .into_iter()
 5796            .map(|s| s.range());
 5797
 5798        self.transact(cx, |this, cx| {
 5799            this.buffer.update(cx, |buffer, cx| {
 5800                buffer.autoindent_ranges(selections, cx);
 5801            });
 5802            let selections = this.selections.all::<usize>(cx);
 5803            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5804        });
 5805    }
 5806
 5807    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5808        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5809        let selections = self.selections.all::<Point>(cx);
 5810
 5811        let mut new_cursors = Vec::new();
 5812        let mut edit_ranges = Vec::new();
 5813        let mut selections = selections.iter().peekable();
 5814        while let Some(selection) = selections.next() {
 5815            let mut rows = selection.spanned_rows(false, &display_map);
 5816            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5817
 5818            // Accumulate contiguous regions of rows that we want to delete.
 5819            while let Some(next_selection) = selections.peek() {
 5820                let next_rows = next_selection.spanned_rows(false, &display_map);
 5821                if next_rows.start <= rows.end {
 5822                    rows.end = next_rows.end;
 5823                    selections.next().unwrap();
 5824                } else {
 5825                    break;
 5826                }
 5827            }
 5828
 5829            let buffer = &display_map.buffer_snapshot;
 5830            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5831            let edit_end;
 5832            let cursor_buffer_row;
 5833            if buffer.max_point().row >= rows.end.0 {
 5834                // If there's a line after the range, delete the \n from the end of the row range
 5835                // and position the cursor on the next line.
 5836                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5837                cursor_buffer_row = rows.end;
 5838            } else {
 5839                // If there isn't a line after the range, delete the \n from the line before the
 5840                // start of the row range and position the cursor there.
 5841                edit_start = edit_start.saturating_sub(1);
 5842                edit_end = buffer.len();
 5843                cursor_buffer_row = rows.start.previous_row();
 5844            }
 5845
 5846            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5847            *cursor.column_mut() =
 5848                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5849
 5850            new_cursors.push((
 5851                selection.id,
 5852                buffer.anchor_after(cursor.to_point(&display_map)),
 5853            ));
 5854            edit_ranges.push(edit_start..edit_end);
 5855        }
 5856
 5857        self.transact(cx, |this, cx| {
 5858            let buffer = this.buffer.update(cx, |buffer, cx| {
 5859                let empty_str: Arc<str> = Arc::default();
 5860                buffer.edit(
 5861                    edit_ranges
 5862                        .into_iter()
 5863                        .map(|range| (range, empty_str.clone())),
 5864                    None,
 5865                    cx,
 5866                );
 5867                buffer.snapshot(cx)
 5868            });
 5869            let new_selections = new_cursors
 5870                .into_iter()
 5871                .map(|(id, cursor)| {
 5872                    let cursor = cursor.to_point(&buffer);
 5873                    Selection {
 5874                        id,
 5875                        start: cursor,
 5876                        end: cursor,
 5877                        reversed: false,
 5878                        goal: SelectionGoal::None,
 5879                    }
 5880                })
 5881                .collect();
 5882
 5883            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5884                s.select(new_selections);
 5885            });
 5886        });
 5887    }
 5888
 5889    pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
 5890        if self.read_only(cx) {
 5891            return;
 5892        }
 5893        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5894        for selection in self.selections.all::<Point>(cx) {
 5895            let start = MultiBufferRow(selection.start.row);
 5896            // Treat single line selections as if they include the next line. Otherwise this action
 5897            // would do nothing for single line selections individual cursors.
 5898            let end = if selection.start.row == selection.end.row {
 5899                MultiBufferRow(selection.start.row + 1)
 5900            } else {
 5901                MultiBufferRow(selection.end.row)
 5902            };
 5903
 5904            if let Some(last_row_range) = row_ranges.last_mut() {
 5905                if start <= last_row_range.end {
 5906                    last_row_range.end = end;
 5907                    continue;
 5908                }
 5909            }
 5910            row_ranges.push(start..end);
 5911        }
 5912
 5913        let snapshot = self.buffer.read(cx).snapshot(cx);
 5914        let mut cursor_positions = Vec::new();
 5915        for row_range in &row_ranges {
 5916            let anchor = snapshot.anchor_before(Point::new(
 5917                row_range.end.previous_row().0,
 5918                snapshot.line_len(row_range.end.previous_row()),
 5919            ));
 5920            cursor_positions.push(anchor..anchor);
 5921        }
 5922
 5923        self.transact(cx, |this, cx| {
 5924            for row_range in row_ranges.into_iter().rev() {
 5925                for row in row_range.iter_rows().rev() {
 5926                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5927                    let next_line_row = row.next_row();
 5928                    let indent = snapshot.indent_size_for_line(next_line_row);
 5929                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5930
 5931                    let replace =
 5932                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 5933                            " "
 5934                        } else {
 5935                            ""
 5936                        };
 5937
 5938                    this.buffer.update(cx, |buffer, cx| {
 5939                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5940                    });
 5941                }
 5942            }
 5943
 5944            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5945                s.select_anchor_ranges(cursor_positions)
 5946            });
 5947        });
 5948    }
 5949
 5950    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5951        self.join_lines_impl(true, cx);
 5952    }
 5953
 5954    pub fn sort_lines_case_sensitive(
 5955        &mut self,
 5956        _: &SortLinesCaseSensitive,
 5957        cx: &mut ViewContext<Self>,
 5958    ) {
 5959        self.manipulate_lines(cx, |lines| lines.sort())
 5960    }
 5961
 5962    pub fn sort_lines_case_insensitive(
 5963        &mut self,
 5964        _: &SortLinesCaseInsensitive,
 5965        cx: &mut ViewContext<Self>,
 5966    ) {
 5967        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5968    }
 5969
 5970    pub fn unique_lines_case_insensitive(
 5971        &mut self,
 5972        _: &UniqueLinesCaseInsensitive,
 5973        cx: &mut ViewContext<Self>,
 5974    ) {
 5975        self.manipulate_lines(cx, |lines| {
 5976            let mut seen = HashSet::default();
 5977            lines.retain(|line| seen.insert(line.to_lowercase()));
 5978        })
 5979    }
 5980
 5981    pub fn unique_lines_case_sensitive(
 5982        &mut self,
 5983        _: &UniqueLinesCaseSensitive,
 5984        cx: &mut ViewContext<Self>,
 5985    ) {
 5986        self.manipulate_lines(cx, |lines| {
 5987            let mut seen = HashSet::default();
 5988            lines.retain(|line| seen.insert(*line));
 5989        })
 5990    }
 5991
 5992    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5993        let mut revert_changes = HashMap::default();
 5994        let snapshot = self.snapshot(cx);
 5995        for hunk in hunks_for_ranges(
 5996            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5997            &snapshot,
 5998        ) {
 5999            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6000        }
 6001        if !revert_changes.is_empty() {
 6002            self.transact(cx, |editor, cx| {
 6003                editor.revert(revert_changes, cx);
 6004            });
 6005        }
 6006    }
 6007
 6008    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6009        let Some(project) = self.project.clone() else {
 6010            return;
 6011        };
 6012        self.reload(project, cx).detach_and_notify_err(cx);
 6013    }
 6014
 6015    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6016        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 6017        if !revert_changes.is_empty() {
 6018            self.transact(cx, |editor, cx| {
 6019                editor.revert(revert_changes, cx);
 6020            });
 6021        }
 6022    }
 6023
 6024    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 6025        let snapshot = self.buffer.read(cx).read(cx);
 6026        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 6027            drop(snapshot);
 6028            let mut revert_changes = HashMap::default();
 6029            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6030            if !revert_changes.is_empty() {
 6031                self.revert(revert_changes, cx)
 6032            }
 6033        }
 6034    }
 6035
 6036    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6037        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6038            let project_path = buffer.read(cx).project_path(cx)?;
 6039            let project = self.project.as_ref()?.read(cx);
 6040            let entry = project.entry_for_path(&project_path, cx)?;
 6041            let parent = match &entry.canonical_path {
 6042                Some(canonical_path) => canonical_path.to_path_buf(),
 6043                None => project.absolute_path(&project_path, cx)?,
 6044            }
 6045            .parent()?
 6046            .to_path_buf();
 6047            Some(parent)
 6048        }) {
 6049            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6050        }
 6051    }
 6052
 6053    fn gather_revert_changes(
 6054        &mut self,
 6055        selections: &[Selection<Point>],
 6056        cx: &mut ViewContext<Editor>,
 6057    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6058        let mut revert_changes = HashMap::default();
 6059        let snapshot = self.snapshot(cx);
 6060        for hunk in hunks_for_selections(&snapshot, selections) {
 6061            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6062        }
 6063        revert_changes
 6064    }
 6065
 6066    pub fn prepare_revert_change(
 6067        &mut self,
 6068        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6069        hunk: &MultiBufferDiffHunk,
 6070        cx: &AppContext,
 6071    ) -> Option<()> {
 6072        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6073        let buffer = buffer.read(cx);
 6074        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6075        let original_text = change_set
 6076            .read(cx)
 6077            .base_text
 6078            .as_ref()?
 6079            .read(cx)
 6080            .as_rope()
 6081            .slice(hunk.diff_base_byte_range.clone());
 6082        let buffer_snapshot = buffer.snapshot();
 6083        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6084        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6085            probe
 6086                .0
 6087                .start
 6088                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6089                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6090        }) {
 6091            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6092            Some(())
 6093        } else {
 6094            None
 6095        }
 6096    }
 6097
 6098    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6099        self.manipulate_lines(cx, |lines| lines.reverse())
 6100    }
 6101
 6102    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6103        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6104    }
 6105
 6106    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6107    where
 6108        Fn: FnMut(&mut Vec<&str>),
 6109    {
 6110        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6111        let buffer = self.buffer.read(cx).snapshot(cx);
 6112
 6113        let mut edits = Vec::new();
 6114
 6115        let selections = self.selections.all::<Point>(cx);
 6116        let mut selections = selections.iter().peekable();
 6117        let mut contiguous_row_selections = Vec::new();
 6118        let mut new_selections = Vec::new();
 6119        let mut added_lines = 0;
 6120        let mut removed_lines = 0;
 6121
 6122        while let Some(selection) = selections.next() {
 6123            let (start_row, end_row) = consume_contiguous_rows(
 6124                &mut contiguous_row_selections,
 6125                selection,
 6126                &display_map,
 6127                &mut selections,
 6128            );
 6129
 6130            let start_point = Point::new(start_row.0, 0);
 6131            let end_point = Point::new(
 6132                end_row.previous_row().0,
 6133                buffer.line_len(end_row.previous_row()),
 6134            );
 6135            let text = buffer
 6136                .text_for_range(start_point..end_point)
 6137                .collect::<String>();
 6138
 6139            let mut lines = text.split('\n').collect_vec();
 6140
 6141            let lines_before = lines.len();
 6142            callback(&mut lines);
 6143            let lines_after = lines.len();
 6144
 6145            edits.push((start_point..end_point, lines.join("\n")));
 6146
 6147            // Selections must change based on added and removed line count
 6148            let start_row =
 6149                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6150            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6151            new_selections.push(Selection {
 6152                id: selection.id,
 6153                start: start_row,
 6154                end: end_row,
 6155                goal: SelectionGoal::None,
 6156                reversed: selection.reversed,
 6157            });
 6158
 6159            if lines_after > lines_before {
 6160                added_lines += lines_after - lines_before;
 6161            } else if lines_before > lines_after {
 6162                removed_lines += lines_before - lines_after;
 6163            }
 6164        }
 6165
 6166        self.transact(cx, |this, cx| {
 6167            let buffer = this.buffer.update(cx, |buffer, cx| {
 6168                buffer.edit(edits, None, cx);
 6169                buffer.snapshot(cx)
 6170            });
 6171
 6172            // Recalculate offsets on newly edited buffer
 6173            let new_selections = new_selections
 6174                .iter()
 6175                .map(|s| {
 6176                    let start_point = Point::new(s.start.0, 0);
 6177                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6178                    Selection {
 6179                        id: s.id,
 6180                        start: buffer.point_to_offset(start_point),
 6181                        end: buffer.point_to_offset(end_point),
 6182                        goal: s.goal,
 6183                        reversed: s.reversed,
 6184                    }
 6185                })
 6186                .collect();
 6187
 6188            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6189                s.select(new_selections);
 6190            });
 6191
 6192            this.request_autoscroll(Autoscroll::fit(), cx);
 6193        });
 6194    }
 6195
 6196    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6197        self.manipulate_text(cx, |text| text.to_uppercase())
 6198    }
 6199
 6200    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6201        self.manipulate_text(cx, |text| text.to_lowercase())
 6202    }
 6203
 6204    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6205        self.manipulate_text(cx, |text| {
 6206            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6207            // https://github.com/rutrum/convert-case/issues/16
 6208            text.split('\n')
 6209                .map(|line| line.to_case(Case::Title))
 6210                .join("\n")
 6211        })
 6212    }
 6213
 6214    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6215        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6216    }
 6217
 6218    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6219        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6220    }
 6221
 6222    pub fn convert_to_upper_camel_case(
 6223        &mut self,
 6224        _: &ConvertToUpperCamelCase,
 6225        cx: &mut ViewContext<Self>,
 6226    ) {
 6227        self.manipulate_text(cx, |text| {
 6228            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6229            // https://github.com/rutrum/convert-case/issues/16
 6230            text.split('\n')
 6231                .map(|line| line.to_case(Case::UpperCamel))
 6232                .join("\n")
 6233        })
 6234    }
 6235
 6236    pub fn convert_to_lower_camel_case(
 6237        &mut self,
 6238        _: &ConvertToLowerCamelCase,
 6239        cx: &mut ViewContext<Self>,
 6240    ) {
 6241        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6242    }
 6243
 6244    pub fn convert_to_opposite_case(
 6245        &mut self,
 6246        _: &ConvertToOppositeCase,
 6247        cx: &mut ViewContext<Self>,
 6248    ) {
 6249        self.manipulate_text(cx, |text| {
 6250            text.chars()
 6251                .fold(String::with_capacity(text.len()), |mut t, c| {
 6252                    if c.is_uppercase() {
 6253                        t.extend(c.to_lowercase());
 6254                    } else {
 6255                        t.extend(c.to_uppercase());
 6256                    }
 6257                    t
 6258                })
 6259        })
 6260    }
 6261
 6262    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6263    where
 6264        Fn: FnMut(&str) -> String,
 6265    {
 6266        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6267        let buffer = self.buffer.read(cx).snapshot(cx);
 6268
 6269        let mut new_selections = Vec::new();
 6270        let mut edits = Vec::new();
 6271        let mut selection_adjustment = 0i32;
 6272
 6273        for selection in self.selections.all::<usize>(cx) {
 6274            let selection_is_empty = selection.is_empty();
 6275
 6276            let (start, end) = if selection_is_empty {
 6277                let word_range = movement::surrounding_word(
 6278                    &display_map,
 6279                    selection.start.to_display_point(&display_map),
 6280                );
 6281                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6282                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6283                (start, end)
 6284            } else {
 6285                (selection.start, selection.end)
 6286            };
 6287
 6288            let text = buffer.text_for_range(start..end).collect::<String>();
 6289            let old_length = text.len() as i32;
 6290            let text = callback(&text);
 6291
 6292            new_selections.push(Selection {
 6293                start: (start as i32 - selection_adjustment) as usize,
 6294                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6295                goal: SelectionGoal::None,
 6296                ..selection
 6297            });
 6298
 6299            selection_adjustment += old_length - text.len() as i32;
 6300
 6301            edits.push((start..end, text));
 6302        }
 6303
 6304        self.transact(cx, |this, cx| {
 6305            this.buffer.update(cx, |buffer, cx| {
 6306                buffer.edit(edits, None, cx);
 6307            });
 6308
 6309            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6310                s.select(new_selections);
 6311            });
 6312
 6313            this.request_autoscroll(Autoscroll::fit(), cx);
 6314        });
 6315    }
 6316
 6317    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6318        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6319        let buffer = &display_map.buffer_snapshot;
 6320        let selections = self.selections.all::<Point>(cx);
 6321
 6322        let mut edits = Vec::new();
 6323        let mut selections_iter = selections.iter().peekable();
 6324        while let Some(selection) = selections_iter.next() {
 6325            let mut rows = selection.spanned_rows(false, &display_map);
 6326            // duplicate line-wise
 6327            if whole_lines || selection.start == selection.end {
 6328                // Avoid duplicating the same lines twice.
 6329                while let Some(next_selection) = selections_iter.peek() {
 6330                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6331                    if next_rows.start < rows.end {
 6332                        rows.end = next_rows.end;
 6333                        selections_iter.next().unwrap();
 6334                    } else {
 6335                        break;
 6336                    }
 6337                }
 6338
 6339                // Copy the text from the selected row region and splice it either at the start
 6340                // or end of the region.
 6341                let start = Point::new(rows.start.0, 0);
 6342                let end = Point::new(
 6343                    rows.end.previous_row().0,
 6344                    buffer.line_len(rows.end.previous_row()),
 6345                );
 6346                let text = buffer
 6347                    .text_for_range(start..end)
 6348                    .chain(Some("\n"))
 6349                    .collect::<String>();
 6350                let insert_location = if upwards {
 6351                    Point::new(rows.end.0, 0)
 6352                } else {
 6353                    start
 6354                };
 6355                edits.push((insert_location..insert_location, text));
 6356            } else {
 6357                // duplicate character-wise
 6358                let start = selection.start;
 6359                let end = selection.end;
 6360                let text = buffer.text_for_range(start..end).collect::<String>();
 6361                edits.push((selection.end..selection.end, text));
 6362            }
 6363        }
 6364
 6365        self.transact(cx, |this, cx| {
 6366            this.buffer.update(cx, |buffer, cx| {
 6367                buffer.edit(edits, None, cx);
 6368            });
 6369
 6370            this.request_autoscroll(Autoscroll::fit(), cx);
 6371        });
 6372    }
 6373
 6374    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6375        self.duplicate(true, true, cx);
 6376    }
 6377
 6378    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6379        self.duplicate(false, true, cx);
 6380    }
 6381
 6382    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6383        self.duplicate(false, false, cx);
 6384    }
 6385
 6386    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6387        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6388        let buffer = self.buffer.read(cx).snapshot(cx);
 6389
 6390        let mut edits = Vec::new();
 6391        let mut unfold_ranges = Vec::new();
 6392        let mut refold_creases = Vec::new();
 6393
 6394        let selections = self.selections.all::<Point>(cx);
 6395        let mut selections = selections.iter().peekable();
 6396        let mut contiguous_row_selections = Vec::new();
 6397        let mut new_selections = Vec::new();
 6398
 6399        while let Some(selection) = selections.next() {
 6400            // Find all the selections that span a contiguous row range
 6401            let (start_row, end_row) = consume_contiguous_rows(
 6402                &mut contiguous_row_selections,
 6403                selection,
 6404                &display_map,
 6405                &mut selections,
 6406            );
 6407
 6408            // Move the text spanned by the row range to be before the line preceding the row range
 6409            if start_row.0 > 0 {
 6410                let range_to_move = Point::new(
 6411                    start_row.previous_row().0,
 6412                    buffer.line_len(start_row.previous_row()),
 6413                )
 6414                    ..Point::new(
 6415                        end_row.previous_row().0,
 6416                        buffer.line_len(end_row.previous_row()),
 6417                    );
 6418                let insertion_point = display_map
 6419                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6420                    .0;
 6421
 6422                // Don't move lines across excerpts
 6423                if buffer
 6424                    .excerpt_boundaries_in_range((
 6425                        Bound::Excluded(insertion_point),
 6426                        Bound::Included(range_to_move.end),
 6427                    ))
 6428                    .next()
 6429                    .is_none()
 6430                {
 6431                    let text = buffer
 6432                        .text_for_range(range_to_move.clone())
 6433                        .flat_map(|s| s.chars())
 6434                        .skip(1)
 6435                        .chain(['\n'])
 6436                        .collect::<String>();
 6437
 6438                    edits.push((
 6439                        buffer.anchor_after(range_to_move.start)
 6440                            ..buffer.anchor_before(range_to_move.end),
 6441                        String::new(),
 6442                    ));
 6443                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6444                    edits.push((insertion_anchor..insertion_anchor, text));
 6445
 6446                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6447
 6448                    // Move selections up
 6449                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6450                        |mut selection| {
 6451                            selection.start.row -= row_delta;
 6452                            selection.end.row -= row_delta;
 6453                            selection
 6454                        },
 6455                    ));
 6456
 6457                    // Move folds up
 6458                    unfold_ranges.push(range_to_move.clone());
 6459                    for fold in display_map.folds_in_range(
 6460                        buffer.anchor_before(range_to_move.start)
 6461                            ..buffer.anchor_after(range_to_move.end),
 6462                    ) {
 6463                        let mut start = fold.range.start.to_point(&buffer);
 6464                        let mut end = fold.range.end.to_point(&buffer);
 6465                        start.row -= row_delta;
 6466                        end.row -= row_delta;
 6467                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6468                    }
 6469                }
 6470            }
 6471
 6472            // If we didn't move line(s), preserve the existing selections
 6473            new_selections.append(&mut contiguous_row_selections);
 6474        }
 6475
 6476        self.transact(cx, |this, cx| {
 6477            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6478            this.buffer.update(cx, |buffer, cx| {
 6479                for (range, text) in edits {
 6480                    buffer.edit([(range, text)], None, cx);
 6481                }
 6482            });
 6483            this.fold_creases(refold_creases, true, cx);
 6484            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6485                s.select(new_selections);
 6486            })
 6487        });
 6488    }
 6489
 6490    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6491        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6492        let buffer = self.buffer.read(cx).snapshot(cx);
 6493
 6494        let mut edits = Vec::new();
 6495        let mut unfold_ranges = Vec::new();
 6496        let mut refold_creases = Vec::new();
 6497
 6498        let selections = self.selections.all::<Point>(cx);
 6499        let mut selections = selections.iter().peekable();
 6500        let mut contiguous_row_selections = Vec::new();
 6501        let mut new_selections = Vec::new();
 6502
 6503        while let Some(selection) = selections.next() {
 6504            // Find all the selections that span a contiguous row range
 6505            let (start_row, end_row) = consume_contiguous_rows(
 6506                &mut contiguous_row_selections,
 6507                selection,
 6508                &display_map,
 6509                &mut selections,
 6510            );
 6511
 6512            // Move the text spanned by the row range to be after the last line of the row range
 6513            if end_row.0 <= buffer.max_point().row {
 6514                let range_to_move =
 6515                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6516                let insertion_point = display_map
 6517                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6518                    .0;
 6519
 6520                // Don't move lines across excerpt boundaries
 6521                if buffer
 6522                    .excerpt_boundaries_in_range((
 6523                        Bound::Excluded(range_to_move.start),
 6524                        Bound::Included(insertion_point),
 6525                    ))
 6526                    .next()
 6527                    .is_none()
 6528                {
 6529                    let mut text = String::from("\n");
 6530                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6531                    text.pop(); // Drop trailing newline
 6532                    edits.push((
 6533                        buffer.anchor_after(range_to_move.start)
 6534                            ..buffer.anchor_before(range_to_move.end),
 6535                        String::new(),
 6536                    ));
 6537                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6538                    edits.push((insertion_anchor..insertion_anchor, text));
 6539
 6540                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6541
 6542                    // Move selections down
 6543                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6544                        |mut selection| {
 6545                            selection.start.row += row_delta;
 6546                            selection.end.row += row_delta;
 6547                            selection
 6548                        },
 6549                    ));
 6550
 6551                    // Move folds down
 6552                    unfold_ranges.push(range_to_move.clone());
 6553                    for fold in display_map.folds_in_range(
 6554                        buffer.anchor_before(range_to_move.start)
 6555                            ..buffer.anchor_after(range_to_move.end),
 6556                    ) {
 6557                        let mut start = fold.range.start.to_point(&buffer);
 6558                        let mut end = fold.range.end.to_point(&buffer);
 6559                        start.row += row_delta;
 6560                        end.row += row_delta;
 6561                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6562                    }
 6563                }
 6564            }
 6565
 6566            // If we didn't move line(s), preserve the existing selections
 6567            new_selections.append(&mut contiguous_row_selections);
 6568        }
 6569
 6570        self.transact(cx, |this, cx| {
 6571            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6572            this.buffer.update(cx, |buffer, cx| {
 6573                for (range, text) in edits {
 6574                    buffer.edit([(range, text)], None, cx);
 6575                }
 6576            });
 6577            this.fold_creases(refold_creases, true, cx);
 6578            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6579        });
 6580    }
 6581
 6582    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6583        let text_layout_details = &self.text_layout_details(cx);
 6584        self.transact(cx, |this, cx| {
 6585            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6586                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6587                let line_mode = s.line_mode;
 6588                s.move_with(|display_map, selection| {
 6589                    if !selection.is_empty() || line_mode {
 6590                        return;
 6591                    }
 6592
 6593                    let mut head = selection.head();
 6594                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6595                    if head.column() == display_map.line_len(head.row()) {
 6596                        transpose_offset = display_map
 6597                            .buffer_snapshot
 6598                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6599                    }
 6600
 6601                    if transpose_offset == 0 {
 6602                        return;
 6603                    }
 6604
 6605                    *head.column_mut() += 1;
 6606                    head = display_map.clip_point(head, Bias::Right);
 6607                    let goal = SelectionGoal::HorizontalPosition(
 6608                        display_map
 6609                            .x_for_display_point(head, text_layout_details)
 6610                            .into(),
 6611                    );
 6612                    selection.collapse_to(head, goal);
 6613
 6614                    let transpose_start = display_map
 6615                        .buffer_snapshot
 6616                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6617                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6618                        let transpose_end = display_map
 6619                            .buffer_snapshot
 6620                            .clip_offset(transpose_offset + 1, Bias::Right);
 6621                        if let Some(ch) =
 6622                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6623                        {
 6624                            edits.push((transpose_start..transpose_offset, String::new()));
 6625                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6626                        }
 6627                    }
 6628                });
 6629                edits
 6630            });
 6631            this.buffer
 6632                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6633            let selections = this.selections.all::<usize>(cx);
 6634            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6635                s.select(selections);
 6636            });
 6637        });
 6638    }
 6639
 6640    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6641        self.rewrap_impl(IsVimMode::No, cx)
 6642    }
 6643
 6644    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6645        let buffer = self.buffer.read(cx).snapshot(cx);
 6646        let selections = self.selections.all::<Point>(cx);
 6647        let mut selections = selections.iter().peekable();
 6648
 6649        let mut edits = Vec::new();
 6650        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6651
 6652        while let Some(selection) = selections.next() {
 6653            let mut start_row = selection.start.row;
 6654            let mut end_row = selection.end.row;
 6655
 6656            // Skip selections that overlap with a range that has already been rewrapped.
 6657            let selection_range = start_row..end_row;
 6658            if rewrapped_row_ranges
 6659                .iter()
 6660                .any(|range| range.overlaps(&selection_range))
 6661            {
 6662                continue;
 6663            }
 6664
 6665            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6666
 6667            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6668                match language_scope.language_name().0.as_ref() {
 6669                    "Markdown" | "Plain Text" => {
 6670                        should_rewrap = true;
 6671                    }
 6672                    _ => {}
 6673                }
 6674            }
 6675
 6676            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6677
 6678            // Since not all lines in the selection may be at the same indent
 6679            // level, choose the indent size that is the most common between all
 6680            // of the lines.
 6681            //
 6682            // If there is a tie, we use the deepest indent.
 6683            let (indent_size, indent_end) = {
 6684                let mut indent_size_occurrences = HashMap::default();
 6685                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6686
 6687                for row in start_row..=end_row {
 6688                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6689                    rows_by_indent_size.entry(indent).or_default().push(row);
 6690                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6691                }
 6692
 6693                let indent_size = indent_size_occurrences
 6694                    .into_iter()
 6695                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6696                    .map(|(indent, _)| indent)
 6697                    .unwrap_or_default();
 6698                let row = rows_by_indent_size[&indent_size][0];
 6699                let indent_end = Point::new(row, indent_size.len);
 6700
 6701                (indent_size, indent_end)
 6702            };
 6703
 6704            let mut line_prefix = indent_size.chars().collect::<String>();
 6705
 6706            if let Some(comment_prefix) =
 6707                buffer
 6708                    .language_scope_at(selection.head())
 6709                    .and_then(|language| {
 6710                        language
 6711                            .line_comment_prefixes()
 6712                            .iter()
 6713                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6714                            .cloned()
 6715                    })
 6716            {
 6717                line_prefix.push_str(&comment_prefix);
 6718                should_rewrap = true;
 6719            }
 6720
 6721            if !should_rewrap {
 6722                continue;
 6723            }
 6724
 6725            if selection.is_empty() {
 6726                'expand_upwards: while start_row > 0 {
 6727                    let prev_row = start_row - 1;
 6728                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6729                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6730                    {
 6731                        start_row = prev_row;
 6732                    } else {
 6733                        break 'expand_upwards;
 6734                    }
 6735                }
 6736
 6737                'expand_downwards: while end_row < buffer.max_point().row {
 6738                    let next_row = end_row + 1;
 6739                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6740                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6741                    {
 6742                        end_row = next_row;
 6743                    } else {
 6744                        break 'expand_downwards;
 6745                    }
 6746                }
 6747            }
 6748
 6749            let start = Point::new(start_row, 0);
 6750            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6751            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6752            let Some(lines_without_prefixes) = selection_text
 6753                .lines()
 6754                .map(|line| {
 6755                    line.strip_prefix(&line_prefix)
 6756                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6757                        .ok_or_else(|| {
 6758                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6759                        })
 6760                })
 6761                .collect::<Result<Vec<_>, _>>()
 6762                .log_err()
 6763            else {
 6764                continue;
 6765            };
 6766
 6767            let wrap_column = buffer
 6768                .settings_at(Point::new(start_row, 0), cx)
 6769                .preferred_line_length as usize;
 6770            let wrapped_text = wrap_with_prefix(
 6771                line_prefix,
 6772                lines_without_prefixes.join(" "),
 6773                wrap_column,
 6774                tab_size,
 6775            );
 6776
 6777            // TODO: should always use char-based diff while still supporting cursor behavior that
 6778            // matches vim.
 6779            let diff = match is_vim_mode {
 6780                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6781                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6782            };
 6783            let mut offset = start.to_offset(&buffer);
 6784            let mut moved_since_edit = true;
 6785
 6786            for change in diff.iter_all_changes() {
 6787                let value = change.value();
 6788                match change.tag() {
 6789                    ChangeTag::Equal => {
 6790                        offset += value.len();
 6791                        moved_since_edit = true;
 6792                    }
 6793                    ChangeTag::Delete => {
 6794                        let start = buffer.anchor_after(offset);
 6795                        let end = buffer.anchor_before(offset + value.len());
 6796
 6797                        if moved_since_edit {
 6798                            edits.push((start..end, String::new()));
 6799                        } else {
 6800                            edits.last_mut().unwrap().0.end = end;
 6801                        }
 6802
 6803                        offset += value.len();
 6804                        moved_since_edit = false;
 6805                    }
 6806                    ChangeTag::Insert => {
 6807                        if moved_since_edit {
 6808                            let anchor = buffer.anchor_after(offset);
 6809                            edits.push((anchor..anchor, value.to_string()));
 6810                        } else {
 6811                            edits.last_mut().unwrap().1.push_str(value);
 6812                        }
 6813
 6814                        moved_since_edit = false;
 6815                    }
 6816                }
 6817            }
 6818
 6819            rewrapped_row_ranges.push(start_row..=end_row);
 6820        }
 6821
 6822        self.buffer
 6823            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6824    }
 6825
 6826    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6827        let mut text = String::new();
 6828        let buffer = self.buffer.read(cx).snapshot(cx);
 6829        let mut selections = self.selections.all::<Point>(cx);
 6830        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6831        {
 6832            let max_point = buffer.max_point();
 6833            let mut is_first = true;
 6834            for selection in &mut selections {
 6835                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6836                if is_entire_line {
 6837                    selection.start = Point::new(selection.start.row, 0);
 6838                    if !selection.is_empty() && selection.end.column == 0 {
 6839                        selection.end = cmp::min(max_point, selection.end);
 6840                    } else {
 6841                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6842                    }
 6843                    selection.goal = SelectionGoal::None;
 6844                }
 6845                if is_first {
 6846                    is_first = false;
 6847                } else {
 6848                    text += "\n";
 6849                }
 6850                let mut len = 0;
 6851                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6852                    text.push_str(chunk);
 6853                    len += chunk.len();
 6854                }
 6855                clipboard_selections.push(ClipboardSelection {
 6856                    len,
 6857                    is_entire_line,
 6858                    first_line_indent: buffer
 6859                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6860                        .len,
 6861                });
 6862            }
 6863        }
 6864
 6865        self.transact(cx, |this, cx| {
 6866            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6867                s.select(selections);
 6868            });
 6869            this.insert("", cx);
 6870        });
 6871        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6872    }
 6873
 6874    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6875        let item = self.cut_common(cx);
 6876        cx.write_to_clipboard(item);
 6877    }
 6878
 6879    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6880        self.change_selections(None, cx, |s| {
 6881            s.move_with(|snapshot, sel| {
 6882                if sel.is_empty() {
 6883                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6884                }
 6885            });
 6886        });
 6887        let item = self.cut_common(cx);
 6888        cx.set_global(KillRing(item))
 6889    }
 6890
 6891    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6892        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6893            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6894                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6895            } else {
 6896                return;
 6897            }
 6898        } else {
 6899            return;
 6900        };
 6901        self.do_paste(&text, metadata, false, cx);
 6902    }
 6903
 6904    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6905        let selections = self.selections.all::<Point>(cx);
 6906        let buffer = self.buffer.read(cx).read(cx);
 6907        let mut text = String::new();
 6908
 6909        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6910        {
 6911            let max_point = buffer.max_point();
 6912            let mut is_first = true;
 6913            for selection in selections.iter() {
 6914                let mut start = selection.start;
 6915                let mut end = selection.end;
 6916                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6917                if is_entire_line {
 6918                    start = Point::new(start.row, 0);
 6919                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6920                }
 6921                if is_first {
 6922                    is_first = false;
 6923                } else {
 6924                    text += "\n";
 6925                }
 6926                let mut len = 0;
 6927                for chunk in buffer.text_for_range(start..end) {
 6928                    text.push_str(chunk);
 6929                    len += chunk.len();
 6930                }
 6931                clipboard_selections.push(ClipboardSelection {
 6932                    len,
 6933                    is_entire_line,
 6934                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6935                });
 6936            }
 6937        }
 6938
 6939        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6940            text,
 6941            clipboard_selections,
 6942        ));
 6943    }
 6944
 6945    pub fn do_paste(
 6946        &mut self,
 6947        text: &String,
 6948        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6949        handle_entire_lines: bool,
 6950        cx: &mut ViewContext<Self>,
 6951    ) {
 6952        if self.read_only(cx) {
 6953            return;
 6954        }
 6955
 6956        let clipboard_text = Cow::Borrowed(text);
 6957
 6958        self.transact(cx, |this, cx| {
 6959            if let Some(mut clipboard_selections) = clipboard_selections {
 6960                let old_selections = this.selections.all::<usize>(cx);
 6961                let all_selections_were_entire_line =
 6962                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6963                let first_selection_indent_column =
 6964                    clipboard_selections.first().map(|s| s.first_line_indent);
 6965                if clipboard_selections.len() != old_selections.len() {
 6966                    clipboard_selections.drain(..);
 6967                }
 6968                let cursor_offset = this.selections.last::<usize>(cx).head();
 6969                let mut auto_indent_on_paste = true;
 6970
 6971                this.buffer.update(cx, |buffer, cx| {
 6972                    let snapshot = buffer.read(cx);
 6973                    auto_indent_on_paste =
 6974                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6975
 6976                    let mut start_offset = 0;
 6977                    let mut edits = Vec::new();
 6978                    let mut original_indent_columns = Vec::new();
 6979                    for (ix, selection) in old_selections.iter().enumerate() {
 6980                        let to_insert;
 6981                        let entire_line;
 6982                        let original_indent_column;
 6983                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6984                            let end_offset = start_offset + clipboard_selection.len;
 6985                            to_insert = &clipboard_text[start_offset..end_offset];
 6986                            entire_line = clipboard_selection.is_entire_line;
 6987                            start_offset = end_offset + 1;
 6988                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6989                        } else {
 6990                            to_insert = clipboard_text.as_str();
 6991                            entire_line = all_selections_were_entire_line;
 6992                            original_indent_column = first_selection_indent_column
 6993                        }
 6994
 6995                        // If the corresponding selection was empty when this slice of the
 6996                        // clipboard text was written, then the entire line containing the
 6997                        // selection was copied. If this selection is also currently empty,
 6998                        // then paste the line before the current line of the buffer.
 6999                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7000                            let column = selection.start.to_point(&snapshot).column as usize;
 7001                            let line_start = selection.start - column;
 7002                            line_start..line_start
 7003                        } else {
 7004                            selection.range()
 7005                        };
 7006
 7007                        edits.push((range, to_insert));
 7008                        original_indent_columns.extend(original_indent_column);
 7009                    }
 7010                    drop(snapshot);
 7011
 7012                    buffer.edit(
 7013                        edits,
 7014                        if auto_indent_on_paste {
 7015                            Some(AutoindentMode::Block {
 7016                                original_indent_columns,
 7017                            })
 7018                        } else {
 7019                            None
 7020                        },
 7021                        cx,
 7022                    );
 7023                });
 7024
 7025                let selections = this.selections.all::<usize>(cx);
 7026                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7027            } else {
 7028                this.insert(&clipboard_text, cx);
 7029            }
 7030        });
 7031    }
 7032
 7033    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7034        if let Some(item) = cx.read_from_clipboard() {
 7035            let entries = item.entries();
 7036
 7037            match entries.first() {
 7038                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7039                // of all the pasted entries.
 7040                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7041                    .do_paste(
 7042                        clipboard_string.text(),
 7043                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7044                        true,
 7045                        cx,
 7046                    ),
 7047                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7048            }
 7049        }
 7050    }
 7051
 7052    pub fn undo(&mut self, _: &Undo, 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.undo(cx)) {
 7058            if let 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            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7070        }
 7071    }
 7072
 7073    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7074        if self.read_only(cx) {
 7075            return;
 7076        }
 7077
 7078        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7079            if let Some((_, Some(selections))) =
 7080                self.selection_history.transaction(transaction_id).cloned()
 7081            {
 7082                self.change_selections(None, cx, |s| {
 7083                    s.select_anchors(selections.to_vec());
 7084                });
 7085            }
 7086            self.request_autoscroll(Autoscroll::fit(), cx);
 7087            self.unmark_text(cx);
 7088            self.refresh_inline_completion(true, false, cx);
 7089            cx.emit(EditorEvent::Edited { transaction_id });
 7090        }
 7091    }
 7092
 7093    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7094        self.buffer
 7095            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7096    }
 7097
 7098    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7099        self.buffer
 7100            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7101    }
 7102
 7103    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7104        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7105            let line_mode = s.line_mode;
 7106            s.move_with(|map, selection| {
 7107                let cursor = if selection.is_empty() && !line_mode {
 7108                    movement::left(map, selection.start)
 7109                } else {
 7110                    selection.start
 7111                };
 7112                selection.collapse_to(cursor, SelectionGoal::None);
 7113            });
 7114        })
 7115    }
 7116
 7117    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7118        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7119            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7120        })
 7121    }
 7122
 7123    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7124        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7125            let line_mode = s.line_mode;
 7126            s.move_with(|map, selection| {
 7127                let cursor = if selection.is_empty() && !line_mode {
 7128                    movement::right(map, selection.end)
 7129                } else {
 7130                    selection.end
 7131                };
 7132                selection.collapse_to(cursor, SelectionGoal::None)
 7133            });
 7134        })
 7135    }
 7136
 7137    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7138        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7139            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7140        })
 7141    }
 7142
 7143    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7144        if self.take_rename(true, cx).is_some() {
 7145            return;
 7146        }
 7147
 7148        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7149            cx.propagate();
 7150            return;
 7151        }
 7152
 7153        let text_layout_details = &self.text_layout_details(cx);
 7154        let selection_count = self.selections.count();
 7155        let first_selection = self.selections.first_anchor();
 7156
 7157        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7158            let line_mode = s.line_mode;
 7159            s.move_with(|map, selection| {
 7160                if !selection.is_empty() && !line_mode {
 7161                    selection.goal = SelectionGoal::None;
 7162                }
 7163                let (cursor, goal) = movement::up(
 7164                    map,
 7165                    selection.start,
 7166                    selection.goal,
 7167                    false,
 7168                    text_layout_details,
 7169                );
 7170                selection.collapse_to(cursor, goal);
 7171            });
 7172        });
 7173
 7174        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7175        {
 7176            cx.propagate();
 7177        }
 7178    }
 7179
 7180    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7181        if self.take_rename(true, cx).is_some() {
 7182            return;
 7183        }
 7184
 7185        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7186            cx.propagate();
 7187            return;
 7188        }
 7189
 7190        let text_layout_details = &self.text_layout_details(cx);
 7191
 7192        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7193            let line_mode = s.line_mode;
 7194            s.move_with(|map, selection| {
 7195                if !selection.is_empty() && !line_mode {
 7196                    selection.goal = SelectionGoal::None;
 7197                }
 7198                let (cursor, goal) = movement::up_by_rows(
 7199                    map,
 7200                    selection.start,
 7201                    action.lines,
 7202                    selection.goal,
 7203                    false,
 7204                    text_layout_details,
 7205                );
 7206                selection.collapse_to(cursor, goal);
 7207            });
 7208        })
 7209    }
 7210
 7211    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7212        if self.take_rename(true, cx).is_some() {
 7213            return;
 7214        }
 7215
 7216        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7217            cx.propagate();
 7218            return;
 7219        }
 7220
 7221        let text_layout_details = &self.text_layout_details(cx);
 7222
 7223        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7224            let line_mode = s.line_mode;
 7225            s.move_with(|map, selection| {
 7226                if !selection.is_empty() && !line_mode {
 7227                    selection.goal = SelectionGoal::None;
 7228                }
 7229                let (cursor, goal) = movement::down_by_rows(
 7230                    map,
 7231                    selection.start,
 7232                    action.lines,
 7233                    selection.goal,
 7234                    false,
 7235                    text_layout_details,
 7236                );
 7237                selection.collapse_to(cursor, goal);
 7238            });
 7239        })
 7240    }
 7241
 7242    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7243        let text_layout_details = &self.text_layout_details(cx);
 7244        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7245            s.move_heads_with(|map, head, goal| {
 7246                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7247            })
 7248        })
 7249    }
 7250
 7251    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7252        let text_layout_details = &self.text_layout_details(cx);
 7253        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7254            s.move_heads_with(|map, head, goal| {
 7255                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7256            })
 7257        })
 7258    }
 7259
 7260    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7261        let Some(row_count) = self.visible_row_count() else {
 7262            return;
 7263        };
 7264
 7265        let text_layout_details = &self.text_layout_details(cx);
 7266
 7267        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7268            s.move_heads_with(|map, head, goal| {
 7269                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7270            })
 7271        })
 7272    }
 7273
 7274    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7275        if self.take_rename(true, cx).is_some() {
 7276            return;
 7277        }
 7278
 7279        if self
 7280            .context_menu
 7281            .borrow_mut()
 7282            .as_mut()
 7283            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7284            .unwrap_or(false)
 7285        {
 7286            return;
 7287        }
 7288
 7289        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7290            cx.propagate();
 7291            return;
 7292        }
 7293
 7294        let Some(row_count) = self.visible_row_count() else {
 7295            return;
 7296        };
 7297
 7298        let autoscroll = if action.center_cursor {
 7299            Autoscroll::center()
 7300        } else {
 7301            Autoscroll::fit()
 7302        };
 7303
 7304        let text_layout_details = &self.text_layout_details(cx);
 7305
 7306        self.change_selections(Some(autoscroll), cx, |s| {
 7307            let line_mode = s.line_mode;
 7308            s.move_with(|map, selection| {
 7309                if !selection.is_empty() && !line_mode {
 7310                    selection.goal = SelectionGoal::None;
 7311                }
 7312                let (cursor, goal) = movement::up_by_rows(
 7313                    map,
 7314                    selection.end,
 7315                    row_count,
 7316                    selection.goal,
 7317                    false,
 7318                    text_layout_details,
 7319                );
 7320                selection.collapse_to(cursor, goal);
 7321            });
 7322        });
 7323    }
 7324
 7325    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7326        let text_layout_details = &self.text_layout_details(cx);
 7327        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7328            s.move_heads_with(|map, head, goal| {
 7329                movement::up(map, head, goal, false, text_layout_details)
 7330            })
 7331        })
 7332    }
 7333
 7334    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7335        self.take_rename(true, cx);
 7336
 7337        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7338            cx.propagate();
 7339            return;
 7340        }
 7341
 7342        let text_layout_details = &self.text_layout_details(cx);
 7343        let selection_count = self.selections.count();
 7344        let first_selection = self.selections.first_anchor();
 7345
 7346        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7347            let line_mode = s.line_mode;
 7348            s.move_with(|map, selection| {
 7349                if !selection.is_empty() && !line_mode {
 7350                    selection.goal = SelectionGoal::None;
 7351                }
 7352                let (cursor, goal) = movement::down(
 7353                    map,
 7354                    selection.end,
 7355                    selection.goal,
 7356                    false,
 7357                    text_layout_details,
 7358                );
 7359                selection.collapse_to(cursor, goal);
 7360            });
 7361        });
 7362
 7363        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7364        {
 7365            cx.propagate();
 7366        }
 7367    }
 7368
 7369    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7370        let Some(row_count) = self.visible_row_count() else {
 7371            return;
 7372        };
 7373
 7374        let text_layout_details = &self.text_layout_details(cx);
 7375
 7376        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7377            s.move_heads_with(|map, head, goal| {
 7378                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7379            })
 7380        })
 7381    }
 7382
 7383    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7384        if self.take_rename(true, cx).is_some() {
 7385            return;
 7386        }
 7387
 7388        if self
 7389            .context_menu
 7390            .borrow_mut()
 7391            .as_mut()
 7392            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7393            .unwrap_or(false)
 7394        {
 7395            return;
 7396        }
 7397
 7398        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7399            cx.propagate();
 7400            return;
 7401        }
 7402
 7403        let Some(row_count) = self.visible_row_count() else {
 7404            return;
 7405        };
 7406
 7407        let autoscroll = if action.center_cursor {
 7408            Autoscroll::center()
 7409        } else {
 7410            Autoscroll::fit()
 7411        };
 7412
 7413        let text_layout_details = &self.text_layout_details(cx);
 7414        self.change_selections(Some(autoscroll), cx, |s| {
 7415            let line_mode = s.line_mode;
 7416            s.move_with(|map, selection| {
 7417                if !selection.is_empty() && !line_mode {
 7418                    selection.goal = SelectionGoal::None;
 7419                }
 7420                let (cursor, goal) = movement::down_by_rows(
 7421                    map,
 7422                    selection.end,
 7423                    row_count,
 7424                    selection.goal,
 7425                    false,
 7426                    text_layout_details,
 7427                );
 7428                selection.collapse_to(cursor, goal);
 7429            });
 7430        });
 7431    }
 7432
 7433    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7434        let text_layout_details = &self.text_layout_details(cx);
 7435        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7436            s.move_heads_with(|map, head, goal| {
 7437                movement::down(map, head, goal, false, text_layout_details)
 7438            })
 7439        });
 7440    }
 7441
 7442    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7443        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7444            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7445        }
 7446    }
 7447
 7448    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7449        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7450            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7451        }
 7452    }
 7453
 7454    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7455        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7456            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7457        }
 7458    }
 7459
 7460    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7461        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7462            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7463        }
 7464    }
 7465
 7466    pub fn move_to_previous_word_start(
 7467        &mut self,
 7468        _: &MoveToPreviousWordStart,
 7469        cx: &mut ViewContext<Self>,
 7470    ) {
 7471        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7472            s.move_cursors_with(|map, head, _| {
 7473                (
 7474                    movement::previous_word_start(map, head),
 7475                    SelectionGoal::None,
 7476                )
 7477            });
 7478        })
 7479    }
 7480
 7481    pub fn move_to_previous_subword_start(
 7482        &mut self,
 7483        _: &MoveToPreviousSubwordStart,
 7484        cx: &mut ViewContext<Self>,
 7485    ) {
 7486        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7487            s.move_cursors_with(|map, head, _| {
 7488                (
 7489                    movement::previous_subword_start(map, head),
 7490                    SelectionGoal::None,
 7491                )
 7492            });
 7493        })
 7494    }
 7495
 7496    pub fn select_to_previous_word_start(
 7497        &mut self,
 7498        _: &SelectToPreviousWordStart,
 7499        cx: &mut ViewContext<Self>,
 7500    ) {
 7501        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7502            s.move_heads_with(|map, head, _| {
 7503                (
 7504                    movement::previous_word_start(map, head),
 7505                    SelectionGoal::None,
 7506                )
 7507            });
 7508        })
 7509    }
 7510
 7511    pub fn select_to_previous_subword_start(
 7512        &mut self,
 7513        _: &SelectToPreviousSubwordStart,
 7514        cx: &mut ViewContext<Self>,
 7515    ) {
 7516        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7517            s.move_heads_with(|map, head, _| {
 7518                (
 7519                    movement::previous_subword_start(map, head),
 7520                    SelectionGoal::None,
 7521                )
 7522            });
 7523        })
 7524    }
 7525
 7526    pub fn delete_to_previous_word_start(
 7527        &mut self,
 7528        action: &DeleteToPreviousWordStart,
 7529        cx: &mut ViewContext<Self>,
 7530    ) {
 7531        self.transact(cx, |this, cx| {
 7532            this.select_autoclose_pair(cx);
 7533            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7534                let line_mode = s.line_mode;
 7535                s.move_with(|map, selection| {
 7536                    if selection.is_empty() && !line_mode {
 7537                        let cursor = if action.ignore_newlines {
 7538                            movement::previous_word_start(map, selection.head())
 7539                        } else {
 7540                            movement::previous_word_start_or_newline(map, selection.head())
 7541                        };
 7542                        selection.set_head(cursor, SelectionGoal::None);
 7543                    }
 7544                });
 7545            });
 7546            this.insert("", cx);
 7547        });
 7548    }
 7549
 7550    pub fn delete_to_previous_subword_start(
 7551        &mut self,
 7552        _: &DeleteToPreviousSubwordStart,
 7553        cx: &mut ViewContext<Self>,
 7554    ) {
 7555        self.transact(cx, |this, cx| {
 7556            this.select_autoclose_pair(cx);
 7557            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7558                let line_mode = s.line_mode;
 7559                s.move_with(|map, selection| {
 7560                    if selection.is_empty() && !line_mode {
 7561                        let cursor = movement::previous_subword_start(map, selection.head());
 7562                        selection.set_head(cursor, SelectionGoal::None);
 7563                    }
 7564                });
 7565            });
 7566            this.insert("", cx);
 7567        });
 7568    }
 7569
 7570    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7571        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7572            s.move_cursors_with(|map, head, _| {
 7573                (movement::next_word_end(map, head), SelectionGoal::None)
 7574            });
 7575        })
 7576    }
 7577
 7578    pub fn move_to_next_subword_end(
 7579        &mut self,
 7580        _: &MoveToNextSubwordEnd,
 7581        cx: &mut ViewContext<Self>,
 7582    ) {
 7583        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7584            s.move_cursors_with(|map, head, _| {
 7585                (movement::next_subword_end(map, head), SelectionGoal::None)
 7586            });
 7587        })
 7588    }
 7589
 7590    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7591        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7592            s.move_heads_with(|map, head, _| {
 7593                (movement::next_word_end(map, head), SelectionGoal::None)
 7594            });
 7595        })
 7596    }
 7597
 7598    pub fn select_to_next_subword_end(
 7599        &mut self,
 7600        _: &SelectToNextSubwordEnd,
 7601        cx: &mut ViewContext<Self>,
 7602    ) {
 7603        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7604            s.move_heads_with(|map, head, _| {
 7605                (movement::next_subword_end(map, head), SelectionGoal::None)
 7606            });
 7607        })
 7608    }
 7609
 7610    pub fn delete_to_next_word_end(
 7611        &mut self,
 7612        action: &DeleteToNextWordEnd,
 7613        cx: &mut ViewContext<Self>,
 7614    ) {
 7615        self.transact(cx, |this, cx| {
 7616            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7617                let line_mode = s.line_mode;
 7618                s.move_with(|map, selection| {
 7619                    if selection.is_empty() && !line_mode {
 7620                        let cursor = if action.ignore_newlines {
 7621                            movement::next_word_end(map, selection.head())
 7622                        } else {
 7623                            movement::next_word_end_or_newline(map, selection.head())
 7624                        };
 7625                        selection.set_head(cursor, SelectionGoal::None);
 7626                    }
 7627                });
 7628            });
 7629            this.insert("", cx);
 7630        });
 7631    }
 7632
 7633    pub fn delete_to_next_subword_end(
 7634        &mut self,
 7635        _: &DeleteToNextSubwordEnd,
 7636        cx: &mut ViewContext<Self>,
 7637    ) {
 7638        self.transact(cx, |this, cx| {
 7639            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7640                s.move_with(|map, selection| {
 7641                    if selection.is_empty() {
 7642                        let cursor = movement::next_subword_end(map, selection.head());
 7643                        selection.set_head(cursor, SelectionGoal::None);
 7644                    }
 7645                });
 7646            });
 7647            this.insert("", cx);
 7648        });
 7649    }
 7650
 7651    pub fn move_to_beginning_of_line(
 7652        &mut self,
 7653        action: &MoveToBeginningOfLine,
 7654        cx: &mut ViewContext<Self>,
 7655    ) {
 7656        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7657            s.move_cursors_with(|map, head, _| {
 7658                (
 7659                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7660                    SelectionGoal::None,
 7661                )
 7662            });
 7663        })
 7664    }
 7665
 7666    pub fn select_to_beginning_of_line(
 7667        &mut self,
 7668        action: &SelectToBeginningOfLine,
 7669        cx: &mut ViewContext<Self>,
 7670    ) {
 7671        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7672            s.move_heads_with(|map, head, _| {
 7673                (
 7674                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7675                    SelectionGoal::None,
 7676                )
 7677            });
 7678        });
 7679    }
 7680
 7681    pub fn delete_to_beginning_of_line(
 7682        &mut self,
 7683        _: &DeleteToBeginningOfLine,
 7684        cx: &mut ViewContext<Self>,
 7685    ) {
 7686        self.transact(cx, |this, cx| {
 7687            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7688                s.move_with(|_, selection| {
 7689                    selection.reversed = true;
 7690                });
 7691            });
 7692
 7693            this.select_to_beginning_of_line(
 7694                &SelectToBeginningOfLine {
 7695                    stop_at_soft_wraps: false,
 7696                },
 7697                cx,
 7698            );
 7699            this.backspace(&Backspace, cx);
 7700        });
 7701    }
 7702
 7703    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7704        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7705            s.move_cursors_with(|map, head, _| {
 7706                (
 7707                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7708                    SelectionGoal::None,
 7709                )
 7710            });
 7711        })
 7712    }
 7713
 7714    pub fn select_to_end_of_line(
 7715        &mut self,
 7716        action: &SelectToEndOfLine,
 7717        cx: &mut ViewContext<Self>,
 7718    ) {
 7719        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7720            s.move_heads_with(|map, head, _| {
 7721                (
 7722                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7723                    SelectionGoal::None,
 7724                )
 7725            });
 7726        })
 7727    }
 7728
 7729    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7730        self.transact(cx, |this, cx| {
 7731            this.select_to_end_of_line(
 7732                &SelectToEndOfLine {
 7733                    stop_at_soft_wraps: false,
 7734                },
 7735                cx,
 7736            );
 7737            this.delete(&Delete, cx);
 7738        });
 7739    }
 7740
 7741    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7742        self.transact(cx, |this, cx| {
 7743            this.select_to_end_of_line(
 7744                &SelectToEndOfLine {
 7745                    stop_at_soft_wraps: false,
 7746                },
 7747                cx,
 7748            );
 7749            this.cut(&Cut, cx);
 7750        });
 7751    }
 7752
 7753    pub fn move_to_start_of_paragraph(
 7754        &mut self,
 7755        _: &MoveToStartOfParagraph,
 7756        cx: &mut ViewContext<Self>,
 7757    ) {
 7758        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7759            cx.propagate();
 7760            return;
 7761        }
 7762
 7763        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7764            s.move_with(|map, selection| {
 7765                selection.collapse_to(
 7766                    movement::start_of_paragraph(map, selection.head(), 1),
 7767                    SelectionGoal::None,
 7768                )
 7769            });
 7770        })
 7771    }
 7772
 7773    pub fn move_to_end_of_paragraph(
 7774        &mut self,
 7775        _: &MoveToEndOfParagraph,
 7776        cx: &mut ViewContext<Self>,
 7777    ) {
 7778        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7779            cx.propagate();
 7780            return;
 7781        }
 7782
 7783        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7784            s.move_with(|map, selection| {
 7785                selection.collapse_to(
 7786                    movement::end_of_paragraph(map, selection.head(), 1),
 7787                    SelectionGoal::None,
 7788                )
 7789            });
 7790        })
 7791    }
 7792
 7793    pub fn select_to_start_of_paragraph(
 7794        &mut self,
 7795        _: &SelectToStartOfParagraph,
 7796        cx: &mut ViewContext<Self>,
 7797    ) {
 7798        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7799            cx.propagate();
 7800            return;
 7801        }
 7802
 7803        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7804            s.move_heads_with(|map, head, _| {
 7805                (
 7806                    movement::start_of_paragraph(map, head, 1),
 7807                    SelectionGoal::None,
 7808                )
 7809            });
 7810        })
 7811    }
 7812
 7813    pub fn select_to_end_of_paragraph(
 7814        &mut self,
 7815        _: &SelectToEndOfParagraph,
 7816        cx: &mut ViewContext<Self>,
 7817    ) {
 7818        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7819            cx.propagate();
 7820            return;
 7821        }
 7822
 7823        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7824            s.move_heads_with(|map, head, _| {
 7825                (
 7826                    movement::end_of_paragraph(map, head, 1),
 7827                    SelectionGoal::None,
 7828                )
 7829            });
 7830        })
 7831    }
 7832
 7833    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7834        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7835            cx.propagate();
 7836            return;
 7837        }
 7838
 7839        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7840            s.select_ranges(vec![0..0]);
 7841        });
 7842    }
 7843
 7844    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7845        let mut selection = self.selections.last::<Point>(cx);
 7846        selection.set_head(Point::zero(), SelectionGoal::None);
 7847
 7848        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7849            s.select(vec![selection]);
 7850        });
 7851    }
 7852
 7853    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7854        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7855            cx.propagate();
 7856            return;
 7857        }
 7858
 7859        let cursor = self.buffer.read(cx).read(cx).len();
 7860        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7861            s.select_ranges(vec![cursor..cursor])
 7862        });
 7863    }
 7864
 7865    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7866        self.nav_history = nav_history;
 7867    }
 7868
 7869    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7870        self.nav_history.as_ref()
 7871    }
 7872
 7873    fn push_to_nav_history(
 7874        &mut self,
 7875        cursor_anchor: Anchor,
 7876        new_position: Option<Point>,
 7877        cx: &mut ViewContext<Self>,
 7878    ) {
 7879        if let Some(nav_history) = self.nav_history.as_mut() {
 7880            let buffer = self.buffer.read(cx).read(cx);
 7881            let cursor_position = cursor_anchor.to_point(&buffer);
 7882            let scroll_state = self.scroll_manager.anchor();
 7883            let scroll_top_row = scroll_state.top_row(&buffer);
 7884            drop(buffer);
 7885
 7886            if let Some(new_position) = new_position {
 7887                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7888                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7889                    return;
 7890                }
 7891            }
 7892
 7893            nav_history.push(
 7894                Some(NavigationData {
 7895                    cursor_anchor,
 7896                    cursor_position,
 7897                    scroll_anchor: scroll_state,
 7898                    scroll_top_row,
 7899                }),
 7900                cx,
 7901            );
 7902        }
 7903    }
 7904
 7905    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7906        let buffer = self.buffer.read(cx).snapshot(cx);
 7907        let mut selection = self.selections.first::<usize>(cx);
 7908        selection.set_head(buffer.len(), SelectionGoal::None);
 7909        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7910            s.select(vec![selection]);
 7911        });
 7912    }
 7913
 7914    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7915        let end = self.buffer.read(cx).read(cx).len();
 7916        self.change_selections(None, cx, |s| {
 7917            s.select_ranges(vec![0..end]);
 7918        });
 7919    }
 7920
 7921    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7922        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7923        let mut selections = self.selections.all::<Point>(cx);
 7924        let max_point = display_map.buffer_snapshot.max_point();
 7925        for selection in &mut selections {
 7926            let rows = selection.spanned_rows(true, &display_map);
 7927            selection.start = Point::new(rows.start.0, 0);
 7928            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7929            selection.reversed = false;
 7930        }
 7931        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7932            s.select(selections);
 7933        });
 7934    }
 7935
 7936    pub fn split_selection_into_lines(
 7937        &mut self,
 7938        _: &SplitSelectionIntoLines,
 7939        cx: &mut ViewContext<Self>,
 7940    ) {
 7941        let mut to_unfold = Vec::new();
 7942        let mut new_selection_ranges = Vec::new();
 7943        {
 7944            let selections = self.selections.all::<Point>(cx);
 7945            let buffer = self.buffer.read(cx).read(cx);
 7946            for selection in selections {
 7947                for row in selection.start.row..selection.end.row {
 7948                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7949                    new_selection_ranges.push(cursor..cursor);
 7950                }
 7951                new_selection_ranges.push(selection.end..selection.end);
 7952                to_unfold.push(selection.start..selection.end);
 7953            }
 7954        }
 7955        self.unfold_ranges(&to_unfold, true, true, cx);
 7956        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7957            s.select_ranges(new_selection_ranges);
 7958        });
 7959    }
 7960
 7961    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7962        self.add_selection(true, cx);
 7963    }
 7964
 7965    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7966        self.add_selection(false, cx);
 7967    }
 7968
 7969    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7970        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7971        let mut selections = self.selections.all::<Point>(cx);
 7972        let text_layout_details = self.text_layout_details(cx);
 7973        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7974            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7975            let range = oldest_selection.display_range(&display_map).sorted();
 7976
 7977            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7978            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7979            let positions = start_x.min(end_x)..start_x.max(end_x);
 7980
 7981            selections.clear();
 7982            let mut stack = Vec::new();
 7983            for row in range.start.row().0..=range.end.row().0 {
 7984                if let Some(selection) = self.selections.build_columnar_selection(
 7985                    &display_map,
 7986                    DisplayRow(row),
 7987                    &positions,
 7988                    oldest_selection.reversed,
 7989                    &text_layout_details,
 7990                ) {
 7991                    stack.push(selection.id);
 7992                    selections.push(selection);
 7993                }
 7994            }
 7995
 7996            if above {
 7997                stack.reverse();
 7998            }
 7999
 8000            AddSelectionsState { above, stack }
 8001        });
 8002
 8003        let last_added_selection = *state.stack.last().unwrap();
 8004        let mut new_selections = Vec::new();
 8005        if above == state.above {
 8006            let end_row = if above {
 8007                DisplayRow(0)
 8008            } else {
 8009                display_map.max_point().row()
 8010            };
 8011
 8012            'outer: for selection in selections {
 8013                if selection.id == last_added_selection {
 8014                    let range = selection.display_range(&display_map).sorted();
 8015                    debug_assert_eq!(range.start.row(), range.end.row());
 8016                    let mut row = range.start.row();
 8017                    let positions =
 8018                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8019                            px(start)..px(end)
 8020                        } else {
 8021                            let start_x =
 8022                                display_map.x_for_display_point(range.start, &text_layout_details);
 8023                            let end_x =
 8024                                display_map.x_for_display_point(range.end, &text_layout_details);
 8025                            start_x.min(end_x)..start_x.max(end_x)
 8026                        };
 8027
 8028                    while row != end_row {
 8029                        if above {
 8030                            row.0 -= 1;
 8031                        } else {
 8032                            row.0 += 1;
 8033                        }
 8034
 8035                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8036                            &display_map,
 8037                            row,
 8038                            &positions,
 8039                            selection.reversed,
 8040                            &text_layout_details,
 8041                        ) {
 8042                            state.stack.push(new_selection.id);
 8043                            if above {
 8044                                new_selections.push(new_selection);
 8045                                new_selections.push(selection);
 8046                            } else {
 8047                                new_selections.push(selection);
 8048                                new_selections.push(new_selection);
 8049                            }
 8050
 8051                            continue 'outer;
 8052                        }
 8053                    }
 8054                }
 8055
 8056                new_selections.push(selection);
 8057            }
 8058        } else {
 8059            new_selections = selections;
 8060            new_selections.retain(|s| s.id != last_added_selection);
 8061            state.stack.pop();
 8062        }
 8063
 8064        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8065            s.select(new_selections);
 8066        });
 8067        if state.stack.len() > 1 {
 8068            self.add_selections_state = Some(state);
 8069        }
 8070    }
 8071
 8072    pub fn select_next_match_internal(
 8073        &mut self,
 8074        display_map: &DisplaySnapshot,
 8075        replace_newest: bool,
 8076        autoscroll: Option<Autoscroll>,
 8077        cx: &mut ViewContext<Self>,
 8078    ) -> Result<()> {
 8079        fn select_next_match_ranges(
 8080            this: &mut Editor,
 8081            range: Range<usize>,
 8082            replace_newest: bool,
 8083            auto_scroll: Option<Autoscroll>,
 8084            cx: &mut ViewContext<Editor>,
 8085        ) {
 8086            this.unfold_ranges(&[range.clone()], false, true, cx);
 8087            this.change_selections(auto_scroll, cx, |s| {
 8088                if replace_newest {
 8089                    s.delete(s.newest_anchor().id);
 8090                }
 8091                s.insert_range(range.clone());
 8092            });
 8093        }
 8094
 8095        let buffer = &display_map.buffer_snapshot;
 8096        let mut selections = self.selections.all::<usize>(cx);
 8097        if let Some(mut select_next_state) = self.select_next_state.take() {
 8098            let query = &select_next_state.query;
 8099            if !select_next_state.done {
 8100                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8101                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8102                let mut next_selected_range = None;
 8103
 8104                let bytes_after_last_selection =
 8105                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8106                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8107                let query_matches = query
 8108                    .stream_find_iter(bytes_after_last_selection)
 8109                    .map(|result| (last_selection.end, result))
 8110                    .chain(
 8111                        query
 8112                            .stream_find_iter(bytes_before_first_selection)
 8113                            .map(|result| (0, result)),
 8114                    );
 8115
 8116                for (start_offset, query_match) in query_matches {
 8117                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8118                    let offset_range =
 8119                        start_offset + query_match.start()..start_offset + query_match.end();
 8120                    let display_range = offset_range.start.to_display_point(display_map)
 8121                        ..offset_range.end.to_display_point(display_map);
 8122
 8123                    if !select_next_state.wordwise
 8124                        || (!movement::is_inside_word(display_map, display_range.start)
 8125                            && !movement::is_inside_word(display_map, display_range.end))
 8126                    {
 8127                        // TODO: This is n^2, because we might check all the selections
 8128                        if !selections
 8129                            .iter()
 8130                            .any(|selection| selection.range().overlaps(&offset_range))
 8131                        {
 8132                            next_selected_range = Some(offset_range);
 8133                            break;
 8134                        }
 8135                    }
 8136                }
 8137
 8138                if let Some(next_selected_range) = next_selected_range {
 8139                    select_next_match_ranges(
 8140                        self,
 8141                        next_selected_range,
 8142                        replace_newest,
 8143                        autoscroll,
 8144                        cx,
 8145                    );
 8146                } else {
 8147                    select_next_state.done = true;
 8148                }
 8149            }
 8150
 8151            self.select_next_state = Some(select_next_state);
 8152        } else {
 8153            let mut only_carets = true;
 8154            let mut same_text_selected = true;
 8155            let mut selected_text = None;
 8156
 8157            let mut selections_iter = selections.iter().peekable();
 8158            while let Some(selection) = selections_iter.next() {
 8159                if selection.start != selection.end {
 8160                    only_carets = false;
 8161                }
 8162
 8163                if same_text_selected {
 8164                    if selected_text.is_none() {
 8165                        selected_text =
 8166                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8167                    }
 8168
 8169                    if let Some(next_selection) = selections_iter.peek() {
 8170                        if next_selection.range().len() == selection.range().len() {
 8171                            let next_selected_text = buffer
 8172                                .text_for_range(next_selection.range())
 8173                                .collect::<String>();
 8174                            if Some(next_selected_text) != selected_text {
 8175                                same_text_selected = false;
 8176                                selected_text = None;
 8177                            }
 8178                        } else {
 8179                            same_text_selected = false;
 8180                            selected_text = None;
 8181                        }
 8182                    }
 8183                }
 8184            }
 8185
 8186            if only_carets {
 8187                for selection in &mut selections {
 8188                    let word_range = movement::surrounding_word(
 8189                        display_map,
 8190                        selection.start.to_display_point(display_map),
 8191                    );
 8192                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8193                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8194                    selection.goal = SelectionGoal::None;
 8195                    selection.reversed = false;
 8196                    select_next_match_ranges(
 8197                        self,
 8198                        selection.start..selection.end,
 8199                        replace_newest,
 8200                        autoscroll,
 8201                        cx,
 8202                    );
 8203                }
 8204
 8205                if selections.len() == 1 {
 8206                    let selection = selections
 8207                        .last()
 8208                        .expect("ensured that there's only one selection");
 8209                    let query = buffer
 8210                        .text_for_range(selection.start..selection.end)
 8211                        .collect::<String>();
 8212                    let is_empty = query.is_empty();
 8213                    let select_state = SelectNextState {
 8214                        query: AhoCorasick::new(&[query])?,
 8215                        wordwise: true,
 8216                        done: is_empty,
 8217                    };
 8218                    self.select_next_state = Some(select_state);
 8219                } else {
 8220                    self.select_next_state = None;
 8221                }
 8222            } else if let Some(selected_text) = selected_text {
 8223                self.select_next_state = Some(SelectNextState {
 8224                    query: AhoCorasick::new(&[selected_text])?,
 8225                    wordwise: false,
 8226                    done: false,
 8227                });
 8228                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8229            }
 8230        }
 8231        Ok(())
 8232    }
 8233
 8234    pub fn select_all_matches(
 8235        &mut self,
 8236        _action: &SelectAllMatches,
 8237        cx: &mut ViewContext<Self>,
 8238    ) -> Result<()> {
 8239        self.push_to_selection_history();
 8240        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8241
 8242        self.select_next_match_internal(&display_map, false, None, cx)?;
 8243        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8244            return Ok(());
 8245        };
 8246        if select_next_state.done {
 8247            return Ok(());
 8248        }
 8249
 8250        let mut new_selections = self.selections.all::<usize>(cx);
 8251
 8252        let buffer = &display_map.buffer_snapshot;
 8253        let query_matches = select_next_state
 8254            .query
 8255            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8256
 8257        for query_match in query_matches {
 8258            let query_match = query_match.unwrap(); // can only fail due to I/O
 8259            let offset_range = query_match.start()..query_match.end();
 8260            let display_range = offset_range.start.to_display_point(&display_map)
 8261                ..offset_range.end.to_display_point(&display_map);
 8262
 8263            if !select_next_state.wordwise
 8264                || (!movement::is_inside_word(&display_map, display_range.start)
 8265                    && !movement::is_inside_word(&display_map, display_range.end))
 8266            {
 8267                self.selections.change_with(cx, |selections| {
 8268                    new_selections.push(Selection {
 8269                        id: selections.new_selection_id(),
 8270                        start: offset_range.start,
 8271                        end: offset_range.end,
 8272                        reversed: false,
 8273                        goal: SelectionGoal::None,
 8274                    });
 8275                });
 8276            }
 8277        }
 8278
 8279        new_selections.sort_by_key(|selection| selection.start);
 8280        let mut ix = 0;
 8281        while ix + 1 < new_selections.len() {
 8282            let current_selection = &new_selections[ix];
 8283            let next_selection = &new_selections[ix + 1];
 8284            if current_selection.range().overlaps(&next_selection.range()) {
 8285                if current_selection.id < next_selection.id {
 8286                    new_selections.remove(ix + 1);
 8287                } else {
 8288                    new_selections.remove(ix);
 8289                }
 8290            } else {
 8291                ix += 1;
 8292            }
 8293        }
 8294
 8295        select_next_state.done = true;
 8296        self.unfold_ranges(
 8297            &new_selections
 8298                .iter()
 8299                .map(|selection| selection.range())
 8300                .collect::<Vec<_>>(),
 8301            false,
 8302            false,
 8303            cx,
 8304        );
 8305        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8306            selections.select(new_selections)
 8307        });
 8308
 8309        Ok(())
 8310    }
 8311
 8312    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8313        self.push_to_selection_history();
 8314        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8315        self.select_next_match_internal(
 8316            &display_map,
 8317            action.replace_newest,
 8318            Some(Autoscroll::newest()),
 8319            cx,
 8320        )?;
 8321        Ok(())
 8322    }
 8323
 8324    pub fn select_previous(
 8325        &mut self,
 8326        action: &SelectPrevious,
 8327        cx: &mut ViewContext<Self>,
 8328    ) -> Result<()> {
 8329        self.push_to_selection_history();
 8330        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8331        let buffer = &display_map.buffer_snapshot;
 8332        let mut selections = self.selections.all::<usize>(cx);
 8333        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8334            let query = &select_prev_state.query;
 8335            if !select_prev_state.done {
 8336                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8337                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8338                let mut next_selected_range = None;
 8339                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8340                let bytes_before_last_selection =
 8341                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8342                let bytes_after_first_selection =
 8343                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8344                let query_matches = query
 8345                    .stream_find_iter(bytes_before_last_selection)
 8346                    .map(|result| (last_selection.start, result))
 8347                    .chain(
 8348                        query
 8349                            .stream_find_iter(bytes_after_first_selection)
 8350                            .map(|result| (buffer.len(), result)),
 8351                    );
 8352                for (end_offset, query_match) in query_matches {
 8353                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8354                    let offset_range =
 8355                        end_offset - query_match.end()..end_offset - query_match.start();
 8356                    let display_range = offset_range.start.to_display_point(&display_map)
 8357                        ..offset_range.end.to_display_point(&display_map);
 8358
 8359                    if !select_prev_state.wordwise
 8360                        || (!movement::is_inside_word(&display_map, display_range.start)
 8361                            && !movement::is_inside_word(&display_map, display_range.end))
 8362                    {
 8363                        next_selected_range = Some(offset_range);
 8364                        break;
 8365                    }
 8366                }
 8367
 8368                if let Some(next_selected_range) = next_selected_range {
 8369                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8370                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8371                        if action.replace_newest {
 8372                            s.delete(s.newest_anchor().id);
 8373                        }
 8374                        s.insert_range(next_selected_range);
 8375                    });
 8376                } else {
 8377                    select_prev_state.done = true;
 8378                }
 8379            }
 8380
 8381            self.select_prev_state = Some(select_prev_state);
 8382        } else {
 8383            let mut only_carets = true;
 8384            let mut same_text_selected = true;
 8385            let mut selected_text = None;
 8386
 8387            let mut selections_iter = selections.iter().peekable();
 8388            while let Some(selection) = selections_iter.next() {
 8389                if selection.start != selection.end {
 8390                    only_carets = false;
 8391                }
 8392
 8393                if same_text_selected {
 8394                    if selected_text.is_none() {
 8395                        selected_text =
 8396                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8397                    }
 8398
 8399                    if let Some(next_selection) = selections_iter.peek() {
 8400                        if next_selection.range().len() == selection.range().len() {
 8401                            let next_selected_text = buffer
 8402                                .text_for_range(next_selection.range())
 8403                                .collect::<String>();
 8404                            if Some(next_selected_text) != selected_text {
 8405                                same_text_selected = false;
 8406                                selected_text = None;
 8407                            }
 8408                        } else {
 8409                            same_text_selected = false;
 8410                            selected_text = None;
 8411                        }
 8412                    }
 8413                }
 8414            }
 8415
 8416            if only_carets {
 8417                for selection in &mut selections {
 8418                    let word_range = movement::surrounding_word(
 8419                        &display_map,
 8420                        selection.start.to_display_point(&display_map),
 8421                    );
 8422                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8423                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8424                    selection.goal = SelectionGoal::None;
 8425                    selection.reversed = false;
 8426                }
 8427                if selections.len() == 1 {
 8428                    let selection = selections
 8429                        .last()
 8430                        .expect("ensured that there's only one selection");
 8431                    let query = buffer
 8432                        .text_for_range(selection.start..selection.end)
 8433                        .collect::<String>();
 8434                    let is_empty = query.is_empty();
 8435                    let select_state = SelectNextState {
 8436                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8437                        wordwise: true,
 8438                        done: is_empty,
 8439                    };
 8440                    self.select_prev_state = Some(select_state);
 8441                } else {
 8442                    self.select_prev_state = None;
 8443                }
 8444
 8445                self.unfold_ranges(
 8446                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8447                    false,
 8448                    true,
 8449                    cx,
 8450                );
 8451                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8452                    s.select(selections);
 8453                });
 8454            } else if let Some(selected_text) = selected_text {
 8455                self.select_prev_state = Some(SelectNextState {
 8456                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8457                    wordwise: false,
 8458                    done: false,
 8459                });
 8460                self.select_previous(action, cx)?;
 8461            }
 8462        }
 8463        Ok(())
 8464    }
 8465
 8466    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8467        if self.read_only(cx) {
 8468            return;
 8469        }
 8470        let text_layout_details = &self.text_layout_details(cx);
 8471        self.transact(cx, |this, cx| {
 8472            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8473            let mut edits = Vec::new();
 8474            let mut selection_edit_ranges = Vec::new();
 8475            let mut last_toggled_row = None;
 8476            let snapshot = this.buffer.read(cx).read(cx);
 8477            let empty_str: Arc<str> = Arc::default();
 8478            let mut suffixes_inserted = Vec::new();
 8479            let ignore_indent = action.ignore_indent;
 8480
 8481            fn comment_prefix_range(
 8482                snapshot: &MultiBufferSnapshot,
 8483                row: MultiBufferRow,
 8484                comment_prefix: &str,
 8485                comment_prefix_whitespace: &str,
 8486                ignore_indent: bool,
 8487            ) -> Range<Point> {
 8488                let indent_size = if ignore_indent {
 8489                    0
 8490                } else {
 8491                    snapshot.indent_size_for_line(row).len
 8492                };
 8493
 8494                let start = Point::new(row.0, indent_size);
 8495
 8496                let mut line_bytes = snapshot
 8497                    .bytes_in_range(start..snapshot.max_point())
 8498                    .flatten()
 8499                    .copied();
 8500
 8501                // If this line currently begins with the line comment prefix, then record
 8502                // the range containing the prefix.
 8503                if line_bytes
 8504                    .by_ref()
 8505                    .take(comment_prefix.len())
 8506                    .eq(comment_prefix.bytes())
 8507                {
 8508                    // Include any whitespace that matches the comment prefix.
 8509                    let matching_whitespace_len = line_bytes
 8510                        .zip(comment_prefix_whitespace.bytes())
 8511                        .take_while(|(a, b)| a == b)
 8512                        .count() as u32;
 8513                    let end = Point::new(
 8514                        start.row,
 8515                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8516                    );
 8517                    start..end
 8518                } else {
 8519                    start..start
 8520                }
 8521            }
 8522
 8523            fn comment_suffix_range(
 8524                snapshot: &MultiBufferSnapshot,
 8525                row: MultiBufferRow,
 8526                comment_suffix: &str,
 8527                comment_suffix_has_leading_space: bool,
 8528            ) -> Range<Point> {
 8529                let end = Point::new(row.0, snapshot.line_len(row));
 8530                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8531
 8532                let mut line_end_bytes = snapshot
 8533                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8534                    .flatten()
 8535                    .copied();
 8536
 8537                let leading_space_len = if suffix_start_column > 0
 8538                    && line_end_bytes.next() == Some(b' ')
 8539                    && comment_suffix_has_leading_space
 8540                {
 8541                    1
 8542                } else {
 8543                    0
 8544                };
 8545
 8546                // If this line currently begins with the line comment prefix, then record
 8547                // the range containing the prefix.
 8548                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8549                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8550                    start..end
 8551                } else {
 8552                    end..end
 8553                }
 8554            }
 8555
 8556            // TODO: Handle selections that cross excerpts
 8557            for selection in &mut selections {
 8558                let start_column = snapshot
 8559                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8560                    .len;
 8561                let language = if let Some(language) =
 8562                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8563                {
 8564                    language
 8565                } else {
 8566                    continue;
 8567                };
 8568
 8569                selection_edit_ranges.clear();
 8570
 8571                // If multiple selections contain a given row, avoid processing that
 8572                // row more than once.
 8573                let mut start_row = MultiBufferRow(selection.start.row);
 8574                if last_toggled_row == Some(start_row) {
 8575                    start_row = start_row.next_row();
 8576                }
 8577                let end_row =
 8578                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8579                        MultiBufferRow(selection.end.row - 1)
 8580                    } else {
 8581                        MultiBufferRow(selection.end.row)
 8582                    };
 8583                last_toggled_row = Some(end_row);
 8584
 8585                if start_row > end_row {
 8586                    continue;
 8587                }
 8588
 8589                // If the language has line comments, toggle those.
 8590                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8591
 8592                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8593                if ignore_indent {
 8594                    full_comment_prefixes = full_comment_prefixes
 8595                        .into_iter()
 8596                        .map(|s| Arc::from(s.trim_end()))
 8597                        .collect();
 8598                }
 8599
 8600                if !full_comment_prefixes.is_empty() {
 8601                    let first_prefix = full_comment_prefixes
 8602                        .first()
 8603                        .expect("prefixes is non-empty");
 8604                    let prefix_trimmed_lengths = full_comment_prefixes
 8605                        .iter()
 8606                        .map(|p| p.trim_end_matches(' ').len())
 8607                        .collect::<SmallVec<[usize; 4]>>();
 8608
 8609                    let mut all_selection_lines_are_comments = true;
 8610
 8611                    for row in start_row.0..=end_row.0 {
 8612                        let row = MultiBufferRow(row);
 8613                        if start_row < end_row && snapshot.is_line_blank(row) {
 8614                            continue;
 8615                        }
 8616
 8617                        let prefix_range = full_comment_prefixes
 8618                            .iter()
 8619                            .zip(prefix_trimmed_lengths.iter().copied())
 8620                            .map(|(prefix, trimmed_prefix_len)| {
 8621                                comment_prefix_range(
 8622                                    snapshot.deref(),
 8623                                    row,
 8624                                    &prefix[..trimmed_prefix_len],
 8625                                    &prefix[trimmed_prefix_len..],
 8626                                    ignore_indent,
 8627                                )
 8628                            })
 8629                            .max_by_key(|range| range.end.column - range.start.column)
 8630                            .expect("prefixes is non-empty");
 8631
 8632                        if prefix_range.is_empty() {
 8633                            all_selection_lines_are_comments = false;
 8634                        }
 8635
 8636                        selection_edit_ranges.push(prefix_range);
 8637                    }
 8638
 8639                    if all_selection_lines_are_comments {
 8640                        edits.extend(
 8641                            selection_edit_ranges
 8642                                .iter()
 8643                                .cloned()
 8644                                .map(|range| (range, empty_str.clone())),
 8645                        );
 8646                    } else {
 8647                        let min_column = selection_edit_ranges
 8648                            .iter()
 8649                            .map(|range| range.start.column)
 8650                            .min()
 8651                            .unwrap_or(0);
 8652                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8653                            let position = Point::new(range.start.row, min_column);
 8654                            (position..position, first_prefix.clone())
 8655                        }));
 8656                    }
 8657                } else if let Some((full_comment_prefix, comment_suffix)) =
 8658                    language.block_comment_delimiters()
 8659                {
 8660                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8661                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8662                    let prefix_range = comment_prefix_range(
 8663                        snapshot.deref(),
 8664                        start_row,
 8665                        comment_prefix,
 8666                        comment_prefix_whitespace,
 8667                        ignore_indent,
 8668                    );
 8669                    let suffix_range = comment_suffix_range(
 8670                        snapshot.deref(),
 8671                        end_row,
 8672                        comment_suffix.trim_start_matches(' '),
 8673                        comment_suffix.starts_with(' '),
 8674                    );
 8675
 8676                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8677                        edits.push((
 8678                            prefix_range.start..prefix_range.start,
 8679                            full_comment_prefix.clone(),
 8680                        ));
 8681                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8682                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8683                    } else {
 8684                        edits.push((prefix_range, empty_str.clone()));
 8685                        edits.push((suffix_range, empty_str.clone()));
 8686                    }
 8687                } else {
 8688                    continue;
 8689                }
 8690            }
 8691
 8692            drop(snapshot);
 8693            this.buffer.update(cx, |buffer, cx| {
 8694                buffer.edit(edits, None, cx);
 8695            });
 8696
 8697            // Adjust selections so that they end before any comment suffixes that
 8698            // were inserted.
 8699            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8700            let mut selections = this.selections.all::<Point>(cx);
 8701            let snapshot = this.buffer.read(cx).read(cx);
 8702            for selection in &mut selections {
 8703                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8704                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8705                        Ordering::Less => {
 8706                            suffixes_inserted.next();
 8707                            continue;
 8708                        }
 8709                        Ordering::Greater => break,
 8710                        Ordering::Equal => {
 8711                            if selection.end.column == snapshot.line_len(row) {
 8712                                if selection.is_empty() {
 8713                                    selection.start.column -= suffix_len as u32;
 8714                                }
 8715                                selection.end.column -= suffix_len as u32;
 8716                            }
 8717                            break;
 8718                        }
 8719                    }
 8720                }
 8721            }
 8722
 8723            drop(snapshot);
 8724            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8725
 8726            let selections = this.selections.all::<Point>(cx);
 8727            let selections_on_single_row = selections.windows(2).all(|selections| {
 8728                selections[0].start.row == selections[1].start.row
 8729                    && selections[0].end.row == selections[1].end.row
 8730                    && selections[0].start.row == selections[0].end.row
 8731            });
 8732            let selections_selecting = selections
 8733                .iter()
 8734                .any(|selection| selection.start != selection.end);
 8735            let advance_downwards = action.advance_downwards
 8736                && selections_on_single_row
 8737                && !selections_selecting
 8738                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8739
 8740            if advance_downwards {
 8741                let snapshot = this.buffer.read(cx).snapshot(cx);
 8742
 8743                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8744                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8745                        let mut point = display_point.to_point(display_snapshot);
 8746                        point.row += 1;
 8747                        point = snapshot.clip_point(point, Bias::Left);
 8748                        let display_point = point.to_display_point(display_snapshot);
 8749                        let goal = SelectionGoal::HorizontalPosition(
 8750                            display_snapshot
 8751                                .x_for_display_point(display_point, text_layout_details)
 8752                                .into(),
 8753                        );
 8754                        (display_point, goal)
 8755                    })
 8756                });
 8757            }
 8758        });
 8759    }
 8760
 8761    pub fn select_enclosing_symbol(
 8762        &mut self,
 8763        _: &SelectEnclosingSymbol,
 8764        cx: &mut ViewContext<Self>,
 8765    ) {
 8766        let buffer = self.buffer.read(cx).snapshot(cx);
 8767        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8768
 8769        fn update_selection(
 8770            selection: &Selection<usize>,
 8771            buffer_snap: &MultiBufferSnapshot,
 8772        ) -> Option<Selection<usize>> {
 8773            let cursor = selection.head();
 8774            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8775            for symbol in symbols.iter().rev() {
 8776                let start = symbol.range.start.to_offset(buffer_snap);
 8777                let end = symbol.range.end.to_offset(buffer_snap);
 8778                let new_range = start..end;
 8779                if start < selection.start || end > selection.end {
 8780                    return Some(Selection {
 8781                        id: selection.id,
 8782                        start: new_range.start,
 8783                        end: new_range.end,
 8784                        goal: SelectionGoal::None,
 8785                        reversed: selection.reversed,
 8786                    });
 8787                }
 8788            }
 8789            None
 8790        }
 8791
 8792        let mut selected_larger_symbol = false;
 8793        let new_selections = old_selections
 8794            .iter()
 8795            .map(|selection| match update_selection(selection, &buffer) {
 8796                Some(new_selection) => {
 8797                    if new_selection.range() != selection.range() {
 8798                        selected_larger_symbol = true;
 8799                    }
 8800                    new_selection
 8801                }
 8802                None => selection.clone(),
 8803            })
 8804            .collect::<Vec<_>>();
 8805
 8806        if selected_larger_symbol {
 8807            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8808                s.select(new_selections);
 8809            });
 8810        }
 8811    }
 8812
 8813    pub fn select_larger_syntax_node(
 8814        &mut self,
 8815        _: &SelectLargerSyntaxNode,
 8816        cx: &mut ViewContext<Self>,
 8817    ) {
 8818        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8819        let buffer = self.buffer.read(cx).snapshot(cx);
 8820        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8821
 8822        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8823        let mut selected_larger_node = false;
 8824        let new_selections = old_selections
 8825            .iter()
 8826            .map(|selection| {
 8827                let old_range = selection.start..selection.end;
 8828                let mut new_range = old_range.clone();
 8829                let mut new_node = None;
 8830                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8831                {
 8832                    new_node = Some(node);
 8833                    new_range = containing_range;
 8834                    if !display_map.intersects_fold(new_range.start)
 8835                        && !display_map.intersects_fold(new_range.end)
 8836                    {
 8837                        break;
 8838                    }
 8839                }
 8840
 8841                if let Some(node) = new_node {
 8842                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8843                    // nodes. Parent and grandparent are also logged because this operation will not
 8844                    // visit nodes that have the same range as their parent.
 8845                    log::info!("Node: {node:?}");
 8846                    let parent = node.parent();
 8847                    log::info!("Parent: {parent:?}");
 8848                    let grandparent = parent.and_then(|x| x.parent());
 8849                    log::info!("Grandparent: {grandparent:?}");
 8850                }
 8851
 8852                selected_larger_node |= new_range != old_range;
 8853                Selection {
 8854                    id: selection.id,
 8855                    start: new_range.start,
 8856                    end: new_range.end,
 8857                    goal: SelectionGoal::None,
 8858                    reversed: selection.reversed,
 8859                }
 8860            })
 8861            .collect::<Vec<_>>();
 8862
 8863        if selected_larger_node {
 8864            stack.push(old_selections);
 8865            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8866                s.select(new_selections);
 8867            });
 8868        }
 8869        self.select_larger_syntax_node_stack = stack;
 8870    }
 8871
 8872    pub fn select_smaller_syntax_node(
 8873        &mut self,
 8874        _: &SelectSmallerSyntaxNode,
 8875        cx: &mut ViewContext<Self>,
 8876    ) {
 8877        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8878        if let Some(selections) = stack.pop() {
 8879            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8880                s.select(selections.to_vec());
 8881            });
 8882        }
 8883        self.select_larger_syntax_node_stack = stack;
 8884    }
 8885
 8886    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8887        if !EditorSettings::get_global(cx).gutter.runnables {
 8888            self.clear_tasks();
 8889            return Task::ready(());
 8890        }
 8891        let project = self.project.as_ref().map(Model::downgrade);
 8892        cx.spawn(|this, mut cx| async move {
 8893            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8894            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8895                return;
 8896            };
 8897            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8898                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8899            }) else {
 8900                return;
 8901            };
 8902
 8903            let hide_runnables = project
 8904                .update(&mut cx, |project, cx| {
 8905                    // Do not display any test indicators in non-dev server remote projects.
 8906                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8907                })
 8908                .unwrap_or(true);
 8909            if hide_runnables {
 8910                return;
 8911            }
 8912            let new_rows =
 8913                cx.background_executor()
 8914                    .spawn({
 8915                        let snapshot = display_snapshot.clone();
 8916                        async move {
 8917                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8918                        }
 8919                    })
 8920                    .await;
 8921            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8922
 8923            this.update(&mut cx, |this, _| {
 8924                this.clear_tasks();
 8925                for (key, value) in rows {
 8926                    this.insert_tasks(key, value);
 8927                }
 8928            })
 8929            .ok();
 8930        })
 8931    }
 8932    fn fetch_runnable_ranges(
 8933        snapshot: &DisplaySnapshot,
 8934        range: Range<Anchor>,
 8935    ) -> Vec<language::RunnableRange> {
 8936        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8937    }
 8938
 8939    fn runnable_rows(
 8940        project: Model<Project>,
 8941        snapshot: DisplaySnapshot,
 8942        runnable_ranges: Vec<RunnableRange>,
 8943        mut cx: AsyncWindowContext,
 8944    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8945        runnable_ranges
 8946            .into_iter()
 8947            .filter_map(|mut runnable| {
 8948                let tasks = cx
 8949                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8950                    .ok()?;
 8951                if tasks.is_empty() {
 8952                    return None;
 8953                }
 8954
 8955                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8956
 8957                let row = snapshot
 8958                    .buffer_snapshot
 8959                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8960                    .1
 8961                    .start
 8962                    .row;
 8963
 8964                let context_range =
 8965                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8966                Some((
 8967                    (runnable.buffer_id, row),
 8968                    RunnableTasks {
 8969                        templates: tasks,
 8970                        offset: MultiBufferOffset(runnable.run_range.start),
 8971                        context_range,
 8972                        column: point.column,
 8973                        extra_variables: runnable.extra_captures,
 8974                    },
 8975                ))
 8976            })
 8977            .collect()
 8978    }
 8979
 8980    fn templates_with_tags(
 8981        project: &Model<Project>,
 8982        runnable: &mut Runnable,
 8983        cx: &WindowContext,
 8984    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8985        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8986            let (worktree_id, file) = project
 8987                .buffer_for_id(runnable.buffer, cx)
 8988                .and_then(|buffer| buffer.read(cx).file())
 8989                .map(|file| (file.worktree_id(cx), file.clone()))
 8990                .unzip();
 8991
 8992            (
 8993                project.task_store().read(cx).task_inventory().cloned(),
 8994                worktree_id,
 8995                file,
 8996            )
 8997        });
 8998
 8999        let tags = mem::take(&mut runnable.tags);
 9000        let mut tags: Vec<_> = tags
 9001            .into_iter()
 9002            .flat_map(|tag| {
 9003                let tag = tag.0.clone();
 9004                inventory
 9005                    .as_ref()
 9006                    .into_iter()
 9007                    .flat_map(|inventory| {
 9008                        inventory.read(cx).list_tasks(
 9009                            file.clone(),
 9010                            Some(runnable.language.clone()),
 9011                            worktree_id,
 9012                            cx,
 9013                        )
 9014                    })
 9015                    .filter(move |(_, template)| {
 9016                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9017                    })
 9018            })
 9019            .sorted_by_key(|(kind, _)| kind.to_owned())
 9020            .collect();
 9021        if let Some((leading_tag_source, _)) = tags.first() {
 9022            // Strongest source wins; if we have worktree tag binding, prefer that to
 9023            // global and language bindings;
 9024            // if we have a global binding, prefer that to language binding.
 9025            let first_mismatch = tags
 9026                .iter()
 9027                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9028            if let Some(index) = first_mismatch {
 9029                tags.truncate(index);
 9030            }
 9031        }
 9032
 9033        tags
 9034    }
 9035
 9036    pub fn move_to_enclosing_bracket(
 9037        &mut self,
 9038        _: &MoveToEnclosingBracket,
 9039        cx: &mut ViewContext<Self>,
 9040    ) {
 9041        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9042            s.move_offsets_with(|snapshot, selection| {
 9043                let Some(enclosing_bracket_ranges) =
 9044                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9045                else {
 9046                    return;
 9047                };
 9048
 9049                let mut best_length = usize::MAX;
 9050                let mut best_inside = false;
 9051                let mut best_in_bracket_range = false;
 9052                let mut best_destination = None;
 9053                for (open, close) in enclosing_bracket_ranges {
 9054                    let close = close.to_inclusive();
 9055                    let length = close.end() - open.start;
 9056                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9057                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9058                        || close.contains(&selection.head());
 9059
 9060                    // If best is next to a bracket and current isn't, skip
 9061                    if !in_bracket_range && best_in_bracket_range {
 9062                        continue;
 9063                    }
 9064
 9065                    // Prefer smaller lengths unless best is inside and current isn't
 9066                    if length > best_length && (best_inside || !inside) {
 9067                        continue;
 9068                    }
 9069
 9070                    best_length = length;
 9071                    best_inside = inside;
 9072                    best_in_bracket_range = in_bracket_range;
 9073                    best_destination = Some(
 9074                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9075                            if inside {
 9076                                open.end
 9077                            } else {
 9078                                open.start
 9079                            }
 9080                        } else if inside {
 9081                            *close.start()
 9082                        } else {
 9083                            *close.end()
 9084                        },
 9085                    );
 9086                }
 9087
 9088                if let Some(destination) = best_destination {
 9089                    selection.collapse_to(destination, SelectionGoal::None);
 9090                }
 9091            })
 9092        });
 9093    }
 9094
 9095    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9096        self.end_selection(cx);
 9097        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9098        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9099            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9100            self.select_next_state = entry.select_next_state;
 9101            self.select_prev_state = entry.select_prev_state;
 9102            self.add_selections_state = entry.add_selections_state;
 9103            self.request_autoscroll(Autoscroll::newest(), cx);
 9104        }
 9105        self.selection_history.mode = SelectionHistoryMode::Normal;
 9106    }
 9107
 9108    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9109        self.end_selection(cx);
 9110        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9111        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9112            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9113            self.select_next_state = entry.select_next_state;
 9114            self.select_prev_state = entry.select_prev_state;
 9115            self.add_selections_state = entry.add_selections_state;
 9116            self.request_autoscroll(Autoscroll::newest(), cx);
 9117        }
 9118        self.selection_history.mode = SelectionHistoryMode::Normal;
 9119    }
 9120
 9121    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9122        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9123    }
 9124
 9125    pub fn expand_excerpts_down(
 9126        &mut self,
 9127        action: &ExpandExcerptsDown,
 9128        cx: &mut ViewContext<Self>,
 9129    ) {
 9130        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9131    }
 9132
 9133    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9134        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9135    }
 9136
 9137    pub fn expand_excerpts_for_direction(
 9138        &mut self,
 9139        lines: u32,
 9140        direction: ExpandExcerptDirection,
 9141        cx: &mut ViewContext<Self>,
 9142    ) {
 9143        let selections = self.selections.disjoint_anchors();
 9144
 9145        let lines = if lines == 0 {
 9146            EditorSettings::get_global(cx).expand_excerpt_lines
 9147        } else {
 9148            lines
 9149        };
 9150
 9151        self.buffer.update(cx, |buffer, cx| {
 9152            let snapshot = buffer.snapshot(cx);
 9153            let mut excerpt_ids = selections
 9154                .iter()
 9155                .flat_map(|selection| {
 9156                    snapshot
 9157                        .excerpts_for_range(selection.range())
 9158                        .map(|excerpt| excerpt.id())
 9159                })
 9160                .collect::<Vec<_>>();
 9161            excerpt_ids.sort();
 9162            excerpt_ids.dedup();
 9163            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9164        })
 9165    }
 9166
 9167    pub fn expand_excerpt(
 9168        &mut self,
 9169        excerpt: ExcerptId,
 9170        direction: ExpandExcerptDirection,
 9171        cx: &mut ViewContext<Self>,
 9172    ) {
 9173        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9174        self.buffer.update(cx, |buffer, cx| {
 9175            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9176        })
 9177    }
 9178
 9179    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9180        self.go_to_diagnostic_impl(Direction::Next, cx)
 9181    }
 9182
 9183    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9184        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9185    }
 9186
 9187    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9188        let buffer = self.buffer.read(cx).snapshot(cx);
 9189        let selection = self.selections.newest::<usize>(cx);
 9190
 9191        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9192        if direction == Direction::Next {
 9193            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9194                self.activate_diagnostics(popover.group_id(), cx);
 9195                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9196                    let primary_range_start = active_diagnostics.primary_range.start;
 9197                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9198                        let mut new_selection = s.newest_anchor().clone();
 9199                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9200                        s.select_anchors(vec![new_selection.clone()]);
 9201                    });
 9202                }
 9203                return;
 9204            }
 9205        }
 9206
 9207        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9208            active_diagnostics
 9209                .primary_range
 9210                .to_offset(&buffer)
 9211                .to_inclusive()
 9212        });
 9213        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9214            if active_primary_range.contains(&selection.head()) {
 9215                *active_primary_range.start()
 9216            } else {
 9217                selection.head()
 9218            }
 9219        } else {
 9220            selection.head()
 9221        };
 9222        let snapshot = self.snapshot(cx);
 9223        loop {
 9224            let diagnostics = if direction == Direction::Prev {
 9225                buffer
 9226                    .diagnostics_in_range(0..search_start, true)
 9227                    .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
 9228                        diagnostic,
 9229                        range: range.to_offset(&buffer),
 9230                    })
 9231                    .collect::<Vec<_>>()
 9232            } else {
 9233                buffer
 9234                    .diagnostics_in_range(search_start..buffer.len(), false)
 9235                    .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
 9236                        diagnostic,
 9237                        range: range.to_offset(&buffer),
 9238                    })
 9239                    .collect::<Vec<_>>()
 9240            }
 9241            .into_iter()
 9242            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9243            let group = diagnostics
 9244                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9245                // be sorted in a stable way
 9246                // skip until we are at current active diagnostic, if it exists
 9247                .skip_while(|entry| {
 9248                    (match direction {
 9249                        Direction::Prev => entry.range.start >= search_start,
 9250                        Direction::Next => entry.range.start <= search_start,
 9251                    }) && self
 9252                        .active_diagnostics
 9253                        .as_ref()
 9254                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9255                })
 9256                .find_map(|entry| {
 9257                    if entry.diagnostic.is_primary
 9258                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9259                        && !entry.range.is_empty()
 9260                        // if we match with the active diagnostic, skip it
 9261                        && Some(entry.diagnostic.group_id)
 9262                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9263                    {
 9264                        Some((entry.range, entry.diagnostic.group_id))
 9265                    } else {
 9266                        None
 9267                    }
 9268                });
 9269
 9270            if let Some((primary_range, group_id)) = group {
 9271                self.activate_diagnostics(group_id, cx);
 9272                if self.active_diagnostics.is_some() {
 9273                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9274                        s.select(vec![Selection {
 9275                            id: selection.id,
 9276                            start: primary_range.start,
 9277                            end: primary_range.start,
 9278                            reversed: false,
 9279                            goal: SelectionGoal::None,
 9280                        }]);
 9281                    });
 9282                }
 9283                break;
 9284            } else {
 9285                // Cycle around to the start of the buffer, potentially moving back to the start of
 9286                // the currently active diagnostic.
 9287                active_primary_range.take();
 9288                if direction == Direction::Prev {
 9289                    if search_start == buffer.len() {
 9290                        break;
 9291                    } else {
 9292                        search_start = buffer.len();
 9293                    }
 9294                } else if search_start == 0 {
 9295                    break;
 9296                } else {
 9297                    search_start = 0;
 9298                }
 9299            }
 9300        }
 9301    }
 9302
 9303    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9304        let snapshot = self.snapshot(cx);
 9305        let selection = self.selections.newest::<Point>(cx);
 9306        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9307    }
 9308
 9309    fn go_to_hunk_after_position(
 9310        &mut self,
 9311        snapshot: &EditorSnapshot,
 9312        position: Point,
 9313        cx: &mut ViewContext<Editor>,
 9314    ) -> Option<MultiBufferDiffHunk> {
 9315        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9316            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9317                snapshot,
 9318                position,
 9319                ix > 0,
 9320                snapshot.diff_map.diff_hunks_in_range(
 9321                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9322                    &snapshot.buffer_snapshot,
 9323                ),
 9324                cx,
 9325            ) {
 9326                return Some(hunk);
 9327            }
 9328        }
 9329        None
 9330    }
 9331
 9332    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9333        let snapshot = self.snapshot(cx);
 9334        let selection = self.selections.newest::<Point>(cx);
 9335        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9336    }
 9337
 9338    fn go_to_hunk_before_position(
 9339        &mut self,
 9340        snapshot: &EditorSnapshot,
 9341        position: Point,
 9342        cx: &mut ViewContext<Editor>,
 9343    ) -> Option<MultiBufferDiffHunk> {
 9344        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9345            .into_iter()
 9346            .enumerate()
 9347        {
 9348            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9349                snapshot,
 9350                position,
 9351                ix > 0,
 9352                snapshot
 9353                    .diff_map
 9354                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9355                cx,
 9356            ) {
 9357                return Some(hunk);
 9358            }
 9359        }
 9360        None
 9361    }
 9362
 9363    fn go_to_next_hunk_in_direction(
 9364        &mut self,
 9365        snapshot: &DisplaySnapshot,
 9366        initial_point: Point,
 9367        is_wrapped: bool,
 9368        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9369        cx: &mut ViewContext<Editor>,
 9370    ) -> Option<MultiBufferDiffHunk> {
 9371        let display_point = initial_point.to_display_point(snapshot);
 9372        let mut hunks = hunks
 9373            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9374            .filter(|(display_hunk, _)| {
 9375                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9376            })
 9377            .dedup();
 9378
 9379        if let Some((display_hunk, hunk)) = hunks.next() {
 9380            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9381                let row = display_hunk.start_display_row();
 9382                let point = DisplayPoint::new(row, 0);
 9383                s.select_display_ranges([point..point]);
 9384            });
 9385
 9386            Some(hunk)
 9387        } else {
 9388            None
 9389        }
 9390    }
 9391
 9392    pub fn go_to_definition(
 9393        &mut self,
 9394        _: &GoToDefinition,
 9395        cx: &mut ViewContext<Self>,
 9396    ) -> Task<Result<Navigated>> {
 9397        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9398        cx.spawn(|editor, mut cx| async move {
 9399            if definition.await? == Navigated::Yes {
 9400                return Ok(Navigated::Yes);
 9401            }
 9402            match editor.update(&mut cx, |editor, cx| {
 9403                editor.find_all_references(&FindAllReferences, cx)
 9404            })? {
 9405                Some(references) => references.await,
 9406                None => Ok(Navigated::No),
 9407            }
 9408        })
 9409    }
 9410
 9411    pub fn go_to_declaration(
 9412        &mut self,
 9413        _: &GoToDeclaration,
 9414        cx: &mut ViewContext<Self>,
 9415    ) -> Task<Result<Navigated>> {
 9416        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9417    }
 9418
 9419    pub fn go_to_declaration_split(
 9420        &mut self,
 9421        _: &GoToDeclaration,
 9422        cx: &mut ViewContext<Self>,
 9423    ) -> Task<Result<Navigated>> {
 9424        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9425    }
 9426
 9427    pub fn go_to_implementation(
 9428        &mut self,
 9429        _: &GoToImplementation,
 9430        cx: &mut ViewContext<Self>,
 9431    ) -> Task<Result<Navigated>> {
 9432        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9433    }
 9434
 9435    pub fn go_to_implementation_split(
 9436        &mut self,
 9437        _: &GoToImplementationSplit,
 9438        cx: &mut ViewContext<Self>,
 9439    ) -> Task<Result<Navigated>> {
 9440        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9441    }
 9442
 9443    pub fn go_to_type_definition(
 9444        &mut self,
 9445        _: &GoToTypeDefinition,
 9446        cx: &mut ViewContext<Self>,
 9447    ) -> Task<Result<Navigated>> {
 9448        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9449    }
 9450
 9451    pub fn go_to_definition_split(
 9452        &mut self,
 9453        _: &GoToDefinitionSplit,
 9454        cx: &mut ViewContext<Self>,
 9455    ) -> Task<Result<Navigated>> {
 9456        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9457    }
 9458
 9459    pub fn go_to_type_definition_split(
 9460        &mut self,
 9461        _: &GoToTypeDefinitionSplit,
 9462        cx: &mut ViewContext<Self>,
 9463    ) -> Task<Result<Navigated>> {
 9464        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9465    }
 9466
 9467    fn go_to_definition_of_kind(
 9468        &mut self,
 9469        kind: GotoDefinitionKind,
 9470        split: bool,
 9471        cx: &mut ViewContext<Self>,
 9472    ) -> Task<Result<Navigated>> {
 9473        let Some(provider) = self.semantics_provider.clone() else {
 9474            return Task::ready(Ok(Navigated::No));
 9475        };
 9476        let head = self.selections.newest::<usize>(cx).head();
 9477        let buffer = self.buffer.read(cx);
 9478        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9479            text_anchor
 9480        } else {
 9481            return Task::ready(Ok(Navigated::No));
 9482        };
 9483
 9484        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9485            return Task::ready(Ok(Navigated::No));
 9486        };
 9487
 9488        cx.spawn(|editor, mut cx| async move {
 9489            let definitions = definitions.await?;
 9490            let navigated = editor
 9491                .update(&mut cx, |editor, cx| {
 9492                    editor.navigate_to_hover_links(
 9493                        Some(kind),
 9494                        definitions
 9495                            .into_iter()
 9496                            .filter(|location| {
 9497                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9498                            })
 9499                            .map(HoverLink::Text)
 9500                            .collect::<Vec<_>>(),
 9501                        split,
 9502                        cx,
 9503                    )
 9504                })?
 9505                .await?;
 9506            anyhow::Ok(navigated)
 9507        })
 9508    }
 9509
 9510    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9511        let selection = self.selections.newest_anchor();
 9512        let head = selection.head();
 9513        let tail = selection.tail();
 9514
 9515        let Some((buffer, start_position)) =
 9516            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9517        else {
 9518            return;
 9519        };
 9520
 9521        let end_position = if head != tail {
 9522            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9523                return;
 9524            };
 9525            Some(pos)
 9526        } else {
 9527            None
 9528        };
 9529
 9530        let url_finder = cx.spawn(|editor, mut cx| async move {
 9531            let url = if let Some(end_pos) = end_position {
 9532                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9533            } else {
 9534                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9535            };
 9536
 9537            if let Some(url) = url {
 9538                editor.update(&mut cx, |_, cx| {
 9539                    cx.open_url(&url);
 9540                })
 9541            } else {
 9542                Ok(())
 9543            }
 9544        });
 9545
 9546        url_finder.detach();
 9547    }
 9548
 9549    pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
 9550        let Some(workspace) = self.workspace() else {
 9551            return;
 9552        };
 9553
 9554        let position = self.selections.newest_anchor().head();
 9555
 9556        let Some((buffer, buffer_position)) =
 9557            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9558        else {
 9559            return;
 9560        };
 9561
 9562        let project = self.project.clone();
 9563
 9564        cx.spawn(|_, mut cx| async move {
 9565            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9566
 9567            if let Some((_, path)) = result {
 9568                workspace
 9569                    .update(&mut cx, |workspace, cx| {
 9570                        workspace.open_resolved_path(path, cx)
 9571                    })?
 9572                    .await?;
 9573            }
 9574            anyhow::Ok(())
 9575        })
 9576        .detach();
 9577    }
 9578
 9579    pub(crate) fn navigate_to_hover_links(
 9580        &mut self,
 9581        kind: Option<GotoDefinitionKind>,
 9582        mut definitions: Vec<HoverLink>,
 9583        split: bool,
 9584        cx: &mut ViewContext<Editor>,
 9585    ) -> Task<Result<Navigated>> {
 9586        // If there is one definition, just open it directly
 9587        if definitions.len() == 1 {
 9588            let definition = definitions.pop().unwrap();
 9589
 9590            enum TargetTaskResult {
 9591                Location(Option<Location>),
 9592                AlreadyNavigated,
 9593            }
 9594
 9595            let target_task = match definition {
 9596                HoverLink::Text(link) => {
 9597                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9598                }
 9599                HoverLink::InlayHint(lsp_location, server_id) => {
 9600                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9601                    cx.background_executor().spawn(async move {
 9602                        let location = computation.await?;
 9603                        Ok(TargetTaskResult::Location(location))
 9604                    })
 9605                }
 9606                HoverLink::Url(url) => {
 9607                    cx.open_url(&url);
 9608                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9609                }
 9610                HoverLink::File(path) => {
 9611                    if let Some(workspace) = self.workspace() {
 9612                        cx.spawn(|_, mut cx| async move {
 9613                            workspace
 9614                                .update(&mut cx, |workspace, cx| {
 9615                                    workspace.open_resolved_path(path, cx)
 9616                                })?
 9617                                .await
 9618                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9619                        })
 9620                    } else {
 9621                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9622                    }
 9623                }
 9624            };
 9625            cx.spawn(|editor, mut cx| async move {
 9626                let target = match target_task.await.context("target resolution task")? {
 9627                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9628                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9629                    TargetTaskResult::Location(Some(target)) => target,
 9630                };
 9631
 9632                editor.update(&mut cx, |editor, cx| {
 9633                    let Some(workspace) = editor.workspace() else {
 9634                        return Navigated::No;
 9635                    };
 9636                    let pane = workspace.read(cx).active_pane().clone();
 9637
 9638                    let range = target.range.to_offset(target.buffer.read(cx));
 9639                    let range = editor.range_for_match(&range);
 9640
 9641                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9642                        let buffer = target.buffer.read(cx);
 9643                        let range = check_multiline_range(buffer, range);
 9644                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9645                            s.select_ranges([range]);
 9646                        });
 9647                    } else {
 9648                        cx.window_context().defer(move |cx| {
 9649                            let target_editor: View<Self> =
 9650                                workspace.update(cx, |workspace, cx| {
 9651                                    let pane = if split {
 9652                                        workspace.adjacent_pane(cx)
 9653                                    } else {
 9654                                        workspace.active_pane().clone()
 9655                                    };
 9656
 9657                                    workspace.open_project_item(
 9658                                        pane,
 9659                                        target.buffer.clone(),
 9660                                        true,
 9661                                        true,
 9662                                        cx,
 9663                                    )
 9664                                });
 9665                            target_editor.update(cx, |target_editor, cx| {
 9666                                // When selecting a definition in a different buffer, disable the nav history
 9667                                // to avoid creating a history entry at the previous cursor location.
 9668                                pane.update(cx, |pane, _| pane.disable_history());
 9669                                let buffer = target.buffer.read(cx);
 9670                                let range = check_multiline_range(buffer, range);
 9671                                target_editor.change_selections(
 9672                                    Some(Autoscroll::focused()),
 9673                                    cx,
 9674                                    |s| {
 9675                                        s.select_ranges([range]);
 9676                                    },
 9677                                );
 9678                                pane.update(cx, |pane, _| pane.enable_history());
 9679                            });
 9680                        });
 9681                    }
 9682                    Navigated::Yes
 9683                })
 9684            })
 9685        } else if !definitions.is_empty() {
 9686            cx.spawn(|editor, mut cx| async move {
 9687                let (title, location_tasks, workspace) = editor
 9688                    .update(&mut cx, |editor, cx| {
 9689                        let tab_kind = match kind {
 9690                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9691                            _ => "Definitions",
 9692                        };
 9693                        let title = definitions
 9694                            .iter()
 9695                            .find_map(|definition| match definition {
 9696                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9697                                    let buffer = origin.buffer.read(cx);
 9698                                    format!(
 9699                                        "{} for {}",
 9700                                        tab_kind,
 9701                                        buffer
 9702                                            .text_for_range(origin.range.clone())
 9703                                            .collect::<String>()
 9704                                    )
 9705                                }),
 9706                                HoverLink::InlayHint(_, _) => None,
 9707                                HoverLink::Url(_) => None,
 9708                                HoverLink::File(_) => None,
 9709                            })
 9710                            .unwrap_or(tab_kind.to_string());
 9711                        let location_tasks = definitions
 9712                            .into_iter()
 9713                            .map(|definition| match definition {
 9714                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9715                                HoverLink::InlayHint(lsp_location, server_id) => {
 9716                                    editor.compute_target_location(lsp_location, server_id, cx)
 9717                                }
 9718                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9719                                HoverLink::File(_) => Task::ready(Ok(None)),
 9720                            })
 9721                            .collect::<Vec<_>>();
 9722                        (title, location_tasks, editor.workspace().clone())
 9723                    })
 9724                    .context("location tasks preparation")?;
 9725
 9726                let locations = future::join_all(location_tasks)
 9727                    .await
 9728                    .into_iter()
 9729                    .filter_map(|location| location.transpose())
 9730                    .collect::<Result<_>>()
 9731                    .context("location tasks")?;
 9732
 9733                let Some(workspace) = workspace else {
 9734                    return Ok(Navigated::No);
 9735                };
 9736                let opened = workspace
 9737                    .update(&mut cx, |workspace, cx| {
 9738                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9739                    })
 9740                    .ok();
 9741
 9742                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9743            })
 9744        } else {
 9745            Task::ready(Ok(Navigated::No))
 9746        }
 9747    }
 9748
 9749    fn compute_target_location(
 9750        &self,
 9751        lsp_location: lsp::Location,
 9752        server_id: LanguageServerId,
 9753        cx: &mut ViewContext<Self>,
 9754    ) -> Task<anyhow::Result<Option<Location>>> {
 9755        let Some(project) = self.project.clone() else {
 9756            return Task::ready(Ok(None));
 9757        };
 9758
 9759        cx.spawn(move |editor, mut cx| async move {
 9760            let location_task = editor.update(&mut cx, |_, cx| {
 9761                project.update(cx, |project, cx| {
 9762                    let language_server_name = project
 9763                        .language_server_statuses(cx)
 9764                        .find(|(id, _)| server_id == *id)
 9765                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9766                    language_server_name.map(|language_server_name| {
 9767                        project.open_local_buffer_via_lsp(
 9768                            lsp_location.uri.clone(),
 9769                            server_id,
 9770                            language_server_name,
 9771                            cx,
 9772                        )
 9773                    })
 9774                })
 9775            })?;
 9776            let location = match location_task {
 9777                Some(task) => Some({
 9778                    let target_buffer_handle = task.await.context("open local buffer")?;
 9779                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9780                        let target_start = target_buffer
 9781                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9782                        let target_end = target_buffer
 9783                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9784                        target_buffer.anchor_after(target_start)
 9785                            ..target_buffer.anchor_before(target_end)
 9786                    })?;
 9787                    Location {
 9788                        buffer: target_buffer_handle,
 9789                        range,
 9790                    }
 9791                }),
 9792                None => None,
 9793            };
 9794            Ok(location)
 9795        })
 9796    }
 9797
 9798    pub fn find_all_references(
 9799        &mut self,
 9800        _: &FindAllReferences,
 9801        cx: &mut ViewContext<Self>,
 9802    ) -> Option<Task<Result<Navigated>>> {
 9803        let selection = self.selections.newest::<usize>(cx);
 9804        let multi_buffer = self.buffer.read(cx);
 9805        let head = selection.head();
 9806
 9807        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9808        let head_anchor = multi_buffer_snapshot.anchor_at(
 9809            head,
 9810            if head < selection.tail() {
 9811                Bias::Right
 9812            } else {
 9813                Bias::Left
 9814            },
 9815        );
 9816
 9817        match self
 9818            .find_all_references_task_sources
 9819            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9820        {
 9821            Ok(_) => {
 9822                log::info!(
 9823                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9824                );
 9825                return None;
 9826            }
 9827            Err(i) => {
 9828                self.find_all_references_task_sources.insert(i, head_anchor);
 9829            }
 9830        }
 9831
 9832        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9833        let workspace = self.workspace()?;
 9834        let project = workspace.read(cx).project().clone();
 9835        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9836        Some(cx.spawn(|editor, mut cx| async move {
 9837            let _cleanup = defer({
 9838                let mut cx = cx.clone();
 9839                move || {
 9840                    let _ = editor.update(&mut cx, |editor, _| {
 9841                        if let Ok(i) =
 9842                            editor
 9843                                .find_all_references_task_sources
 9844                                .binary_search_by(|anchor| {
 9845                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9846                                })
 9847                        {
 9848                            editor.find_all_references_task_sources.remove(i);
 9849                        }
 9850                    });
 9851                }
 9852            });
 9853
 9854            let locations = references.await?;
 9855            if locations.is_empty() {
 9856                return anyhow::Ok(Navigated::No);
 9857            }
 9858
 9859            workspace.update(&mut cx, |workspace, cx| {
 9860                let title = locations
 9861                    .first()
 9862                    .as_ref()
 9863                    .map(|location| {
 9864                        let buffer = location.buffer.read(cx);
 9865                        format!(
 9866                            "References to `{}`",
 9867                            buffer
 9868                                .text_for_range(location.range.clone())
 9869                                .collect::<String>()
 9870                        )
 9871                    })
 9872                    .unwrap();
 9873                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9874                Navigated::Yes
 9875            })
 9876        }))
 9877    }
 9878
 9879    /// Opens a multibuffer with the given project locations in it
 9880    pub fn open_locations_in_multibuffer(
 9881        workspace: &mut Workspace,
 9882        mut locations: Vec<Location>,
 9883        title: String,
 9884        split: bool,
 9885        cx: &mut ViewContext<Workspace>,
 9886    ) {
 9887        // If there are multiple definitions, open them in a multibuffer
 9888        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9889        let mut locations = locations.into_iter().peekable();
 9890        let mut ranges_to_highlight = Vec::new();
 9891        let capability = workspace.project().read(cx).capability();
 9892
 9893        let excerpt_buffer = cx.new_model(|cx| {
 9894            let mut multibuffer = MultiBuffer::new(capability);
 9895            while let Some(location) = locations.next() {
 9896                let buffer = location.buffer.read(cx);
 9897                let mut ranges_for_buffer = Vec::new();
 9898                let range = location.range.to_offset(buffer);
 9899                ranges_for_buffer.push(range.clone());
 9900
 9901                while let Some(next_location) = locations.peek() {
 9902                    if next_location.buffer == location.buffer {
 9903                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9904                        locations.next();
 9905                    } else {
 9906                        break;
 9907                    }
 9908                }
 9909
 9910                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9911                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9912                    location.buffer.clone(),
 9913                    ranges_for_buffer,
 9914                    DEFAULT_MULTIBUFFER_CONTEXT,
 9915                    cx,
 9916                ))
 9917            }
 9918
 9919            multibuffer.with_title(title)
 9920        });
 9921
 9922        let editor = cx.new_view(|cx| {
 9923            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9924        });
 9925        editor.update(cx, |editor, cx| {
 9926            if let Some(first_range) = ranges_to_highlight.first() {
 9927                editor.change_selections(None, cx, |selections| {
 9928                    selections.clear_disjoint();
 9929                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9930                });
 9931            }
 9932            editor.highlight_background::<Self>(
 9933                &ranges_to_highlight,
 9934                |theme| theme.editor_highlighted_line_background,
 9935                cx,
 9936            );
 9937            editor.register_buffers_with_language_servers(cx);
 9938        });
 9939
 9940        let item = Box::new(editor);
 9941        let item_id = item.item_id();
 9942
 9943        if split {
 9944            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9945        } else {
 9946            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9947                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9948                    pane.close_current_preview_item(cx)
 9949                } else {
 9950                    None
 9951                }
 9952            });
 9953            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9954        }
 9955        workspace.active_pane().update(cx, |pane, cx| {
 9956            pane.set_preview_item_id(Some(item_id), cx);
 9957        });
 9958    }
 9959
 9960    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9961        use language::ToOffset as _;
 9962
 9963        let provider = self.semantics_provider.clone()?;
 9964        let selection = self.selections.newest_anchor().clone();
 9965        let (cursor_buffer, cursor_buffer_position) = self
 9966            .buffer
 9967            .read(cx)
 9968            .text_anchor_for_position(selection.head(), cx)?;
 9969        let (tail_buffer, cursor_buffer_position_end) = self
 9970            .buffer
 9971            .read(cx)
 9972            .text_anchor_for_position(selection.tail(), cx)?;
 9973        if tail_buffer != cursor_buffer {
 9974            return None;
 9975        }
 9976
 9977        let snapshot = cursor_buffer.read(cx).snapshot();
 9978        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9979        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9980        let prepare_rename = provider
 9981            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9982            .unwrap_or_else(|| Task::ready(Ok(None)));
 9983        drop(snapshot);
 9984
 9985        Some(cx.spawn(|this, mut cx| async move {
 9986            let rename_range = if let Some(range) = prepare_rename.await? {
 9987                Some(range)
 9988            } else {
 9989                this.update(&mut cx, |this, cx| {
 9990                    let buffer = this.buffer.read(cx).snapshot(cx);
 9991                    let mut buffer_highlights = this
 9992                        .document_highlights_for_position(selection.head(), &buffer)
 9993                        .filter(|highlight| {
 9994                            highlight.start.excerpt_id == selection.head().excerpt_id
 9995                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9996                        });
 9997                    buffer_highlights
 9998                        .next()
 9999                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10000                })?
10001            };
10002            if let Some(rename_range) = rename_range {
10003                this.update(&mut cx, |this, cx| {
10004                    let snapshot = cursor_buffer.read(cx).snapshot();
10005                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10006                    let cursor_offset_in_rename_range =
10007                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10008                    let cursor_offset_in_rename_range_end =
10009                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10010
10011                    this.take_rename(false, cx);
10012                    let buffer = this.buffer.read(cx).read(cx);
10013                    let cursor_offset = selection.head().to_offset(&buffer);
10014                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10015                    let rename_end = rename_start + rename_buffer_range.len();
10016                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10017                    let mut old_highlight_id = None;
10018                    let old_name: Arc<str> = buffer
10019                        .chunks(rename_start..rename_end, true)
10020                        .map(|chunk| {
10021                            if old_highlight_id.is_none() {
10022                                old_highlight_id = chunk.syntax_highlight_id;
10023                            }
10024                            chunk.text
10025                        })
10026                        .collect::<String>()
10027                        .into();
10028
10029                    drop(buffer);
10030
10031                    // Position the selection in the rename editor so that it matches the current selection.
10032                    this.show_local_selections = false;
10033                    let rename_editor = cx.new_view(|cx| {
10034                        let mut editor = Editor::single_line(cx);
10035                        editor.buffer.update(cx, |buffer, cx| {
10036                            buffer.edit([(0..0, old_name.clone())], None, cx)
10037                        });
10038                        let rename_selection_range = match cursor_offset_in_rename_range
10039                            .cmp(&cursor_offset_in_rename_range_end)
10040                        {
10041                            Ordering::Equal => {
10042                                editor.select_all(&SelectAll, cx);
10043                                return editor;
10044                            }
10045                            Ordering::Less => {
10046                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10047                            }
10048                            Ordering::Greater => {
10049                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10050                            }
10051                        };
10052                        if rename_selection_range.end > old_name.len() {
10053                            editor.select_all(&SelectAll, cx);
10054                        } else {
10055                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10056                                s.select_ranges([rename_selection_range]);
10057                            });
10058                        }
10059                        editor
10060                    });
10061                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10062                        if e == &EditorEvent::Focused {
10063                            cx.emit(EditorEvent::FocusedIn)
10064                        }
10065                    })
10066                    .detach();
10067
10068                    let write_highlights =
10069                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10070                    let read_highlights =
10071                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10072                    let ranges = write_highlights
10073                        .iter()
10074                        .flat_map(|(_, ranges)| ranges.iter())
10075                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10076                        .cloned()
10077                        .collect();
10078
10079                    this.highlight_text::<Rename>(
10080                        ranges,
10081                        HighlightStyle {
10082                            fade_out: Some(0.6),
10083                            ..Default::default()
10084                        },
10085                        cx,
10086                    );
10087                    let rename_focus_handle = rename_editor.focus_handle(cx);
10088                    cx.focus(&rename_focus_handle);
10089                    let block_id = this.insert_blocks(
10090                        [BlockProperties {
10091                            style: BlockStyle::Flex,
10092                            placement: BlockPlacement::Below(range.start),
10093                            height: 1,
10094                            render: Arc::new({
10095                                let rename_editor = rename_editor.clone();
10096                                move |cx: &mut BlockContext| {
10097                                    let mut text_style = cx.editor_style.text.clone();
10098                                    if let Some(highlight_style) = old_highlight_id
10099                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10100                                    {
10101                                        text_style = text_style.highlight(highlight_style);
10102                                    }
10103                                    div()
10104                                        .block_mouse_down()
10105                                        .pl(cx.anchor_x)
10106                                        .child(EditorElement::new(
10107                                            &rename_editor,
10108                                            EditorStyle {
10109                                                background: cx.theme().system().transparent,
10110                                                local_player: cx.editor_style.local_player,
10111                                                text: text_style,
10112                                                scrollbar_width: cx.editor_style.scrollbar_width,
10113                                                syntax: cx.editor_style.syntax.clone(),
10114                                                status: cx.editor_style.status.clone(),
10115                                                inlay_hints_style: HighlightStyle {
10116                                                    font_weight: Some(FontWeight::BOLD),
10117                                                    ..make_inlay_hints_style(cx)
10118                                                },
10119                                                inline_completion_styles: make_suggestion_styles(
10120                                                    cx,
10121                                                ),
10122                                                ..EditorStyle::default()
10123                                            },
10124                                        ))
10125                                        .into_any_element()
10126                                }
10127                            }),
10128                            priority: 0,
10129                        }],
10130                        Some(Autoscroll::fit()),
10131                        cx,
10132                    )[0];
10133                    this.pending_rename = Some(RenameState {
10134                        range,
10135                        old_name,
10136                        editor: rename_editor,
10137                        block_id,
10138                    });
10139                })?;
10140            }
10141
10142            Ok(())
10143        }))
10144    }
10145
10146    pub fn confirm_rename(
10147        &mut self,
10148        _: &ConfirmRename,
10149        cx: &mut ViewContext<Self>,
10150    ) -> Option<Task<Result<()>>> {
10151        let rename = self.take_rename(false, cx)?;
10152        let workspace = self.workspace()?.downgrade();
10153        let (buffer, start) = self
10154            .buffer
10155            .read(cx)
10156            .text_anchor_for_position(rename.range.start, cx)?;
10157        let (end_buffer, _) = self
10158            .buffer
10159            .read(cx)
10160            .text_anchor_for_position(rename.range.end, cx)?;
10161        if buffer != end_buffer {
10162            return None;
10163        }
10164
10165        let old_name = rename.old_name;
10166        let new_name = rename.editor.read(cx).text(cx);
10167
10168        let rename = self.semantics_provider.as_ref()?.perform_rename(
10169            &buffer,
10170            start,
10171            new_name.clone(),
10172            cx,
10173        )?;
10174
10175        Some(cx.spawn(|editor, mut cx| async move {
10176            let project_transaction = rename.await?;
10177            Self::open_project_transaction(
10178                &editor,
10179                workspace,
10180                project_transaction,
10181                format!("Rename: {}{}", old_name, new_name),
10182                cx.clone(),
10183            )
10184            .await?;
10185
10186            editor.update(&mut cx, |editor, cx| {
10187                editor.refresh_document_highlights(cx);
10188            })?;
10189            Ok(())
10190        }))
10191    }
10192
10193    fn take_rename(
10194        &mut self,
10195        moving_cursor: bool,
10196        cx: &mut ViewContext<Self>,
10197    ) -> Option<RenameState> {
10198        let rename = self.pending_rename.take()?;
10199        if rename.editor.focus_handle(cx).is_focused(cx) {
10200            cx.focus(&self.focus_handle);
10201        }
10202
10203        self.remove_blocks(
10204            [rename.block_id].into_iter().collect(),
10205            Some(Autoscroll::fit()),
10206            cx,
10207        );
10208        self.clear_highlights::<Rename>(cx);
10209        self.show_local_selections = true;
10210
10211        if moving_cursor {
10212            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10213                editor.selections.newest::<usize>(cx).head()
10214            });
10215
10216            // Update the selection to match the position of the selection inside
10217            // the rename editor.
10218            let snapshot = self.buffer.read(cx).read(cx);
10219            let rename_range = rename.range.to_offset(&snapshot);
10220            let cursor_in_editor = snapshot
10221                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10222                .min(rename_range.end);
10223            drop(snapshot);
10224
10225            self.change_selections(None, cx, |s| {
10226                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10227            });
10228        } else {
10229            self.refresh_document_highlights(cx);
10230        }
10231
10232        Some(rename)
10233    }
10234
10235    pub fn pending_rename(&self) -> Option<&RenameState> {
10236        self.pending_rename.as_ref()
10237    }
10238
10239    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10240        let project = match &self.project {
10241            Some(project) => project.clone(),
10242            None => return None,
10243        };
10244
10245        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffers, cx))
10246    }
10247
10248    fn format_selections(
10249        &mut self,
10250        _: &FormatSelections,
10251        cx: &mut ViewContext<Self>,
10252    ) -> Option<Task<Result<()>>> {
10253        let project = match &self.project {
10254            Some(project) => project.clone(),
10255            None => return None,
10256        };
10257
10258        let ranges = self
10259            .selections
10260            .all_adjusted(cx)
10261            .into_iter()
10262            .map(|selection| selection.range())
10263            .collect_vec();
10264
10265        Some(self.perform_format(
10266            project,
10267            FormatTrigger::Manual,
10268            FormatTarget::Ranges(ranges),
10269            cx,
10270        ))
10271    }
10272
10273    fn perform_format(
10274        &mut self,
10275        project: Model<Project>,
10276        trigger: FormatTrigger,
10277        target: FormatTarget,
10278        cx: &mut ViewContext<Self>,
10279    ) -> Task<Result<()>> {
10280        let buffer = self.buffer.clone();
10281        let (buffers, target) = match target {
10282            FormatTarget::Buffers => {
10283                let mut buffers = buffer.read(cx).all_buffers();
10284                if trigger == FormatTrigger::Save {
10285                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10286                }
10287                (buffers, LspFormatTarget::Buffers)
10288            }
10289            FormatTarget::Ranges(selection_ranges) => {
10290                let multi_buffer = buffer.read(cx);
10291                let snapshot = multi_buffer.read(cx);
10292                let mut buffers = HashSet::default();
10293                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10294                    BTreeMap::new();
10295                for selection_range in selection_ranges {
10296                    for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10297                    {
10298                        let buffer_id = excerpt.buffer_id();
10299                        let start = excerpt.buffer().anchor_before(buffer_range.start);
10300                        let end = excerpt.buffer().anchor_after(buffer_range.end);
10301                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10302                        buffer_id_to_ranges
10303                            .entry(buffer_id)
10304                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10305                            .or_insert_with(|| vec![start..end]);
10306                    }
10307                }
10308                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10309            }
10310        };
10311
10312        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10313        let format = project.update(cx, |project, cx| {
10314            project.format(buffers, target, true, trigger, cx)
10315        });
10316
10317        cx.spawn(|_, mut cx| async move {
10318            let transaction = futures::select_biased! {
10319                () = timeout => {
10320                    log::warn!("timed out waiting for formatting");
10321                    None
10322                }
10323                transaction = format.log_err().fuse() => transaction,
10324            };
10325
10326            buffer
10327                .update(&mut cx, |buffer, cx| {
10328                    if let Some(transaction) = transaction {
10329                        if !buffer.is_singleton() {
10330                            buffer.push_transaction(&transaction.0, cx);
10331                        }
10332                    }
10333
10334                    cx.notify();
10335                })
10336                .ok();
10337
10338            Ok(())
10339        })
10340    }
10341
10342    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10343        if let Some(project) = self.project.clone() {
10344            self.buffer.update(cx, |multi_buffer, cx| {
10345                project.update(cx, |project, cx| {
10346                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10347                });
10348            })
10349        }
10350    }
10351
10352    fn cancel_language_server_work(
10353        &mut self,
10354        _: &actions::CancelLanguageServerWork,
10355        cx: &mut ViewContext<Self>,
10356    ) {
10357        if let Some(project) = self.project.clone() {
10358            self.buffer.update(cx, |multi_buffer, cx| {
10359                project.update(cx, |project, cx| {
10360                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10361                });
10362            })
10363        }
10364    }
10365
10366    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10367        cx.show_character_palette();
10368    }
10369
10370    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10371        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10372            let buffer = self.buffer.read(cx).snapshot(cx);
10373            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10374            let is_valid = buffer
10375                .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10376                .any(|entry| {
10377                    let range = entry.range.to_offset(&buffer);
10378                    entry.diagnostic.is_primary
10379                        && !range.is_empty()
10380                        && range.start == primary_range_start
10381                        && entry.diagnostic.message == active_diagnostics.primary_message
10382                });
10383
10384            if is_valid != active_diagnostics.is_valid {
10385                active_diagnostics.is_valid = is_valid;
10386                let mut new_styles = HashMap::default();
10387                for (block_id, diagnostic) in &active_diagnostics.blocks {
10388                    new_styles.insert(
10389                        *block_id,
10390                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10391                    );
10392                }
10393                self.display_map.update(cx, |display_map, _cx| {
10394                    display_map.replace_blocks(new_styles)
10395                });
10396            }
10397        }
10398    }
10399
10400    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10401        self.dismiss_diagnostics(cx);
10402        let snapshot = self.snapshot(cx);
10403        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10404            let buffer = self.buffer.read(cx).snapshot(cx);
10405
10406            let mut primary_range = None;
10407            let mut primary_message = None;
10408            let mut group_end = Point::zero();
10409            let diagnostic_group = buffer
10410                .diagnostic_group(group_id)
10411                .filter_map(|entry| {
10412                    let start = entry.range.start.to_point(&buffer);
10413                    let end = entry.range.end.to_point(&buffer);
10414                    if snapshot.is_line_folded(MultiBufferRow(start.row))
10415                        && (start.row == end.row
10416                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
10417                    {
10418                        return None;
10419                    }
10420                    if end > group_end {
10421                        group_end = end;
10422                    }
10423                    if entry.diagnostic.is_primary {
10424                        primary_range = Some(entry.range.clone());
10425                        primary_message = Some(entry.diagnostic.message.clone());
10426                    }
10427                    Some(entry)
10428                })
10429                .collect::<Vec<_>>();
10430            let primary_range = primary_range?;
10431            let primary_message = primary_message?;
10432
10433            let blocks = display_map
10434                .insert_blocks(
10435                    diagnostic_group.iter().map(|entry| {
10436                        let diagnostic = entry.diagnostic.clone();
10437                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10438                        BlockProperties {
10439                            style: BlockStyle::Fixed,
10440                            placement: BlockPlacement::Below(
10441                                buffer.anchor_after(entry.range.start),
10442                            ),
10443                            height: message_height,
10444                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10445                            priority: 0,
10446                        }
10447                    }),
10448                    cx,
10449                )
10450                .into_iter()
10451                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10452                .collect();
10453
10454            Some(ActiveDiagnosticGroup {
10455                primary_range,
10456                primary_message,
10457                group_id,
10458                blocks,
10459                is_valid: true,
10460            })
10461        });
10462    }
10463
10464    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10465        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10466            self.display_map.update(cx, |display_map, cx| {
10467                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10468            });
10469            cx.notify();
10470        }
10471    }
10472
10473    pub fn set_selections_from_remote(
10474        &mut self,
10475        selections: Vec<Selection<Anchor>>,
10476        pending_selection: Option<Selection<Anchor>>,
10477        cx: &mut ViewContext<Self>,
10478    ) {
10479        let old_cursor_position = self.selections.newest_anchor().head();
10480        self.selections.change_with(cx, |s| {
10481            s.select_anchors(selections);
10482            if let Some(pending_selection) = pending_selection {
10483                s.set_pending(pending_selection, SelectMode::Character);
10484            } else {
10485                s.clear_pending();
10486            }
10487        });
10488        self.selections_did_change(false, &old_cursor_position, true, cx);
10489    }
10490
10491    fn push_to_selection_history(&mut self) {
10492        self.selection_history.push(SelectionHistoryEntry {
10493            selections: self.selections.disjoint_anchors(),
10494            select_next_state: self.select_next_state.clone(),
10495            select_prev_state: self.select_prev_state.clone(),
10496            add_selections_state: self.add_selections_state.clone(),
10497        });
10498    }
10499
10500    pub fn transact(
10501        &mut self,
10502        cx: &mut ViewContext<Self>,
10503        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10504    ) -> Option<TransactionId> {
10505        self.start_transaction_at(Instant::now(), cx);
10506        update(self, cx);
10507        self.end_transaction_at(Instant::now(), cx)
10508    }
10509
10510    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10511        self.end_selection(cx);
10512        if let Some(tx_id) = self
10513            .buffer
10514            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10515        {
10516            self.selection_history
10517                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10518            cx.emit(EditorEvent::TransactionBegun {
10519                transaction_id: tx_id,
10520            })
10521        }
10522    }
10523
10524    pub fn end_transaction_at(
10525        &mut self,
10526        now: Instant,
10527        cx: &mut ViewContext<Self>,
10528    ) -> Option<TransactionId> {
10529        if let Some(transaction_id) = self
10530            .buffer
10531            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10532        {
10533            if let Some((_, end_selections)) =
10534                self.selection_history.transaction_mut(transaction_id)
10535            {
10536                *end_selections = Some(self.selections.disjoint_anchors());
10537            } else {
10538                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10539            }
10540
10541            cx.emit(EditorEvent::Edited { transaction_id });
10542            Some(transaction_id)
10543        } else {
10544            None
10545        }
10546    }
10547
10548    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10549        if self.is_singleton(cx) {
10550            let selection = self.selections.newest::<Point>(cx);
10551
10552            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10553            let range = if selection.is_empty() {
10554                let point = selection.head().to_display_point(&display_map);
10555                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10556                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10557                    .to_point(&display_map);
10558                start..end
10559            } else {
10560                selection.range()
10561            };
10562            if display_map.folds_in_range(range).next().is_some() {
10563                self.unfold_lines(&Default::default(), cx)
10564            } else {
10565                self.fold(&Default::default(), cx)
10566            }
10567        } else {
10568            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10569            let mut toggled_buffers = HashSet::default();
10570            for (_, buffer_snapshot, _) in
10571                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10572            {
10573                let buffer_id = buffer_snapshot.remote_id();
10574                if toggled_buffers.insert(buffer_id) {
10575                    if self.buffer_folded(buffer_id, cx) {
10576                        self.unfold_buffer(buffer_id, cx);
10577                    } else {
10578                        self.fold_buffer(buffer_id, cx);
10579                    }
10580                }
10581            }
10582        }
10583    }
10584
10585    pub fn toggle_fold_recursive(
10586        &mut self,
10587        _: &actions::ToggleFoldRecursive,
10588        cx: &mut ViewContext<Self>,
10589    ) {
10590        let selection = self.selections.newest::<Point>(cx);
10591
10592        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10593        let range = if selection.is_empty() {
10594            let point = selection.head().to_display_point(&display_map);
10595            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10596            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10597                .to_point(&display_map);
10598            start..end
10599        } else {
10600            selection.range()
10601        };
10602        if display_map.folds_in_range(range).next().is_some() {
10603            self.unfold_recursive(&Default::default(), cx)
10604        } else {
10605            self.fold_recursive(&Default::default(), cx)
10606        }
10607    }
10608
10609    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10610        if self.is_singleton(cx) {
10611            let mut to_fold = Vec::new();
10612            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10613            let selections = self.selections.all_adjusted(cx);
10614
10615            for selection in selections {
10616                let range = selection.range().sorted();
10617                let buffer_start_row = range.start.row;
10618
10619                if range.start.row != range.end.row {
10620                    let mut found = false;
10621                    let mut row = range.start.row;
10622                    while row <= range.end.row {
10623                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10624                        {
10625                            found = true;
10626                            row = crease.range().end.row + 1;
10627                            to_fold.push(crease);
10628                        } else {
10629                            row += 1
10630                        }
10631                    }
10632                    if found {
10633                        continue;
10634                    }
10635                }
10636
10637                for row in (0..=range.start.row).rev() {
10638                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10639                        if crease.range().end.row >= buffer_start_row {
10640                            to_fold.push(crease);
10641                            if row <= range.start.row {
10642                                break;
10643                            }
10644                        }
10645                    }
10646                }
10647            }
10648
10649            self.fold_creases(to_fold, true, cx);
10650        } else {
10651            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10652            let mut folded_buffers = HashSet::default();
10653            for (_, buffer_snapshot, _) in
10654                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10655            {
10656                let buffer_id = buffer_snapshot.remote_id();
10657                if folded_buffers.insert(buffer_id) {
10658                    self.fold_buffer(buffer_id, cx);
10659                }
10660            }
10661        }
10662    }
10663
10664    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10665        if !self.buffer.read(cx).is_singleton() {
10666            return;
10667        }
10668
10669        let fold_at_level = fold_at.level;
10670        let snapshot = self.buffer.read(cx).snapshot(cx);
10671        let mut to_fold = Vec::new();
10672        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10673
10674        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10675            while start_row < end_row {
10676                match self
10677                    .snapshot(cx)
10678                    .crease_for_buffer_row(MultiBufferRow(start_row))
10679                {
10680                    Some(crease) => {
10681                        let nested_start_row = crease.range().start.row + 1;
10682                        let nested_end_row = crease.range().end.row;
10683
10684                        if current_level < fold_at_level {
10685                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10686                        } else if current_level == fold_at_level {
10687                            to_fold.push(crease);
10688                        }
10689
10690                        start_row = nested_end_row + 1;
10691                    }
10692                    None => start_row += 1,
10693                }
10694            }
10695        }
10696
10697        self.fold_creases(to_fold, true, cx);
10698    }
10699
10700    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10701        if self.buffer.read(cx).is_singleton() {
10702            let mut fold_ranges = Vec::new();
10703            let snapshot = self.buffer.read(cx).snapshot(cx);
10704
10705            for row in 0..snapshot.max_row().0 {
10706                if let Some(foldable_range) =
10707                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10708                {
10709                    fold_ranges.push(foldable_range);
10710                }
10711            }
10712
10713            self.fold_creases(fold_ranges, true, cx);
10714        } else {
10715            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10716                editor
10717                    .update(&mut cx, |editor, cx| {
10718                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10719                            editor.fold_buffer(buffer_id, cx);
10720                        }
10721                    })
10722                    .ok();
10723            });
10724        }
10725    }
10726
10727    pub fn fold_function_bodies(
10728        &mut self,
10729        _: &actions::FoldFunctionBodies,
10730        cx: &mut ViewContext<Self>,
10731    ) {
10732        let snapshot = self.buffer.read(cx).snapshot(cx);
10733        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10734            return;
10735        };
10736        let creases = buffer
10737            .function_body_fold_ranges(0..buffer.len())
10738            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10739            .collect();
10740
10741        self.fold_creases(creases, true, cx);
10742    }
10743
10744    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10745        let mut to_fold = Vec::new();
10746        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10747        let selections = self.selections.all_adjusted(cx);
10748
10749        for selection in selections {
10750            let range = selection.range().sorted();
10751            let buffer_start_row = range.start.row;
10752
10753            if range.start.row != range.end.row {
10754                let mut found = false;
10755                for row in range.start.row..=range.end.row {
10756                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10757                        found = true;
10758                        to_fold.push(crease);
10759                    }
10760                }
10761                if found {
10762                    continue;
10763                }
10764            }
10765
10766            for row in (0..=range.start.row).rev() {
10767                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10768                    if crease.range().end.row >= buffer_start_row {
10769                        to_fold.push(crease);
10770                    } else {
10771                        break;
10772                    }
10773                }
10774            }
10775        }
10776
10777        self.fold_creases(to_fold, true, cx);
10778    }
10779
10780    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10781        let buffer_row = fold_at.buffer_row;
10782        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10783
10784        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10785            let autoscroll = self
10786                .selections
10787                .all::<Point>(cx)
10788                .iter()
10789                .any(|selection| crease.range().overlaps(&selection.range()));
10790
10791            self.fold_creases(vec![crease], autoscroll, cx);
10792        }
10793    }
10794
10795    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10796        if self.is_singleton(cx) {
10797            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10798            let buffer = &display_map.buffer_snapshot;
10799            let selections = self.selections.all::<Point>(cx);
10800            let ranges = selections
10801                .iter()
10802                .map(|s| {
10803                    let range = s.display_range(&display_map).sorted();
10804                    let mut start = range.start.to_point(&display_map);
10805                    let mut end = range.end.to_point(&display_map);
10806                    start.column = 0;
10807                    end.column = buffer.line_len(MultiBufferRow(end.row));
10808                    start..end
10809                })
10810                .collect::<Vec<_>>();
10811
10812            self.unfold_ranges(&ranges, true, true, cx);
10813        } else {
10814            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10815            let mut unfolded_buffers = HashSet::default();
10816            for (_, buffer_snapshot, _) in
10817                multi_buffer_snapshot.excerpts_in_ranges(self.selections.disjoint_anchor_ranges())
10818            {
10819                let buffer_id = buffer_snapshot.remote_id();
10820                if unfolded_buffers.insert(buffer_id) {
10821                    self.unfold_buffer(buffer_id, cx);
10822                }
10823            }
10824        }
10825    }
10826
10827    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10828        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10829        let selections = self.selections.all::<Point>(cx);
10830        let ranges = selections
10831            .iter()
10832            .map(|s| {
10833                let mut range = s.display_range(&display_map).sorted();
10834                *range.start.column_mut() = 0;
10835                *range.end.column_mut() = display_map.line_len(range.end.row());
10836                let start = range.start.to_point(&display_map);
10837                let end = range.end.to_point(&display_map);
10838                start..end
10839            })
10840            .collect::<Vec<_>>();
10841
10842        self.unfold_ranges(&ranges, true, true, cx);
10843    }
10844
10845    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10846        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10847
10848        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10849            ..Point::new(
10850                unfold_at.buffer_row.0,
10851                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10852            );
10853
10854        let autoscroll = self
10855            .selections
10856            .all::<Point>(cx)
10857            .iter()
10858            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10859
10860        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10861    }
10862
10863    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10864        if self.buffer.read(cx).is_singleton() {
10865            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10866            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10867        } else {
10868            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10869                editor
10870                    .update(&mut cx, |editor, cx| {
10871                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10872                            editor.unfold_buffer(buffer_id, cx);
10873                        }
10874                    })
10875                    .ok();
10876            });
10877        }
10878    }
10879
10880    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10881        let selections = self.selections.all::<Point>(cx);
10882        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10883        let line_mode = self.selections.line_mode;
10884        let ranges = selections
10885            .into_iter()
10886            .map(|s| {
10887                if line_mode {
10888                    let start = Point::new(s.start.row, 0);
10889                    let end = Point::new(
10890                        s.end.row,
10891                        display_map
10892                            .buffer_snapshot
10893                            .line_len(MultiBufferRow(s.end.row)),
10894                    );
10895                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10896                } else {
10897                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10898                }
10899            })
10900            .collect::<Vec<_>>();
10901        self.fold_creases(ranges, true, cx);
10902    }
10903
10904    pub fn fold_creases<T: ToOffset + Clone>(
10905        &mut self,
10906        creases: Vec<Crease<T>>,
10907        auto_scroll: bool,
10908        cx: &mut ViewContext<Self>,
10909    ) {
10910        if creases.is_empty() {
10911            return;
10912        }
10913
10914        let mut buffers_affected = HashSet::default();
10915        let multi_buffer = self.buffer().read(cx);
10916        for crease in &creases {
10917            if let Some((_, buffer, _)) =
10918                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10919            {
10920                buffers_affected.insert(buffer.read(cx).remote_id());
10921            };
10922        }
10923
10924        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10925
10926        if auto_scroll {
10927            self.request_autoscroll(Autoscroll::fit(), cx);
10928        }
10929
10930        for buffer_id in buffers_affected {
10931            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10932        }
10933
10934        cx.notify();
10935
10936        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10937            // Clear diagnostics block when folding a range that contains it.
10938            let snapshot = self.snapshot(cx);
10939            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10940                drop(snapshot);
10941                self.active_diagnostics = Some(active_diagnostics);
10942                self.dismiss_diagnostics(cx);
10943            } else {
10944                self.active_diagnostics = Some(active_diagnostics);
10945            }
10946        }
10947
10948        self.scrollbar_marker_state.dirty = true;
10949    }
10950
10951    /// Removes any folds whose ranges intersect any of the given ranges.
10952    pub fn unfold_ranges<T: ToOffset + Clone>(
10953        &mut self,
10954        ranges: &[Range<T>],
10955        inclusive: bool,
10956        auto_scroll: bool,
10957        cx: &mut ViewContext<Self>,
10958    ) {
10959        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10960            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10961        });
10962    }
10963
10964    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10965        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10966            return;
10967        }
10968        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10969            return;
10970        };
10971        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10972        self.display_map
10973            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10974        cx.emit(EditorEvent::BufferFoldToggled {
10975            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10976            folded: true,
10977        });
10978        cx.notify();
10979    }
10980
10981    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10982        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10983            return;
10984        }
10985        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10986            return;
10987        };
10988        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10989        self.display_map.update(cx, |display_map, cx| {
10990            display_map.unfold_buffer(buffer_id, cx);
10991        });
10992        cx.emit(EditorEvent::BufferFoldToggled {
10993            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10994            folded: false,
10995        });
10996        cx.notify();
10997    }
10998
10999    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11000        self.display_map.read(cx).buffer_folded(buffer)
11001    }
11002
11003    /// Removes any folds with the given ranges.
11004    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11005        &mut self,
11006        ranges: &[Range<T>],
11007        type_id: TypeId,
11008        auto_scroll: bool,
11009        cx: &mut ViewContext<Self>,
11010    ) {
11011        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11012            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11013        });
11014    }
11015
11016    fn remove_folds_with<T: ToOffset + Clone>(
11017        &mut self,
11018        ranges: &[Range<T>],
11019        auto_scroll: bool,
11020        cx: &mut ViewContext<Self>,
11021        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11022    ) {
11023        if ranges.is_empty() {
11024            return;
11025        }
11026
11027        let mut buffers_affected = HashSet::default();
11028        let multi_buffer = self.buffer().read(cx);
11029        for range in ranges {
11030            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11031                buffers_affected.insert(buffer.read(cx).remote_id());
11032            };
11033        }
11034
11035        self.display_map.update(cx, update);
11036
11037        if auto_scroll {
11038            self.request_autoscroll(Autoscroll::fit(), cx);
11039        }
11040
11041        for buffer_id in buffers_affected {
11042            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11043        }
11044
11045        cx.notify();
11046        self.scrollbar_marker_state.dirty = true;
11047        self.active_indent_guides_state.dirty = true;
11048    }
11049
11050    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11051        self.display_map.read(cx).fold_placeholder.clone()
11052    }
11053
11054    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11055        if hovered != self.gutter_hovered {
11056            self.gutter_hovered = hovered;
11057            cx.notify();
11058        }
11059    }
11060
11061    pub fn insert_blocks(
11062        &mut self,
11063        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11064        autoscroll: Option<Autoscroll>,
11065        cx: &mut ViewContext<Self>,
11066    ) -> Vec<CustomBlockId> {
11067        let blocks = self
11068            .display_map
11069            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11070        if let Some(autoscroll) = autoscroll {
11071            self.request_autoscroll(autoscroll, cx);
11072        }
11073        cx.notify();
11074        blocks
11075    }
11076
11077    pub fn resize_blocks(
11078        &mut self,
11079        heights: HashMap<CustomBlockId, u32>,
11080        autoscroll: Option<Autoscroll>,
11081        cx: &mut ViewContext<Self>,
11082    ) {
11083        self.display_map
11084            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11085        if let Some(autoscroll) = autoscroll {
11086            self.request_autoscroll(autoscroll, cx);
11087        }
11088        cx.notify();
11089    }
11090
11091    pub fn replace_blocks(
11092        &mut self,
11093        renderers: HashMap<CustomBlockId, RenderBlock>,
11094        autoscroll: Option<Autoscroll>,
11095        cx: &mut ViewContext<Self>,
11096    ) {
11097        self.display_map
11098            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11099        if let Some(autoscroll) = autoscroll {
11100            self.request_autoscroll(autoscroll, cx);
11101        }
11102        cx.notify();
11103    }
11104
11105    pub fn remove_blocks(
11106        &mut self,
11107        block_ids: HashSet<CustomBlockId>,
11108        autoscroll: Option<Autoscroll>,
11109        cx: &mut ViewContext<Self>,
11110    ) {
11111        self.display_map.update(cx, |display_map, cx| {
11112            display_map.remove_blocks(block_ids, cx)
11113        });
11114        if let Some(autoscroll) = autoscroll {
11115            self.request_autoscroll(autoscroll, cx);
11116        }
11117        cx.notify();
11118    }
11119
11120    pub fn row_for_block(
11121        &self,
11122        block_id: CustomBlockId,
11123        cx: &mut ViewContext<Self>,
11124    ) -> Option<DisplayRow> {
11125        self.display_map
11126            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11127    }
11128
11129    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11130        self.focused_block = Some(focused_block);
11131    }
11132
11133    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11134        self.focused_block.take()
11135    }
11136
11137    pub fn insert_creases(
11138        &mut self,
11139        creases: impl IntoIterator<Item = Crease<Anchor>>,
11140        cx: &mut ViewContext<Self>,
11141    ) -> Vec<CreaseId> {
11142        self.display_map
11143            .update(cx, |map, cx| map.insert_creases(creases, cx))
11144    }
11145
11146    pub fn remove_creases(
11147        &mut self,
11148        ids: impl IntoIterator<Item = CreaseId>,
11149        cx: &mut ViewContext<Self>,
11150    ) {
11151        self.display_map
11152            .update(cx, |map, cx| map.remove_creases(ids, cx));
11153    }
11154
11155    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11156        self.display_map
11157            .update(cx, |map, cx| map.snapshot(cx))
11158            .longest_row()
11159    }
11160
11161    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11162        self.display_map
11163            .update(cx, |map, cx| map.snapshot(cx))
11164            .max_point()
11165    }
11166
11167    pub fn text(&self, cx: &AppContext) -> String {
11168        self.buffer.read(cx).read(cx).text()
11169    }
11170
11171    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11172        let text = self.text(cx);
11173        let text = text.trim();
11174
11175        if text.is_empty() {
11176            return None;
11177        }
11178
11179        Some(text.to_string())
11180    }
11181
11182    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11183        self.transact(cx, |this, cx| {
11184            this.buffer
11185                .read(cx)
11186                .as_singleton()
11187                .expect("you can only call set_text on editors for singleton buffers")
11188                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11189        });
11190    }
11191
11192    pub fn display_text(&self, cx: &mut AppContext) -> String {
11193        self.display_map
11194            .update(cx, |map, cx| map.snapshot(cx))
11195            .text()
11196    }
11197
11198    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11199        let mut wrap_guides = smallvec::smallvec![];
11200
11201        if self.show_wrap_guides == Some(false) {
11202            return wrap_guides;
11203        }
11204
11205        let settings = self.buffer.read(cx).settings_at(0, cx);
11206        if settings.show_wrap_guides {
11207            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11208                wrap_guides.push((soft_wrap as usize, true));
11209            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11210                wrap_guides.push((soft_wrap as usize, true));
11211            }
11212            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11213        }
11214
11215        wrap_guides
11216    }
11217
11218    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11219        let settings = self.buffer.read(cx).settings_at(0, cx);
11220        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11221        match mode {
11222            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11223                SoftWrap::None
11224            }
11225            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11226            language_settings::SoftWrap::PreferredLineLength => {
11227                SoftWrap::Column(settings.preferred_line_length)
11228            }
11229            language_settings::SoftWrap::Bounded => {
11230                SoftWrap::Bounded(settings.preferred_line_length)
11231            }
11232        }
11233    }
11234
11235    pub fn set_soft_wrap_mode(
11236        &mut self,
11237        mode: language_settings::SoftWrap,
11238        cx: &mut ViewContext<Self>,
11239    ) {
11240        self.soft_wrap_mode_override = Some(mode);
11241        cx.notify();
11242    }
11243
11244    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11245        self.text_style_refinement = Some(style);
11246    }
11247
11248    /// called by the Element so we know what style we were most recently rendered with.
11249    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11250        let rem_size = cx.rem_size();
11251        self.display_map.update(cx, |map, cx| {
11252            map.set_font(
11253                style.text.font(),
11254                style.text.font_size.to_pixels(rem_size),
11255                cx,
11256            )
11257        });
11258        self.style = Some(style);
11259    }
11260
11261    pub fn style(&self) -> Option<&EditorStyle> {
11262        self.style.as_ref()
11263    }
11264
11265    // Called by the element. This method is not designed to be called outside of the editor
11266    // element's layout code because it does not notify when rewrapping is computed synchronously.
11267    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11268        self.display_map
11269            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11270    }
11271
11272    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11273        if self.soft_wrap_mode_override.is_some() {
11274            self.soft_wrap_mode_override.take();
11275        } else {
11276            let soft_wrap = match self.soft_wrap_mode(cx) {
11277                SoftWrap::GitDiff => return,
11278                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11279                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11280                    language_settings::SoftWrap::None
11281                }
11282            };
11283            self.soft_wrap_mode_override = Some(soft_wrap);
11284        }
11285        cx.notify();
11286    }
11287
11288    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11289        let Some(workspace) = self.workspace() else {
11290            return;
11291        };
11292        let fs = workspace.read(cx).app_state().fs.clone();
11293        let current_show = TabBarSettings::get_global(cx).show;
11294        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11295            setting.show = Some(!current_show);
11296        });
11297    }
11298
11299    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11300        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11301            self.buffer
11302                .read(cx)
11303                .settings_at(0, cx)
11304                .indent_guides
11305                .enabled
11306        });
11307        self.show_indent_guides = Some(!currently_enabled);
11308        cx.notify();
11309    }
11310
11311    fn should_show_indent_guides(&self) -> Option<bool> {
11312        self.show_indent_guides
11313    }
11314
11315    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11316        let mut editor_settings = EditorSettings::get_global(cx).clone();
11317        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11318        EditorSettings::override_global(editor_settings, cx);
11319    }
11320
11321    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11322        self.use_relative_line_numbers
11323            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11324    }
11325
11326    pub fn toggle_relative_line_numbers(
11327        &mut self,
11328        _: &ToggleRelativeLineNumbers,
11329        cx: &mut ViewContext<Self>,
11330    ) {
11331        let is_relative = self.should_use_relative_line_numbers(cx);
11332        self.set_relative_line_number(Some(!is_relative), cx)
11333    }
11334
11335    pub fn set_relative_line_number(
11336        &mut self,
11337        is_relative: Option<bool>,
11338        cx: &mut ViewContext<Self>,
11339    ) {
11340        self.use_relative_line_numbers = is_relative;
11341        cx.notify();
11342    }
11343
11344    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11345        self.show_gutter = show_gutter;
11346        cx.notify();
11347    }
11348
11349    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11350        self.show_scrollbars = show_scrollbars;
11351        cx.notify();
11352    }
11353
11354    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11355        self.show_line_numbers = Some(show_line_numbers);
11356        cx.notify();
11357    }
11358
11359    pub fn set_show_git_diff_gutter(
11360        &mut self,
11361        show_git_diff_gutter: bool,
11362        cx: &mut ViewContext<Self>,
11363    ) {
11364        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11365        cx.notify();
11366    }
11367
11368    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11369        self.show_code_actions = Some(show_code_actions);
11370        cx.notify();
11371    }
11372
11373    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11374        self.show_runnables = Some(show_runnables);
11375        cx.notify();
11376    }
11377
11378    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11379        if self.display_map.read(cx).masked != masked {
11380            self.display_map.update(cx, |map, _| map.masked = masked);
11381        }
11382        cx.notify()
11383    }
11384
11385    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11386        self.show_wrap_guides = Some(show_wrap_guides);
11387        cx.notify();
11388    }
11389
11390    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11391        self.show_indent_guides = Some(show_indent_guides);
11392        cx.notify();
11393    }
11394
11395    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11396        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11397            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11398                if let Some(dir) = file.abs_path(cx).parent() {
11399                    return Some(dir.to_owned());
11400                }
11401            }
11402
11403            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11404                return Some(project_path.path.to_path_buf());
11405            }
11406        }
11407
11408        None
11409    }
11410
11411    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11412        self.active_excerpt(cx)?
11413            .1
11414            .read(cx)
11415            .file()
11416            .and_then(|f| f.as_local())
11417    }
11418
11419    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11420        if let Some(target) = self.target_file(cx) {
11421            cx.reveal_path(&target.abs_path(cx));
11422        }
11423    }
11424
11425    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11426        if let Some(file) = self.target_file(cx) {
11427            if let Some(path) = file.abs_path(cx).to_str() {
11428                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11429            }
11430        }
11431    }
11432
11433    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11434        if let Some(file) = self.target_file(cx) {
11435            if let Some(path) = file.path().to_str() {
11436                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11437            }
11438        }
11439    }
11440
11441    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11442        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11443
11444        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11445            self.start_git_blame(true, cx);
11446        }
11447
11448        cx.notify();
11449    }
11450
11451    pub fn toggle_git_blame_inline(
11452        &mut self,
11453        _: &ToggleGitBlameInline,
11454        cx: &mut ViewContext<Self>,
11455    ) {
11456        self.toggle_git_blame_inline_internal(true, cx);
11457        cx.notify();
11458    }
11459
11460    pub fn git_blame_inline_enabled(&self) -> bool {
11461        self.git_blame_inline_enabled
11462    }
11463
11464    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11465        self.show_selection_menu = self
11466            .show_selection_menu
11467            .map(|show_selections_menu| !show_selections_menu)
11468            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11469
11470        cx.notify();
11471    }
11472
11473    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11474        self.show_selection_menu
11475            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11476    }
11477
11478    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11479        if let Some(project) = self.project.as_ref() {
11480            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11481                return;
11482            };
11483
11484            if buffer.read(cx).file().is_none() {
11485                return;
11486            }
11487
11488            let focused = self.focus_handle(cx).contains_focused(cx);
11489
11490            let project = project.clone();
11491            let blame =
11492                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11493            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11494            self.blame = Some(blame);
11495        }
11496    }
11497
11498    fn toggle_git_blame_inline_internal(
11499        &mut self,
11500        user_triggered: bool,
11501        cx: &mut ViewContext<Self>,
11502    ) {
11503        if self.git_blame_inline_enabled {
11504            self.git_blame_inline_enabled = false;
11505            self.show_git_blame_inline = false;
11506            self.show_git_blame_inline_delay_task.take();
11507        } else {
11508            self.git_blame_inline_enabled = true;
11509            self.start_git_blame_inline(user_triggered, cx);
11510        }
11511
11512        cx.notify();
11513    }
11514
11515    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11516        self.start_git_blame(user_triggered, cx);
11517
11518        if ProjectSettings::get_global(cx)
11519            .git
11520            .inline_blame_delay()
11521            .is_some()
11522        {
11523            self.start_inline_blame_timer(cx);
11524        } else {
11525            self.show_git_blame_inline = true
11526        }
11527    }
11528
11529    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11530        self.blame.as_ref()
11531    }
11532
11533    pub fn show_git_blame_gutter(&self) -> bool {
11534        self.show_git_blame_gutter
11535    }
11536
11537    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11538        self.show_git_blame_gutter && self.has_blame_entries(cx)
11539    }
11540
11541    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11542        self.show_git_blame_inline
11543            && self.focus_handle.is_focused(cx)
11544            && !self.newest_selection_head_on_empty_line(cx)
11545            && self.has_blame_entries(cx)
11546    }
11547
11548    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11549        self.blame()
11550            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11551    }
11552
11553    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11554        let cursor_anchor = self.selections.newest_anchor().head();
11555
11556        let snapshot = self.buffer.read(cx).snapshot(cx);
11557        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11558
11559        snapshot.line_len(buffer_row) == 0
11560    }
11561
11562    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11563        let buffer_and_selection = maybe!({
11564            let selection = self.selections.newest::<Point>(cx);
11565            let selection_range = selection.range();
11566
11567            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11568                (buffer, selection_range.start.row..selection_range.end.row)
11569            } else {
11570                let multi_buffer = self.buffer().read(cx);
11571                let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11572                let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11573
11574                let (excerpt, range) = if selection.reversed {
11575                    buffer_ranges.first()
11576                } else {
11577                    buffer_ranges.last()
11578                }?;
11579
11580                let snapshot = excerpt.buffer();
11581                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11582                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11583                (
11584                    multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11585                    selection,
11586                )
11587            };
11588
11589            Some((buffer, selection))
11590        });
11591
11592        let Some((buffer, selection)) = buffer_and_selection else {
11593            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11594        };
11595
11596        let Some(project) = self.project.as_ref() else {
11597            return Task::ready(Err(anyhow!("editor does not have project")));
11598        };
11599
11600        project.update(cx, |project, cx| {
11601            project.get_permalink_to_line(&buffer, selection, cx)
11602        })
11603    }
11604
11605    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11606        let permalink_task = self.get_permalink_to_line(cx);
11607        let workspace = self.workspace();
11608
11609        cx.spawn(|_, mut cx| async move {
11610            match permalink_task.await {
11611                Ok(permalink) => {
11612                    cx.update(|cx| {
11613                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11614                    })
11615                    .ok();
11616                }
11617                Err(err) => {
11618                    let message = format!("Failed to copy permalink: {err}");
11619
11620                    Err::<(), anyhow::Error>(err).log_err();
11621
11622                    if let Some(workspace) = workspace {
11623                        workspace
11624                            .update(&mut cx, |workspace, cx| {
11625                                struct CopyPermalinkToLine;
11626
11627                                workspace.show_toast(
11628                                    Toast::new(
11629                                        NotificationId::unique::<CopyPermalinkToLine>(),
11630                                        message,
11631                                    ),
11632                                    cx,
11633                                )
11634                            })
11635                            .ok();
11636                    }
11637                }
11638            }
11639        })
11640        .detach();
11641    }
11642
11643    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11644        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11645        if let Some(file) = self.target_file(cx) {
11646            if let Some(path) = file.path().to_str() {
11647                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11648            }
11649        }
11650    }
11651
11652    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11653        let permalink_task = self.get_permalink_to_line(cx);
11654        let workspace = self.workspace();
11655
11656        cx.spawn(|_, mut cx| async move {
11657            match permalink_task.await {
11658                Ok(permalink) => {
11659                    cx.update(|cx| {
11660                        cx.open_url(permalink.as_ref());
11661                    })
11662                    .ok();
11663                }
11664                Err(err) => {
11665                    let message = format!("Failed to open permalink: {err}");
11666
11667                    Err::<(), anyhow::Error>(err).log_err();
11668
11669                    if let Some(workspace) = workspace {
11670                        workspace
11671                            .update(&mut cx, |workspace, cx| {
11672                                struct OpenPermalinkToLine;
11673
11674                                workspace.show_toast(
11675                                    Toast::new(
11676                                        NotificationId::unique::<OpenPermalinkToLine>(),
11677                                        message,
11678                                    ),
11679                                    cx,
11680                                )
11681                            })
11682                            .ok();
11683                    }
11684                }
11685            }
11686        })
11687        .detach();
11688    }
11689
11690    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11691        self.insert_uuid(UuidVersion::V4, cx);
11692    }
11693
11694    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11695        self.insert_uuid(UuidVersion::V7, cx);
11696    }
11697
11698    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11699        self.transact(cx, |this, cx| {
11700            let edits = this
11701                .selections
11702                .all::<Point>(cx)
11703                .into_iter()
11704                .map(|selection| {
11705                    let uuid = match version {
11706                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11707                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11708                    };
11709
11710                    (selection.range(), uuid.to_string())
11711                });
11712            this.edit(edits, cx);
11713            this.refresh_inline_completion(true, false, cx);
11714        });
11715    }
11716
11717    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11718    /// last highlight added will be used.
11719    ///
11720    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11721    pub fn highlight_rows<T: 'static>(
11722        &mut self,
11723        range: Range<Anchor>,
11724        color: Hsla,
11725        should_autoscroll: bool,
11726        cx: &mut ViewContext<Self>,
11727    ) {
11728        let snapshot = self.buffer().read(cx).snapshot(cx);
11729        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11730        let ix = row_highlights.binary_search_by(|highlight| {
11731            Ordering::Equal
11732                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11733                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11734        });
11735
11736        if let Err(mut ix) = ix {
11737            let index = post_inc(&mut self.highlight_order);
11738
11739            // If this range intersects with the preceding highlight, then merge it with
11740            // the preceding highlight. Otherwise insert a new highlight.
11741            let mut merged = false;
11742            if ix > 0 {
11743                let prev_highlight = &mut row_highlights[ix - 1];
11744                if prev_highlight
11745                    .range
11746                    .end
11747                    .cmp(&range.start, &snapshot)
11748                    .is_ge()
11749                {
11750                    ix -= 1;
11751                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11752                        prev_highlight.range.end = range.end;
11753                    }
11754                    merged = true;
11755                    prev_highlight.index = index;
11756                    prev_highlight.color = color;
11757                    prev_highlight.should_autoscroll = should_autoscroll;
11758                }
11759            }
11760
11761            if !merged {
11762                row_highlights.insert(
11763                    ix,
11764                    RowHighlight {
11765                        range: range.clone(),
11766                        index,
11767                        color,
11768                        should_autoscroll,
11769                    },
11770                );
11771            }
11772
11773            // If any of the following highlights intersect with this one, merge them.
11774            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11775                let highlight = &row_highlights[ix];
11776                if next_highlight
11777                    .range
11778                    .start
11779                    .cmp(&highlight.range.end, &snapshot)
11780                    .is_le()
11781                {
11782                    if next_highlight
11783                        .range
11784                        .end
11785                        .cmp(&highlight.range.end, &snapshot)
11786                        .is_gt()
11787                    {
11788                        row_highlights[ix].range.end = next_highlight.range.end;
11789                    }
11790                    row_highlights.remove(ix + 1);
11791                } else {
11792                    break;
11793                }
11794            }
11795        }
11796    }
11797
11798    /// Remove any highlighted row ranges of the given type that intersect the
11799    /// given ranges.
11800    pub fn remove_highlighted_rows<T: 'static>(
11801        &mut self,
11802        ranges_to_remove: Vec<Range<Anchor>>,
11803        cx: &mut ViewContext<Self>,
11804    ) {
11805        let snapshot = self.buffer().read(cx).snapshot(cx);
11806        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11807        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11808        row_highlights.retain(|highlight| {
11809            while let Some(range_to_remove) = ranges_to_remove.peek() {
11810                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11811                    Ordering::Less | Ordering::Equal => {
11812                        ranges_to_remove.next();
11813                    }
11814                    Ordering::Greater => {
11815                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11816                            Ordering::Less | Ordering::Equal => {
11817                                return false;
11818                            }
11819                            Ordering::Greater => break,
11820                        }
11821                    }
11822                }
11823            }
11824
11825            true
11826        })
11827    }
11828
11829    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11830    pub fn clear_row_highlights<T: 'static>(&mut self) {
11831        self.highlighted_rows.remove(&TypeId::of::<T>());
11832    }
11833
11834    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11835    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11836        self.highlighted_rows
11837            .get(&TypeId::of::<T>())
11838            .map_or(&[] as &[_], |vec| vec.as_slice())
11839            .iter()
11840            .map(|highlight| (highlight.range.clone(), highlight.color))
11841    }
11842
11843    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11844    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11845    /// Allows to ignore certain kinds of highlights.
11846    pub fn highlighted_display_rows(
11847        &mut self,
11848        cx: &mut WindowContext,
11849    ) -> BTreeMap<DisplayRow, Hsla> {
11850        let snapshot = self.snapshot(cx);
11851        let mut used_highlight_orders = HashMap::default();
11852        self.highlighted_rows
11853            .iter()
11854            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11855            .fold(
11856                BTreeMap::<DisplayRow, Hsla>::new(),
11857                |mut unique_rows, highlight| {
11858                    let start = highlight.range.start.to_display_point(&snapshot);
11859                    let end = highlight.range.end.to_display_point(&snapshot);
11860                    let start_row = start.row().0;
11861                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11862                        && end.column() == 0
11863                    {
11864                        end.row().0.saturating_sub(1)
11865                    } else {
11866                        end.row().0
11867                    };
11868                    for row in start_row..=end_row {
11869                        let used_index =
11870                            used_highlight_orders.entry(row).or_insert(highlight.index);
11871                        if highlight.index >= *used_index {
11872                            *used_index = highlight.index;
11873                            unique_rows.insert(DisplayRow(row), highlight.color);
11874                        }
11875                    }
11876                    unique_rows
11877                },
11878            )
11879    }
11880
11881    pub fn highlighted_display_row_for_autoscroll(
11882        &self,
11883        snapshot: &DisplaySnapshot,
11884    ) -> Option<DisplayRow> {
11885        self.highlighted_rows
11886            .values()
11887            .flat_map(|highlighted_rows| highlighted_rows.iter())
11888            .filter_map(|highlight| {
11889                if highlight.should_autoscroll {
11890                    Some(highlight.range.start.to_display_point(snapshot).row())
11891                } else {
11892                    None
11893                }
11894            })
11895            .min()
11896    }
11897
11898    pub fn set_search_within_ranges(
11899        &mut self,
11900        ranges: &[Range<Anchor>],
11901        cx: &mut ViewContext<Self>,
11902    ) {
11903        self.highlight_background::<SearchWithinRange>(
11904            ranges,
11905            |colors| colors.editor_document_highlight_read_background,
11906            cx,
11907        )
11908    }
11909
11910    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11911        self.breadcrumb_header = Some(new_header);
11912    }
11913
11914    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11915        self.clear_background_highlights::<SearchWithinRange>(cx);
11916    }
11917
11918    pub fn highlight_background<T: 'static>(
11919        &mut self,
11920        ranges: &[Range<Anchor>],
11921        color_fetcher: fn(&ThemeColors) -> Hsla,
11922        cx: &mut ViewContext<Self>,
11923    ) {
11924        self.background_highlights
11925            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11926        self.scrollbar_marker_state.dirty = true;
11927        cx.notify();
11928    }
11929
11930    pub fn clear_background_highlights<T: 'static>(
11931        &mut self,
11932        cx: &mut ViewContext<Self>,
11933    ) -> Option<BackgroundHighlight> {
11934        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11935        if !text_highlights.1.is_empty() {
11936            self.scrollbar_marker_state.dirty = true;
11937            cx.notify();
11938        }
11939        Some(text_highlights)
11940    }
11941
11942    pub fn highlight_gutter<T: 'static>(
11943        &mut self,
11944        ranges: &[Range<Anchor>],
11945        color_fetcher: fn(&AppContext) -> Hsla,
11946        cx: &mut ViewContext<Self>,
11947    ) {
11948        self.gutter_highlights
11949            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11950        cx.notify();
11951    }
11952
11953    pub fn clear_gutter_highlights<T: 'static>(
11954        &mut self,
11955        cx: &mut ViewContext<Self>,
11956    ) -> Option<GutterHighlight> {
11957        cx.notify();
11958        self.gutter_highlights.remove(&TypeId::of::<T>())
11959    }
11960
11961    #[cfg(feature = "test-support")]
11962    pub fn all_text_background_highlights(
11963        &mut self,
11964        cx: &mut ViewContext<Self>,
11965    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11966        let snapshot = self.snapshot(cx);
11967        let buffer = &snapshot.buffer_snapshot;
11968        let start = buffer.anchor_before(0);
11969        let end = buffer.anchor_after(buffer.len());
11970        let theme = cx.theme().colors();
11971        self.background_highlights_in_range(start..end, &snapshot, theme)
11972    }
11973
11974    #[cfg(feature = "test-support")]
11975    pub fn search_background_highlights(
11976        &mut self,
11977        cx: &mut ViewContext<Self>,
11978    ) -> Vec<Range<Point>> {
11979        let snapshot = self.buffer().read(cx).snapshot(cx);
11980
11981        let highlights = self
11982            .background_highlights
11983            .get(&TypeId::of::<items::BufferSearchHighlights>());
11984
11985        if let Some((_color, ranges)) = highlights {
11986            ranges
11987                .iter()
11988                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11989                .collect_vec()
11990        } else {
11991            vec![]
11992        }
11993    }
11994
11995    fn document_highlights_for_position<'a>(
11996        &'a self,
11997        position: Anchor,
11998        buffer: &'a MultiBufferSnapshot,
11999    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12000        let read_highlights = self
12001            .background_highlights
12002            .get(&TypeId::of::<DocumentHighlightRead>())
12003            .map(|h| &h.1);
12004        let write_highlights = self
12005            .background_highlights
12006            .get(&TypeId::of::<DocumentHighlightWrite>())
12007            .map(|h| &h.1);
12008        let left_position = position.bias_left(buffer);
12009        let right_position = position.bias_right(buffer);
12010        read_highlights
12011            .into_iter()
12012            .chain(write_highlights)
12013            .flat_map(move |ranges| {
12014                let start_ix = match ranges.binary_search_by(|probe| {
12015                    let cmp = probe.end.cmp(&left_position, buffer);
12016                    if cmp.is_ge() {
12017                        Ordering::Greater
12018                    } else {
12019                        Ordering::Less
12020                    }
12021                }) {
12022                    Ok(i) | Err(i) => i,
12023                };
12024
12025                ranges[start_ix..]
12026                    .iter()
12027                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12028            })
12029    }
12030
12031    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12032        self.background_highlights
12033            .get(&TypeId::of::<T>())
12034            .map_or(false, |(_, highlights)| !highlights.is_empty())
12035    }
12036
12037    pub fn background_highlights_in_range(
12038        &self,
12039        search_range: Range<Anchor>,
12040        display_snapshot: &DisplaySnapshot,
12041        theme: &ThemeColors,
12042    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12043        let mut results = Vec::new();
12044        for (color_fetcher, ranges) in self.background_highlights.values() {
12045            let color = color_fetcher(theme);
12046            let start_ix = match ranges.binary_search_by(|probe| {
12047                let cmp = probe
12048                    .end
12049                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12050                if cmp.is_gt() {
12051                    Ordering::Greater
12052                } else {
12053                    Ordering::Less
12054                }
12055            }) {
12056                Ok(i) | Err(i) => i,
12057            };
12058            for range in &ranges[start_ix..] {
12059                if range
12060                    .start
12061                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12062                    .is_ge()
12063                {
12064                    break;
12065                }
12066
12067                let start = range.start.to_display_point(display_snapshot);
12068                let end = range.end.to_display_point(display_snapshot);
12069                results.push((start..end, color))
12070            }
12071        }
12072        results
12073    }
12074
12075    pub fn background_highlight_row_ranges<T: 'static>(
12076        &self,
12077        search_range: Range<Anchor>,
12078        display_snapshot: &DisplaySnapshot,
12079        count: usize,
12080    ) -> Vec<RangeInclusive<DisplayPoint>> {
12081        let mut results = Vec::new();
12082        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12083            return vec![];
12084        };
12085
12086        let start_ix = match ranges.binary_search_by(|probe| {
12087            let cmp = probe
12088                .end
12089                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12090            if cmp.is_gt() {
12091                Ordering::Greater
12092            } else {
12093                Ordering::Less
12094            }
12095        }) {
12096            Ok(i) | Err(i) => i,
12097        };
12098        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12099            if let (Some(start_display), Some(end_display)) = (start, end) {
12100                results.push(
12101                    start_display.to_display_point(display_snapshot)
12102                        ..=end_display.to_display_point(display_snapshot),
12103                );
12104            }
12105        };
12106        let mut start_row: Option<Point> = None;
12107        let mut end_row: Option<Point> = None;
12108        if ranges.len() > count {
12109            return Vec::new();
12110        }
12111        for range in &ranges[start_ix..] {
12112            if range
12113                .start
12114                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12115                .is_ge()
12116            {
12117                break;
12118            }
12119            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12120            if let Some(current_row) = &end_row {
12121                if end.row == current_row.row {
12122                    continue;
12123                }
12124            }
12125            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12126            if start_row.is_none() {
12127                assert_eq!(end_row, None);
12128                start_row = Some(start);
12129                end_row = Some(end);
12130                continue;
12131            }
12132            if let Some(current_end) = end_row.as_mut() {
12133                if start.row > current_end.row + 1 {
12134                    push_region(start_row, end_row);
12135                    start_row = Some(start);
12136                    end_row = Some(end);
12137                } else {
12138                    // Merge two hunks.
12139                    *current_end = end;
12140                }
12141            } else {
12142                unreachable!();
12143            }
12144        }
12145        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12146        push_region(start_row, end_row);
12147        results
12148    }
12149
12150    pub fn gutter_highlights_in_range(
12151        &self,
12152        search_range: Range<Anchor>,
12153        display_snapshot: &DisplaySnapshot,
12154        cx: &AppContext,
12155    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12156        let mut results = Vec::new();
12157        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12158            let color = color_fetcher(cx);
12159            let start_ix = match ranges.binary_search_by(|probe| {
12160                let cmp = probe
12161                    .end
12162                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12163                if cmp.is_gt() {
12164                    Ordering::Greater
12165                } else {
12166                    Ordering::Less
12167                }
12168            }) {
12169                Ok(i) | Err(i) => i,
12170            };
12171            for range in &ranges[start_ix..] {
12172                if range
12173                    .start
12174                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12175                    .is_ge()
12176                {
12177                    break;
12178                }
12179
12180                let start = range.start.to_display_point(display_snapshot);
12181                let end = range.end.to_display_point(display_snapshot);
12182                results.push((start..end, color))
12183            }
12184        }
12185        results
12186    }
12187
12188    /// Get the text ranges corresponding to the redaction query
12189    pub fn redacted_ranges(
12190        &self,
12191        search_range: Range<Anchor>,
12192        display_snapshot: &DisplaySnapshot,
12193        cx: &WindowContext,
12194    ) -> Vec<Range<DisplayPoint>> {
12195        display_snapshot
12196            .buffer_snapshot
12197            .redacted_ranges(search_range, |file| {
12198                if let Some(file) = file {
12199                    file.is_private()
12200                        && EditorSettings::get(
12201                            Some(SettingsLocation {
12202                                worktree_id: file.worktree_id(cx),
12203                                path: file.path().as_ref(),
12204                            }),
12205                            cx,
12206                        )
12207                        .redact_private_values
12208                } else {
12209                    false
12210                }
12211            })
12212            .map(|range| {
12213                range.start.to_display_point(display_snapshot)
12214                    ..range.end.to_display_point(display_snapshot)
12215            })
12216            .collect()
12217    }
12218
12219    pub fn highlight_text<T: 'static>(
12220        &mut self,
12221        ranges: Vec<Range<Anchor>>,
12222        style: HighlightStyle,
12223        cx: &mut ViewContext<Self>,
12224    ) {
12225        self.display_map.update(cx, |map, _| {
12226            map.highlight_text(TypeId::of::<T>(), ranges, style)
12227        });
12228        cx.notify();
12229    }
12230
12231    pub(crate) fn highlight_inlays<T: 'static>(
12232        &mut self,
12233        highlights: Vec<InlayHighlight>,
12234        style: HighlightStyle,
12235        cx: &mut ViewContext<Self>,
12236    ) {
12237        self.display_map.update(cx, |map, _| {
12238            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12239        });
12240        cx.notify();
12241    }
12242
12243    pub fn text_highlights<'a, T: 'static>(
12244        &'a self,
12245        cx: &'a AppContext,
12246    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12247        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12248    }
12249
12250    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12251        let cleared = self
12252            .display_map
12253            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12254        if cleared {
12255            cx.notify();
12256        }
12257    }
12258
12259    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12260        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12261            && self.focus_handle.is_focused(cx)
12262    }
12263
12264    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12265        self.show_cursor_when_unfocused = is_enabled;
12266        cx.notify();
12267    }
12268
12269    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12270        self.project
12271            .as_ref()
12272            .map(|project| project.read(cx).lsp_store())
12273    }
12274
12275    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12276        cx.notify();
12277    }
12278
12279    fn on_buffer_event(
12280        &mut self,
12281        multibuffer: Model<MultiBuffer>,
12282        event: &multi_buffer::Event,
12283        cx: &mut ViewContext<Self>,
12284    ) {
12285        match event {
12286            multi_buffer::Event::Edited {
12287                singleton_buffer_edited,
12288                edited_buffer: buffer_edited,
12289            } => {
12290                self.scrollbar_marker_state.dirty = true;
12291                self.active_indent_guides_state.dirty = true;
12292                self.refresh_active_diagnostics(cx);
12293                self.refresh_code_actions(cx);
12294                if self.has_active_inline_completion() {
12295                    self.update_visible_inline_completion(cx);
12296                }
12297                if let Some(buffer) = buffer_edited {
12298                    let buffer_id = buffer.read(cx).remote_id();
12299                    if !self.registered_buffers.contains_key(&buffer_id) {
12300                        if let Some(lsp_store) = self.lsp_store(cx) {
12301                            lsp_store.update(cx, |lsp_store, cx| {
12302                                self.registered_buffers.insert(
12303                                    buffer_id,
12304                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12305                                );
12306                            })
12307                        }
12308                    }
12309                }
12310                cx.emit(EditorEvent::BufferEdited);
12311                cx.emit(SearchEvent::MatchesInvalidated);
12312                if *singleton_buffer_edited {
12313                    if let Some(project) = &self.project {
12314                        let project = project.read(cx);
12315                        #[allow(clippy::mutable_key_type)]
12316                        let languages_affected = multibuffer
12317                            .read(cx)
12318                            .all_buffers()
12319                            .into_iter()
12320                            .filter_map(|buffer| {
12321                                let buffer = buffer.read(cx);
12322                                let language = buffer.language()?;
12323                                if project.is_local()
12324                                    && project
12325                                        .language_servers_for_local_buffer(buffer, cx)
12326                                        .count()
12327                                        == 0
12328                                {
12329                                    None
12330                                } else {
12331                                    Some(language)
12332                                }
12333                            })
12334                            .cloned()
12335                            .collect::<HashSet<_>>();
12336                        if !languages_affected.is_empty() {
12337                            self.refresh_inlay_hints(
12338                                InlayHintRefreshReason::BufferEdited(languages_affected),
12339                                cx,
12340                            );
12341                        }
12342                    }
12343                }
12344
12345                let Some(project) = &self.project else { return };
12346                let (telemetry, is_via_ssh) = {
12347                    let project = project.read(cx);
12348                    let telemetry = project.client().telemetry().clone();
12349                    let is_via_ssh = project.is_via_ssh();
12350                    (telemetry, is_via_ssh)
12351                };
12352                refresh_linked_ranges(self, cx);
12353                telemetry.log_edit_event("editor", is_via_ssh);
12354            }
12355            multi_buffer::Event::ExcerptsAdded {
12356                buffer,
12357                predecessor,
12358                excerpts,
12359            } => {
12360                self.tasks_update_task = Some(self.refresh_runnables(cx));
12361                let buffer_id = buffer.read(cx).remote_id();
12362                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12363                    if let Some(project) = &self.project {
12364                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12365                    }
12366                }
12367                cx.emit(EditorEvent::ExcerptsAdded {
12368                    buffer: buffer.clone(),
12369                    predecessor: *predecessor,
12370                    excerpts: excerpts.clone(),
12371                });
12372                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12373            }
12374            multi_buffer::Event::ExcerptsRemoved { ids } => {
12375                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12376                let buffer = self.buffer.read(cx);
12377                self.registered_buffers
12378                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12379                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12380            }
12381            multi_buffer::Event::ExcerptsEdited { ids } => {
12382                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12383            }
12384            multi_buffer::Event::ExcerptsExpanded { ids } => {
12385                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12386            }
12387            multi_buffer::Event::Reparsed(buffer_id) => {
12388                self.tasks_update_task = Some(self.refresh_runnables(cx));
12389
12390                cx.emit(EditorEvent::Reparsed(*buffer_id));
12391            }
12392            multi_buffer::Event::LanguageChanged(buffer_id) => {
12393                linked_editing_ranges::refresh_linked_ranges(self, cx);
12394                cx.emit(EditorEvent::Reparsed(*buffer_id));
12395                cx.notify();
12396            }
12397            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12398            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12399            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12400                cx.emit(EditorEvent::TitleChanged)
12401            }
12402            // multi_buffer::Event::DiffBaseChanged => {
12403            //     self.scrollbar_marker_state.dirty = true;
12404            //     cx.emit(EditorEvent::DiffBaseChanged);
12405            //     cx.notify();
12406            // }
12407            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12408            multi_buffer::Event::DiagnosticsUpdated => {
12409                self.refresh_active_diagnostics(cx);
12410                self.scrollbar_marker_state.dirty = true;
12411                cx.notify();
12412            }
12413            _ => {}
12414        };
12415    }
12416
12417    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12418        cx.notify();
12419    }
12420
12421    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12422        self.tasks_update_task = Some(self.refresh_runnables(cx));
12423        self.refresh_inline_completion(true, false, cx);
12424        self.refresh_inlay_hints(
12425            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12426                self.selections.newest_anchor().head(),
12427                &self.buffer.read(cx).snapshot(cx),
12428                cx,
12429            )),
12430            cx,
12431        );
12432
12433        let old_cursor_shape = self.cursor_shape;
12434
12435        {
12436            let editor_settings = EditorSettings::get_global(cx);
12437            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12438            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12439            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12440        }
12441
12442        if old_cursor_shape != self.cursor_shape {
12443            cx.emit(EditorEvent::CursorShapeChanged);
12444        }
12445
12446        let project_settings = ProjectSettings::get_global(cx);
12447        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12448
12449        if self.mode == EditorMode::Full {
12450            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12451            if self.git_blame_inline_enabled != inline_blame_enabled {
12452                self.toggle_git_blame_inline_internal(false, cx);
12453            }
12454        }
12455
12456        cx.notify();
12457    }
12458
12459    pub fn set_searchable(&mut self, searchable: bool) {
12460        self.searchable = searchable;
12461    }
12462
12463    pub fn searchable(&self) -> bool {
12464        self.searchable
12465    }
12466
12467    fn open_proposed_changes_editor(
12468        &mut self,
12469        _: &OpenProposedChangesEditor,
12470        cx: &mut ViewContext<Self>,
12471    ) {
12472        let Some(workspace) = self.workspace() else {
12473            cx.propagate();
12474            return;
12475        };
12476
12477        let selections = self.selections.all::<usize>(cx);
12478        let multi_buffer = self.buffer.read(cx);
12479        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12480        let mut new_selections_by_buffer = HashMap::default();
12481        for selection in selections {
12482            for (excerpt, range) in
12483                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12484            {
12485                let mut range = range.to_point(excerpt.buffer());
12486                range.start.column = 0;
12487                range.end.column = excerpt.buffer().line_len(range.end.row);
12488                new_selections_by_buffer
12489                    .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12490                    .or_insert(Vec::new())
12491                    .push(range)
12492            }
12493        }
12494
12495        let proposed_changes_buffers = new_selections_by_buffer
12496            .into_iter()
12497            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12498            .collect::<Vec<_>>();
12499        let proposed_changes_editor = cx.new_view(|cx| {
12500            ProposedChangesEditor::new(
12501                "Proposed changes",
12502                proposed_changes_buffers,
12503                self.project.clone(),
12504                cx,
12505            )
12506        });
12507
12508        cx.window_context().defer(move |cx| {
12509            workspace.update(cx, |workspace, cx| {
12510                workspace.active_pane().update(cx, |pane, cx| {
12511                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12512                });
12513            });
12514        });
12515    }
12516
12517    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12518        self.open_excerpts_common(None, true, cx)
12519    }
12520
12521    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12522        self.open_excerpts_common(None, false, cx)
12523    }
12524
12525    fn open_excerpts_common(
12526        &mut self,
12527        jump_data: Option<JumpData>,
12528        split: bool,
12529        cx: &mut ViewContext<Self>,
12530    ) {
12531        let Some(workspace) = self.workspace() else {
12532            cx.propagate();
12533            return;
12534        };
12535
12536        if self.buffer.read(cx).is_singleton() {
12537            cx.propagate();
12538            return;
12539        }
12540
12541        let mut new_selections_by_buffer = HashMap::default();
12542        match &jump_data {
12543            Some(JumpData::MultiBufferPoint {
12544                excerpt_id,
12545                position,
12546                anchor,
12547                line_offset_from_top,
12548            }) => {
12549                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12550                if let Some(buffer) = multi_buffer_snapshot
12551                    .buffer_id_for_excerpt(*excerpt_id)
12552                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12553                {
12554                    let buffer_snapshot = buffer.read(cx).snapshot();
12555                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12556                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12557                    } else {
12558                        buffer_snapshot.clip_point(*position, Bias::Left)
12559                    };
12560                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12561                    new_selections_by_buffer.insert(
12562                        buffer,
12563                        (
12564                            vec![jump_to_offset..jump_to_offset],
12565                            Some(*line_offset_from_top),
12566                        ),
12567                    );
12568                }
12569            }
12570            Some(JumpData::MultiBufferRow {
12571                row,
12572                line_offset_from_top,
12573            }) => {
12574                let point = MultiBufferPoint::new(row.0, 0);
12575                if let Some((buffer, buffer_point, _)) =
12576                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12577                {
12578                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12579                    new_selections_by_buffer
12580                        .entry(buffer)
12581                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12582                        .0
12583                        .push(buffer_offset..buffer_offset)
12584                }
12585            }
12586            None => {
12587                let selections = self.selections.all::<usize>(cx);
12588                let multi_buffer = self.buffer.read(cx);
12589                for selection in selections {
12590                    for (excerpt, mut range) in multi_buffer
12591                        .snapshot(cx)
12592                        .range_to_buffer_ranges(selection.range())
12593                    {
12594                        // When editing branch buffers, jump to the corresponding location
12595                        // in their base buffer.
12596                        let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12597                        let buffer = buffer_handle.read(cx);
12598                        if let Some(base_buffer) = buffer.base_buffer() {
12599                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12600                            buffer_handle = base_buffer;
12601                        }
12602
12603                        if selection.reversed {
12604                            mem::swap(&mut range.start, &mut range.end);
12605                        }
12606                        new_selections_by_buffer
12607                            .entry(buffer_handle)
12608                            .or_insert((Vec::new(), None))
12609                            .0
12610                            .push(range)
12611                    }
12612                }
12613            }
12614        }
12615
12616        if new_selections_by_buffer.is_empty() {
12617            return;
12618        }
12619
12620        // We defer the pane interaction because we ourselves are a workspace item
12621        // and activating a new item causes the pane to call a method on us reentrantly,
12622        // which panics if we're on the stack.
12623        cx.window_context().defer(move |cx| {
12624            workspace.update(cx, |workspace, cx| {
12625                let pane = if split {
12626                    workspace.adjacent_pane(cx)
12627                } else {
12628                    workspace.active_pane().clone()
12629                };
12630
12631                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12632                    let editor = buffer
12633                        .read(cx)
12634                        .file()
12635                        .is_none()
12636                        .then(|| {
12637                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12638                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12639                            // Instead, we try to activate the existing editor in the pane first.
12640                            let (editor, pane_item_index) =
12641                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12642                                    let editor = item.downcast::<Editor>()?;
12643                                    let singleton_buffer =
12644                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12645                                    if singleton_buffer == buffer {
12646                                        Some((editor, i))
12647                                    } else {
12648                                        None
12649                                    }
12650                                })?;
12651                            pane.update(cx, |pane, cx| {
12652                                pane.activate_item(pane_item_index, true, true, cx)
12653                            });
12654                            Some(editor)
12655                        })
12656                        .flatten()
12657                        .unwrap_or_else(|| {
12658                            workspace.open_project_item::<Self>(
12659                                pane.clone(),
12660                                buffer,
12661                                true,
12662                                true,
12663                                cx,
12664                            )
12665                        });
12666
12667                    editor.update(cx, |editor, cx| {
12668                        let autoscroll = match scroll_offset {
12669                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12670                            None => Autoscroll::newest(),
12671                        };
12672                        let nav_history = editor.nav_history.take();
12673                        editor.change_selections(Some(autoscroll), cx, |s| {
12674                            s.select_ranges(ranges);
12675                        });
12676                        editor.nav_history = nav_history;
12677                    });
12678                }
12679            })
12680        });
12681    }
12682
12683    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12684        let snapshot = self.buffer.read(cx).read(cx);
12685        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12686        Some(
12687            ranges
12688                .iter()
12689                .map(move |range| {
12690                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12691                })
12692                .collect(),
12693        )
12694    }
12695
12696    fn selection_replacement_ranges(
12697        &self,
12698        range: Range<OffsetUtf16>,
12699        cx: &mut AppContext,
12700    ) -> Vec<Range<OffsetUtf16>> {
12701        let selections = self.selections.all::<OffsetUtf16>(cx);
12702        let newest_selection = selections
12703            .iter()
12704            .max_by_key(|selection| selection.id)
12705            .unwrap();
12706        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12707        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12708        let snapshot = self.buffer.read(cx).read(cx);
12709        selections
12710            .into_iter()
12711            .map(|mut selection| {
12712                selection.start.0 =
12713                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12714                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12715                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12716                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12717            })
12718            .collect()
12719    }
12720
12721    fn report_editor_event(
12722        &self,
12723        event_type: &'static str,
12724        file_extension: Option<String>,
12725        cx: &AppContext,
12726    ) {
12727        if cfg!(any(test, feature = "test-support")) {
12728            return;
12729        }
12730
12731        let Some(project) = &self.project else { return };
12732
12733        // If None, we are in a file without an extension
12734        let file = self
12735            .buffer
12736            .read(cx)
12737            .as_singleton()
12738            .and_then(|b| b.read(cx).file());
12739        let file_extension = file_extension.or(file
12740            .as_ref()
12741            .and_then(|file| Path::new(file.file_name(cx)).extension())
12742            .and_then(|e| e.to_str())
12743            .map(|a| a.to_string()));
12744
12745        let vim_mode = cx
12746            .global::<SettingsStore>()
12747            .raw_user_settings()
12748            .get("vim_mode")
12749            == Some(&serde_json::Value::Bool(true));
12750
12751        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12752            == language::language_settings::InlineCompletionProvider::Copilot;
12753        let copilot_enabled_for_language = self
12754            .buffer
12755            .read(cx)
12756            .settings_at(0, cx)
12757            .show_inline_completions;
12758
12759        let project = project.read(cx);
12760        telemetry::event!(
12761            event_type,
12762            file_extension,
12763            vim_mode,
12764            copilot_enabled,
12765            copilot_enabled_for_language,
12766            is_via_ssh = project.is_via_ssh(),
12767        );
12768    }
12769
12770    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12771    /// with each line being an array of {text, highlight} objects.
12772    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12773        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12774            return;
12775        };
12776
12777        #[derive(Serialize)]
12778        struct Chunk<'a> {
12779            text: String,
12780            highlight: Option<&'a str>,
12781        }
12782
12783        let snapshot = buffer.read(cx).snapshot();
12784        let range = self
12785            .selected_text_range(false, cx)
12786            .and_then(|selection| {
12787                if selection.range.is_empty() {
12788                    None
12789                } else {
12790                    Some(selection.range)
12791                }
12792            })
12793            .unwrap_or_else(|| 0..snapshot.len());
12794
12795        let chunks = snapshot.chunks(range, true);
12796        let mut lines = Vec::new();
12797        let mut line: VecDeque<Chunk> = VecDeque::new();
12798
12799        let Some(style) = self.style.as_ref() else {
12800            return;
12801        };
12802
12803        for chunk in chunks {
12804            let highlight = chunk
12805                .syntax_highlight_id
12806                .and_then(|id| id.name(&style.syntax));
12807            let mut chunk_lines = chunk.text.split('\n').peekable();
12808            while let Some(text) = chunk_lines.next() {
12809                let mut merged_with_last_token = false;
12810                if let Some(last_token) = line.back_mut() {
12811                    if last_token.highlight == highlight {
12812                        last_token.text.push_str(text);
12813                        merged_with_last_token = true;
12814                    }
12815                }
12816
12817                if !merged_with_last_token {
12818                    line.push_back(Chunk {
12819                        text: text.into(),
12820                        highlight,
12821                    });
12822                }
12823
12824                if chunk_lines.peek().is_some() {
12825                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12826                        line.pop_front();
12827                    }
12828                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12829                        line.pop_back();
12830                    }
12831
12832                    lines.push(mem::take(&mut line));
12833                }
12834            }
12835        }
12836
12837        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12838            return;
12839        };
12840        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12841    }
12842
12843    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12844        self.request_autoscroll(Autoscroll::newest(), cx);
12845        let position = self.selections.newest_display(cx).start;
12846        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12847    }
12848
12849    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12850        &self.inlay_hint_cache
12851    }
12852
12853    pub fn replay_insert_event(
12854        &mut self,
12855        text: &str,
12856        relative_utf16_range: Option<Range<isize>>,
12857        cx: &mut ViewContext<Self>,
12858    ) {
12859        if !self.input_enabled {
12860            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12861            return;
12862        }
12863        if let Some(relative_utf16_range) = relative_utf16_range {
12864            let selections = self.selections.all::<OffsetUtf16>(cx);
12865            self.change_selections(None, cx, |s| {
12866                let new_ranges = selections.into_iter().map(|range| {
12867                    let start = OffsetUtf16(
12868                        range
12869                            .head()
12870                            .0
12871                            .saturating_add_signed(relative_utf16_range.start),
12872                    );
12873                    let end = OffsetUtf16(
12874                        range
12875                            .head()
12876                            .0
12877                            .saturating_add_signed(relative_utf16_range.end),
12878                    );
12879                    start..end
12880                });
12881                s.select_ranges(new_ranges);
12882            });
12883        }
12884
12885        self.handle_input(text, cx);
12886    }
12887
12888    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12889        let Some(provider) = self.semantics_provider.as_ref() else {
12890            return false;
12891        };
12892
12893        let mut supports = false;
12894        self.buffer().read(cx).for_each_buffer(|buffer| {
12895            supports |= provider.supports_inlay_hints(buffer, cx);
12896        });
12897        supports
12898    }
12899
12900    pub fn focus(&self, cx: &mut WindowContext) {
12901        cx.focus(&self.focus_handle)
12902    }
12903
12904    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12905        self.focus_handle.is_focused(cx)
12906    }
12907
12908    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12909        cx.emit(EditorEvent::Focused);
12910
12911        if let Some(descendant) = self
12912            .last_focused_descendant
12913            .take()
12914            .and_then(|descendant| descendant.upgrade())
12915        {
12916            cx.focus(&descendant);
12917        } else {
12918            if let Some(blame) = self.blame.as_ref() {
12919                blame.update(cx, GitBlame::focus)
12920            }
12921
12922            self.blink_manager.update(cx, BlinkManager::enable);
12923            self.show_cursor_names(cx);
12924            self.buffer.update(cx, |buffer, cx| {
12925                buffer.finalize_last_transaction(cx);
12926                if self.leader_peer_id.is_none() {
12927                    buffer.set_active_selections(
12928                        &self.selections.disjoint_anchors(),
12929                        self.selections.line_mode,
12930                        self.cursor_shape,
12931                        cx,
12932                    );
12933                }
12934            });
12935        }
12936    }
12937
12938    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12939        cx.emit(EditorEvent::FocusedIn)
12940    }
12941
12942    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12943        if event.blurred != self.focus_handle {
12944            self.last_focused_descendant = Some(event.blurred);
12945        }
12946    }
12947
12948    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12949        self.blink_manager.update(cx, BlinkManager::disable);
12950        self.buffer
12951            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12952
12953        if let Some(blame) = self.blame.as_ref() {
12954            blame.update(cx, GitBlame::blur)
12955        }
12956        if !self.hover_state.focused(cx) {
12957            hide_hover(self, cx);
12958        }
12959
12960        self.hide_context_menu(cx);
12961        cx.emit(EditorEvent::Blurred);
12962        cx.notify();
12963    }
12964
12965    pub fn register_action<A: Action>(
12966        &mut self,
12967        listener: impl Fn(&A, &mut WindowContext) + 'static,
12968    ) -> Subscription {
12969        let id = self.next_editor_action_id.post_inc();
12970        let listener = Arc::new(listener);
12971        self.editor_actions.borrow_mut().insert(
12972            id,
12973            Box::new(move |cx| {
12974                let cx = cx.window_context();
12975                let listener = listener.clone();
12976                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12977                    let action = action.downcast_ref().unwrap();
12978                    if phase == DispatchPhase::Bubble {
12979                        listener(action, cx)
12980                    }
12981                })
12982            }),
12983        );
12984
12985        let editor_actions = self.editor_actions.clone();
12986        Subscription::new(move || {
12987            editor_actions.borrow_mut().remove(&id);
12988        })
12989    }
12990
12991    pub fn file_header_size(&self) -> u32 {
12992        FILE_HEADER_HEIGHT
12993    }
12994
12995    pub fn revert(
12996        &mut self,
12997        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12998        cx: &mut ViewContext<Self>,
12999    ) {
13000        self.buffer().update(cx, |multi_buffer, cx| {
13001            for (buffer_id, changes) in revert_changes {
13002                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13003                    buffer.update(cx, |buffer, cx| {
13004                        buffer.edit(
13005                            changes.into_iter().map(|(range, text)| {
13006                                (range, text.to_string().map(Arc::<str>::from))
13007                            }),
13008                            None,
13009                            cx,
13010                        );
13011                    });
13012                }
13013            }
13014        });
13015        self.change_selections(None, cx, |selections| selections.refresh());
13016    }
13017
13018    pub fn to_pixel_point(
13019        &mut self,
13020        source: multi_buffer::Anchor,
13021        editor_snapshot: &EditorSnapshot,
13022        cx: &mut ViewContext<Self>,
13023    ) -> Option<gpui::Point<Pixels>> {
13024        let source_point = source.to_display_point(editor_snapshot);
13025        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13026    }
13027
13028    pub fn display_to_pixel_point(
13029        &self,
13030        source: DisplayPoint,
13031        editor_snapshot: &EditorSnapshot,
13032        cx: &WindowContext,
13033    ) -> Option<gpui::Point<Pixels>> {
13034        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13035        let text_layout_details = self.text_layout_details(cx);
13036        let scroll_top = text_layout_details
13037            .scroll_anchor
13038            .scroll_position(editor_snapshot)
13039            .y;
13040
13041        if source.row().as_f32() < scroll_top.floor() {
13042            return None;
13043        }
13044        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13045        let source_y = line_height * (source.row().as_f32() - scroll_top);
13046        Some(gpui::Point::new(source_x, source_y))
13047    }
13048
13049    pub fn has_active_completions_menu(&self) -> bool {
13050        self.context_menu.borrow().as_ref().map_or(false, |menu| {
13051            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13052        })
13053    }
13054
13055    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13056        self.addons
13057            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13058    }
13059
13060    pub fn unregister_addon<T: Addon>(&mut self) {
13061        self.addons.remove(&std::any::TypeId::of::<T>());
13062    }
13063
13064    pub fn addon<T: Addon>(&self) -> Option<&T> {
13065        let type_id = std::any::TypeId::of::<T>();
13066        self.addons
13067            .get(&type_id)
13068            .and_then(|item| item.to_any().downcast_ref::<T>())
13069    }
13070
13071    pub fn add_change_set(
13072        &mut self,
13073        change_set: Model<BufferChangeSet>,
13074        cx: &mut ViewContext<Self>,
13075    ) {
13076        self.diff_map.add_change_set(change_set, cx);
13077    }
13078
13079    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13080        let text_layout_details = self.text_layout_details(cx);
13081        let style = &text_layout_details.editor_style;
13082        let font_id = cx.text_system().resolve_font(&style.text.font());
13083        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13084        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13085
13086        let em_width = cx
13087            .text_system()
13088            .typographic_bounds(font_id, font_size, 'm')
13089            .unwrap()
13090            .size
13091            .width;
13092
13093        gpui::Point::new(em_width, line_height)
13094    }
13095}
13096
13097fn get_unstaged_changes_for_buffers(
13098    project: &Model<Project>,
13099    buffers: impl IntoIterator<Item = Model<Buffer>>,
13100    cx: &mut ViewContext<Editor>,
13101) {
13102    let mut tasks = Vec::new();
13103    project.update(cx, |project, cx| {
13104        for buffer in buffers {
13105            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13106        }
13107    });
13108    cx.spawn(|this, mut cx| async move {
13109        let change_sets = futures::future::join_all(tasks).await;
13110        this.update(&mut cx, |this, cx| {
13111            for change_set in change_sets {
13112                if let Some(change_set) = change_set.log_err() {
13113                    this.diff_map.add_change_set(change_set, cx);
13114                }
13115            }
13116        })
13117        .ok();
13118    })
13119    .detach();
13120}
13121
13122fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13123    let tab_size = tab_size.get() as usize;
13124    let mut width = offset;
13125
13126    for ch in text.chars() {
13127        width += if ch == '\t' {
13128            tab_size - (width % tab_size)
13129        } else {
13130            1
13131        };
13132    }
13133
13134    width - offset
13135}
13136
13137#[cfg(test)]
13138mod tests {
13139    use super::*;
13140
13141    #[test]
13142    fn test_string_size_with_expanded_tabs() {
13143        let nz = |val| NonZeroU32::new(val).unwrap();
13144        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13145        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13146        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13147        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13148        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13149        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13150        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13151        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13152    }
13153}
13154
13155/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13156struct WordBreakingTokenizer<'a> {
13157    input: &'a str,
13158}
13159
13160impl<'a> WordBreakingTokenizer<'a> {
13161    fn new(input: &'a str) -> Self {
13162        Self { input }
13163    }
13164}
13165
13166fn is_char_ideographic(ch: char) -> bool {
13167    use unicode_script::Script::*;
13168    use unicode_script::UnicodeScript;
13169    matches!(ch.script(), Han | Tangut | Yi)
13170}
13171
13172fn is_grapheme_ideographic(text: &str) -> bool {
13173    text.chars().any(is_char_ideographic)
13174}
13175
13176fn is_grapheme_whitespace(text: &str) -> bool {
13177    text.chars().any(|x| x.is_whitespace())
13178}
13179
13180fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13181    text.chars().next().map_or(false, |ch| {
13182        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13183    })
13184}
13185
13186#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13187struct WordBreakToken<'a> {
13188    token: &'a str,
13189    grapheme_len: usize,
13190    is_whitespace: bool,
13191}
13192
13193impl<'a> Iterator for WordBreakingTokenizer<'a> {
13194    /// Yields a span, the count of graphemes in the token, and whether it was
13195    /// whitespace. Note that it also breaks at word boundaries.
13196    type Item = WordBreakToken<'a>;
13197
13198    fn next(&mut self) -> Option<Self::Item> {
13199        use unicode_segmentation::UnicodeSegmentation;
13200        if self.input.is_empty() {
13201            return None;
13202        }
13203
13204        let mut iter = self.input.graphemes(true).peekable();
13205        let mut offset = 0;
13206        let mut graphemes = 0;
13207        if let Some(first_grapheme) = iter.next() {
13208            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13209            offset += first_grapheme.len();
13210            graphemes += 1;
13211            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13212                if let Some(grapheme) = iter.peek().copied() {
13213                    if should_stay_with_preceding_ideograph(grapheme) {
13214                        offset += grapheme.len();
13215                        graphemes += 1;
13216                    }
13217                }
13218            } else {
13219                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13220                let mut next_word_bound = words.peek().copied();
13221                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13222                    next_word_bound = words.next();
13223                }
13224                while let Some(grapheme) = iter.peek().copied() {
13225                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13226                        break;
13227                    };
13228                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13229                        break;
13230                    };
13231                    offset += grapheme.len();
13232                    graphemes += 1;
13233                    iter.next();
13234                }
13235            }
13236            let token = &self.input[..offset];
13237            self.input = &self.input[offset..];
13238            if is_whitespace {
13239                Some(WordBreakToken {
13240                    token: " ",
13241                    grapheme_len: 1,
13242                    is_whitespace: true,
13243                })
13244            } else {
13245                Some(WordBreakToken {
13246                    token,
13247                    grapheme_len: graphemes,
13248                    is_whitespace: false,
13249                })
13250            }
13251        } else {
13252            None
13253        }
13254    }
13255}
13256
13257#[test]
13258fn test_word_breaking_tokenizer() {
13259    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13260        ("", &[]),
13261        ("  ", &[(" ", 1, true)]),
13262        ("Ʒ", &[("Ʒ", 1, false)]),
13263        ("Ǽ", &[("Ǽ", 1, false)]),
13264        ("", &[("", 1, false)]),
13265        ("⋑⋑", &[("⋑⋑", 2, false)]),
13266        (
13267            "原理,进而",
13268            &[
13269                ("", 1, false),
13270                ("理,", 2, false),
13271                ("", 1, false),
13272                ("", 1, false),
13273            ],
13274        ),
13275        (
13276            "hello world",
13277            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13278        ),
13279        (
13280            "hello, world",
13281            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13282        ),
13283        (
13284            "  hello world",
13285            &[
13286                (" ", 1, true),
13287                ("hello", 5, false),
13288                (" ", 1, true),
13289                ("world", 5, false),
13290            ],
13291        ),
13292        (
13293            "这是什么 \n 钢笔",
13294            &[
13295                ("", 1, false),
13296                ("", 1, false),
13297                ("", 1, false),
13298                ("", 1, false),
13299                (" ", 1, true),
13300                ("", 1, false),
13301                ("", 1, false),
13302            ],
13303        ),
13304        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13305    ];
13306
13307    for (input, result) in tests {
13308        assert_eq!(
13309            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13310            result
13311                .iter()
13312                .copied()
13313                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13314                    token,
13315                    grapheme_len,
13316                    is_whitespace,
13317                })
13318                .collect::<Vec<_>>()
13319        );
13320    }
13321}
13322
13323fn wrap_with_prefix(
13324    line_prefix: String,
13325    unwrapped_text: String,
13326    wrap_column: usize,
13327    tab_size: NonZeroU32,
13328) -> String {
13329    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13330    let mut wrapped_text = String::new();
13331    let mut current_line = line_prefix.clone();
13332
13333    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13334    let mut current_line_len = line_prefix_len;
13335    for WordBreakToken {
13336        token,
13337        grapheme_len,
13338        is_whitespace,
13339    } in tokenizer
13340    {
13341        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13342            wrapped_text.push_str(current_line.trim_end());
13343            wrapped_text.push('\n');
13344            current_line.truncate(line_prefix.len());
13345            current_line_len = line_prefix_len;
13346            if !is_whitespace {
13347                current_line.push_str(token);
13348                current_line_len += grapheme_len;
13349            }
13350        } else if !is_whitespace {
13351            current_line.push_str(token);
13352            current_line_len += grapheme_len;
13353        } else if current_line_len != line_prefix_len {
13354            current_line.push(' ');
13355            current_line_len += 1;
13356        }
13357    }
13358
13359    if !current_line.is_empty() {
13360        wrapped_text.push_str(&current_line);
13361    }
13362    wrapped_text
13363}
13364
13365#[test]
13366fn test_wrap_with_prefix() {
13367    assert_eq!(
13368        wrap_with_prefix(
13369            "# ".to_string(),
13370            "abcdefg".to_string(),
13371            4,
13372            NonZeroU32::new(4).unwrap()
13373        ),
13374        "# abcdefg"
13375    );
13376    assert_eq!(
13377        wrap_with_prefix(
13378            "".to_string(),
13379            "\thello world".to_string(),
13380            8,
13381            NonZeroU32::new(4).unwrap()
13382        ),
13383        "hello\nworld"
13384    );
13385    assert_eq!(
13386        wrap_with_prefix(
13387            "// ".to_string(),
13388            "xx \nyy zz aa bb cc".to_string(),
13389            12,
13390            NonZeroU32::new(4).unwrap()
13391        ),
13392        "// xx yy zz\n// aa bb cc"
13393    );
13394    assert_eq!(
13395        wrap_with_prefix(
13396            String::new(),
13397            "这是什么 \n 钢笔".to_string(),
13398            3,
13399            NonZeroU32::new(4).unwrap()
13400        ),
13401        "这是什\n么 钢\n"
13402    );
13403}
13404
13405fn hunks_for_selections(
13406    snapshot: &EditorSnapshot,
13407    selections: &[Selection<Point>],
13408) -> Vec<MultiBufferDiffHunk> {
13409    hunks_for_ranges(
13410        selections.iter().map(|selection| selection.range()),
13411        snapshot,
13412    )
13413}
13414
13415pub fn hunks_for_ranges(
13416    ranges: impl Iterator<Item = Range<Point>>,
13417    snapshot: &EditorSnapshot,
13418) -> Vec<MultiBufferDiffHunk> {
13419    let mut hunks = Vec::new();
13420    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13421        HashMap::default();
13422    for query_range in ranges {
13423        let query_rows =
13424            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13425        for hunk in snapshot.diff_map.diff_hunks_in_range(
13426            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13427            &snapshot.buffer_snapshot,
13428        ) {
13429            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13430            // when the caret is just above or just below the deleted hunk.
13431            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13432            let related_to_selection = if allow_adjacent {
13433                hunk.row_range.overlaps(&query_rows)
13434                    || hunk.row_range.start == query_rows.end
13435                    || hunk.row_range.end == query_rows.start
13436            } else {
13437                hunk.row_range.overlaps(&query_rows)
13438            };
13439            if related_to_selection {
13440                if !processed_buffer_rows
13441                    .entry(hunk.buffer_id)
13442                    .or_default()
13443                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13444                {
13445                    continue;
13446                }
13447                hunks.push(hunk);
13448            }
13449        }
13450    }
13451
13452    hunks
13453}
13454
13455pub trait CollaborationHub {
13456    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13457    fn user_participant_indices<'a>(
13458        &self,
13459        cx: &'a AppContext,
13460    ) -> &'a HashMap<u64, ParticipantIndex>;
13461    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13462}
13463
13464impl CollaborationHub for Model<Project> {
13465    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13466        self.read(cx).collaborators()
13467    }
13468
13469    fn user_participant_indices<'a>(
13470        &self,
13471        cx: &'a AppContext,
13472    ) -> &'a HashMap<u64, ParticipantIndex> {
13473        self.read(cx).user_store().read(cx).participant_indices()
13474    }
13475
13476    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13477        let this = self.read(cx);
13478        let user_ids = this.collaborators().values().map(|c| c.user_id);
13479        this.user_store().read_with(cx, |user_store, cx| {
13480            user_store.participant_names(user_ids, cx)
13481        })
13482    }
13483}
13484
13485pub trait SemanticsProvider {
13486    fn hover(
13487        &self,
13488        buffer: &Model<Buffer>,
13489        position: text::Anchor,
13490        cx: &mut AppContext,
13491    ) -> Option<Task<Vec<project::Hover>>>;
13492
13493    fn inlay_hints(
13494        &self,
13495        buffer_handle: Model<Buffer>,
13496        range: Range<text::Anchor>,
13497        cx: &mut AppContext,
13498    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13499
13500    fn resolve_inlay_hint(
13501        &self,
13502        hint: InlayHint,
13503        buffer_handle: Model<Buffer>,
13504        server_id: LanguageServerId,
13505        cx: &mut AppContext,
13506    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13507
13508    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13509
13510    fn document_highlights(
13511        &self,
13512        buffer: &Model<Buffer>,
13513        position: text::Anchor,
13514        cx: &mut AppContext,
13515    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13516
13517    fn definitions(
13518        &self,
13519        buffer: &Model<Buffer>,
13520        position: text::Anchor,
13521        kind: GotoDefinitionKind,
13522        cx: &mut AppContext,
13523    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13524
13525    fn range_for_rename(
13526        &self,
13527        buffer: &Model<Buffer>,
13528        position: text::Anchor,
13529        cx: &mut AppContext,
13530    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13531
13532    fn perform_rename(
13533        &self,
13534        buffer: &Model<Buffer>,
13535        position: text::Anchor,
13536        new_name: String,
13537        cx: &mut AppContext,
13538    ) -> Option<Task<Result<ProjectTransaction>>>;
13539}
13540
13541pub trait CompletionProvider {
13542    fn completions(
13543        &self,
13544        buffer: &Model<Buffer>,
13545        buffer_position: text::Anchor,
13546        trigger: CompletionContext,
13547        cx: &mut ViewContext<Editor>,
13548    ) -> Task<Result<Vec<Completion>>>;
13549
13550    fn resolve_completions(
13551        &self,
13552        buffer: Model<Buffer>,
13553        completion_indices: Vec<usize>,
13554        completions: Rc<RefCell<Box<[Completion]>>>,
13555        cx: &mut ViewContext<Editor>,
13556    ) -> Task<Result<bool>>;
13557
13558    fn apply_additional_edits_for_completion(
13559        &self,
13560        _buffer: Model<Buffer>,
13561        _completions: Rc<RefCell<Box<[Completion]>>>,
13562        _completion_index: usize,
13563        _push_to_history: bool,
13564        _cx: &mut ViewContext<Editor>,
13565    ) -> Task<Result<Option<language::Transaction>>> {
13566        Task::ready(Ok(None))
13567    }
13568
13569    fn is_completion_trigger(
13570        &self,
13571        buffer: &Model<Buffer>,
13572        position: language::Anchor,
13573        text: &str,
13574        trigger_in_words: bool,
13575        cx: &mut ViewContext<Editor>,
13576    ) -> bool;
13577
13578    fn sort_completions(&self) -> bool {
13579        true
13580    }
13581}
13582
13583pub trait CodeActionProvider {
13584    fn code_actions(
13585        &self,
13586        buffer: &Model<Buffer>,
13587        range: Range<text::Anchor>,
13588        cx: &mut WindowContext,
13589    ) -> Task<Result<Vec<CodeAction>>>;
13590
13591    fn apply_code_action(
13592        &self,
13593        buffer_handle: Model<Buffer>,
13594        action: CodeAction,
13595        excerpt_id: ExcerptId,
13596        push_to_history: bool,
13597        cx: &mut WindowContext,
13598    ) -> Task<Result<ProjectTransaction>>;
13599}
13600
13601impl CodeActionProvider for Model<Project> {
13602    fn code_actions(
13603        &self,
13604        buffer: &Model<Buffer>,
13605        range: Range<text::Anchor>,
13606        cx: &mut WindowContext,
13607    ) -> Task<Result<Vec<CodeAction>>> {
13608        self.update(cx, |project, cx| {
13609            project.code_actions(buffer, range, None, cx)
13610        })
13611    }
13612
13613    fn apply_code_action(
13614        &self,
13615        buffer_handle: Model<Buffer>,
13616        action: CodeAction,
13617        _excerpt_id: ExcerptId,
13618        push_to_history: bool,
13619        cx: &mut WindowContext,
13620    ) -> Task<Result<ProjectTransaction>> {
13621        self.update(cx, |project, cx| {
13622            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13623        })
13624    }
13625}
13626
13627fn snippet_completions(
13628    project: &Project,
13629    buffer: &Model<Buffer>,
13630    buffer_position: text::Anchor,
13631    cx: &mut AppContext,
13632) -> Task<Result<Vec<Completion>>> {
13633    let language = buffer.read(cx).language_at(buffer_position);
13634    let language_name = language.as_ref().map(|language| language.lsp_id());
13635    let snippet_store = project.snippets().read(cx);
13636    let snippets = snippet_store.snippets_for(language_name, cx);
13637
13638    if snippets.is_empty() {
13639        return Task::ready(Ok(vec![]));
13640    }
13641    let snapshot = buffer.read(cx).text_snapshot();
13642    let chars: String = snapshot
13643        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13644        .collect();
13645
13646    let scope = language.map(|language| language.default_scope());
13647    let executor = cx.background_executor().clone();
13648
13649    cx.background_executor().spawn(async move {
13650        let classifier = CharClassifier::new(scope).for_completion(true);
13651        let mut last_word = chars
13652            .chars()
13653            .take_while(|c| classifier.is_word(*c))
13654            .collect::<String>();
13655        last_word = last_word.chars().rev().collect();
13656
13657        if last_word.is_empty() {
13658            return Ok(vec![]);
13659        }
13660
13661        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13662        let to_lsp = |point: &text::Anchor| {
13663            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13664            point_to_lsp(end)
13665        };
13666        let lsp_end = to_lsp(&buffer_position);
13667
13668        let candidates = snippets
13669            .iter()
13670            .enumerate()
13671            .flat_map(|(ix, snippet)| {
13672                snippet
13673                    .prefix
13674                    .iter()
13675                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13676            })
13677            .collect::<Vec<StringMatchCandidate>>();
13678
13679        let mut matches = fuzzy::match_strings(
13680            &candidates,
13681            &last_word,
13682            last_word.chars().any(|c| c.is_uppercase()),
13683            100,
13684            &Default::default(),
13685            executor,
13686        )
13687        .await;
13688
13689        // Remove all candidates where the query's start does not match the start of any word in the candidate
13690        if let Some(query_start) = last_word.chars().next() {
13691            matches.retain(|string_match| {
13692                split_words(&string_match.string).any(|word| {
13693                    // Check that the first codepoint of the word as lowercase matches the first
13694                    // codepoint of the query as lowercase
13695                    word.chars()
13696                        .flat_map(|codepoint| codepoint.to_lowercase())
13697                        .zip(query_start.to_lowercase())
13698                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13699                })
13700            });
13701        }
13702
13703        let matched_strings = matches
13704            .into_iter()
13705            .map(|m| m.string)
13706            .collect::<HashSet<_>>();
13707
13708        let result: Vec<Completion> = snippets
13709            .into_iter()
13710            .filter_map(|snippet| {
13711                let matching_prefix = snippet
13712                    .prefix
13713                    .iter()
13714                    .find(|prefix| matched_strings.contains(*prefix))?;
13715                let start = as_offset - last_word.len();
13716                let start = snapshot.anchor_before(start);
13717                let range = start..buffer_position;
13718                let lsp_start = to_lsp(&start);
13719                let lsp_range = lsp::Range {
13720                    start: lsp_start,
13721                    end: lsp_end,
13722                };
13723                Some(Completion {
13724                    old_range: range,
13725                    new_text: snippet.body.clone(),
13726                    resolved: false,
13727                    label: CodeLabel {
13728                        text: matching_prefix.clone(),
13729                        runs: vec![],
13730                        filter_range: 0..matching_prefix.len(),
13731                    },
13732                    server_id: LanguageServerId(usize::MAX),
13733                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13734                    lsp_completion: lsp::CompletionItem {
13735                        label: snippet.prefix.first().unwrap().clone(),
13736                        kind: Some(CompletionItemKind::SNIPPET),
13737                        label_details: snippet.description.as_ref().map(|description| {
13738                            lsp::CompletionItemLabelDetails {
13739                                detail: Some(description.clone()),
13740                                description: None,
13741                            }
13742                        }),
13743                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13744                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13745                            lsp::InsertReplaceEdit {
13746                                new_text: snippet.body.clone(),
13747                                insert: lsp_range,
13748                                replace: lsp_range,
13749                            },
13750                        )),
13751                        filter_text: Some(snippet.body.clone()),
13752                        sort_text: Some(char::MAX.to_string()),
13753                        ..Default::default()
13754                    },
13755                    confirm: None,
13756                })
13757            })
13758            .collect();
13759
13760        Ok(result)
13761    })
13762}
13763
13764impl CompletionProvider for Model<Project> {
13765    fn completions(
13766        &self,
13767        buffer: &Model<Buffer>,
13768        buffer_position: text::Anchor,
13769        options: CompletionContext,
13770        cx: &mut ViewContext<Editor>,
13771    ) -> Task<Result<Vec<Completion>>> {
13772        self.update(cx, |project, cx| {
13773            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13774            let project_completions = project.completions(buffer, buffer_position, options, cx);
13775            cx.background_executor().spawn(async move {
13776                let mut completions = project_completions.await?;
13777                let snippets_completions = snippets.await?;
13778                completions.extend(snippets_completions);
13779                Ok(completions)
13780            })
13781        })
13782    }
13783
13784    fn resolve_completions(
13785        &self,
13786        buffer: Model<Buffer>,
13787        completion_indices: Vec<usize>,
13788        completions: Rc<RefCell<Box<[Completion]>>>,
13789        cx: &mut ViewContext<Editor>,
13790    ) -> Task<Result<bool>> {
13791        self.update(cx, |project, cx| {
13792            project.lsp_store().update(cx, |lsp_store, cx| {
13793                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13794            })
13795        })
13796    }
13797
13798    fn apply_additional_edits_for_completion(
13799        &self,
13800        buffer: Model<Buffer>,
13801        completions: Rc<RefCell<Box<[Completion]>>>,
13802        completion_index: usize,
13803        push_to_history: bool,
13804        cx: &mut ViewContext<Editor>,
13805    ) -> Task<Result<Option<language::Transaction>>> {
13806        self.update(cx, |project, cx| {
13807            project.lsp_store().update(cx, |lsp_store, cx| {
13808                lsp_store.apply_additional_edits_for_completion(
13809                    buffer,
13810                    completions,
13811                    completion_index,
13812                    push_to_history,
13813                    cx,
13814                )
13815            })
13816        })
13817    }
13818
13819    fn is_completion_trigger(
13820        &self,
13821        buffer: &Model<Buffer>,
13822        position: language::Anchor,
13823        text: &str,
13824        trigger_in_words: bool,
13825        cx: &mut ViewContext<Editor>,
13826    ) -> bool {
13827        let mut chars = text.chars();
13828        let char = if let Some(char) = chars.next() {
13829            char
13830        } else {
13831            return false;
13832        };
13833        if chars.next().is_some() {
13834            return false;
13835        }
13836
13837        let buffer = buffer.read(cx);
13838        let snapshot = buffer.snapshot();
13839        if !snapshot.settings_at(position, cx).show_completions_on_input {
13840            return false;
13841        }
13842        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13843        if trigger_in_words && classifier.is_word(char) {
13844            return true;
13845        }
13846
13847        buffer.completion_triggers().contains(text)
13848    }
13849}
13850
13851impl SemanticsProvider for Model<Project> {
13852    fn hover(
13853        &self,
13854        buffer: &Model<Buffer>,
13855        position: text::Anchor,
13856        cx: &mut AppContext,
13857    ) -> Option<Task<Vec<project::Hover>>> {
13858        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13859    }
13860
13861    fn document_highlights(
13862        &self,
13863        buffer: &Model<Buffer>,
13864        position: text::Anchor,
13865        cx: &mut AppContext,
13866    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13867        Some(self.update(cx, |project, cx| {
13868            project.document_highlights(buffer, position, cx)
13869        }))
13870    }
13871
13872    fn definitions(
13873        &self,
13874        buffer: &Model<Buffer>,
13875        position: text::Anchor,
13876        kind: GotoDefinitionKind,
13877        cx: &mut AppContext,
13878    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13879        Some(self.update(cx, |project, cx| match kind {
13880            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13881            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13882            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13883            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13884        }))
13885    }
13886
13887    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13888        // TODO: make this work for remote projects
13889        self.read(cx)
13890            .language_servers_for_local_buffer(buffer.read(cx), cx)
13891            .any(
13892                |(_, server)| match server.capabilities().inlay_hint_provider {
13893                    Some(lsp::OneOf::Left(enabled)) => enabled,
13894                    Some(lsp::OneOf::Right(_)) => true,
13895                    None => false,
13896                },
13897            )
13898    }
13899
13900    fn inlay_hints(
13901        &self,
13902        buffer_handle: Model<Buffer>,
13903        range: Range<text::Anchor>,
13904        cx: &mut AppContext,
13905    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13906        Some(self.update(cx, |project, cx| {
13907            project.inlay_hints(buffer_handle, range, cx)
13908        }))
13909    }
13910
13911    fn resolve_inlay_hint(
13912        &self,
13913        hint: InlayHint,
13914        buffer_handle: Model<Buffer>,
13915        server_id: LanguageServerId,
13916        cx: &mut AppContext,
13917    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13918        Some(self.update(cx, |project, cx| {
13919            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13920        }))
13921    }
13922
13923    fn range_for_rename(
13924        &self,
13925        buffer: &Model<Buffer>,
13926        position: text::Anchor,
13927        cx: &mut AppContext,
13928    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13929        Some(self.update(cx, |project, cx| {
13930            project.prepare_rename(buffer.clone(), position, cx)
13931        }))
13932    }
13933
13934    fn perform_rename(
13935        &self,
13936        buffer: &Model<Buffer>,
13937        position: text::Anchor,
13938        new_name: String,
13939        cx: &mut AppContext,
13940    ) -> Option<Task<Result<ProjectTransaction>>> {
13941        Some(self.update(cx, |project, cx| {
13942            project.perform_rename(buffer.clone(), position, new_name, cx)
13943        }))
13944    }
13945}
13946
13947fn inlay_hint_settings(
13948    location: Anchor,
13949    snapshot: &MultiBufferSnapshot,
13950    cx: &mut ViewContext<Editor>,
13951) -> InlayHintSettings {
13952    let file = snapshot.file_at(location);
13953    let language = snapshot.language_at(location).map(|l| l.name());
13954    language_settings(language, file, cx).inlay_hints
13955}
13956
13957fn consume_contiguous_rows(
13958    contiguous_row_selections: &mut Vec<Selection<Point>>,
13959    selection: &Selection<Point>,
13960    display_map: &DisplaySnapshot,
13961    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13962) -> (MultiBufferRow, MultiBufferRow) {
13963    contiguous_row_selections.push(selection.clone());
13964    let start_row = MultiBufferRow(selection.start.row);
13965    let mut end_row = ending_row(selection, display_map);
13966
13967    while let Some(next_selection) = selections.peek() {
13968        if next_selection.start.row <= end_row.0 {
13969            end_row = ending_row(next_selection, display_map);
13970            contiguous_row_selections.push(selections.next().unwrap().clone());
13971        } else {
13972            break;
13973        }
13974    }
13975    (start_row, end_row)
13976}
13977
13978fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13979    if next_selection.end.column > 0 || next_selection.is_empty() {
13980        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13981    } else {
13982        MultiBufferRow(next_selection.end.row)
13983    }
13984}
13985
13986impl EditorSnapshot {
13987    pub fn remote_selections_in_range<'a>(
13988        &'a self,
13989        range: &'a Range<Anchor>,
13990        collaboration_hub: &dyn CollaborationHub,
13991        cx: &'a AppContext,
13992    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13993        let participant_names = collaboration_hub.user_names(cx);
13994        let participant_indices = collaboration_hub.user_participant_indices(cx);
13995        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13996        let collaborators_by_replica_id = collaborators_by_peer_id
13997            .iter()
13998            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13999            .collect::<HashMap<_, _>>();
14000        self.buffer_snapshot
14001            .selections_in_range(range, false)
14002            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14003                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14004                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14005                let user_name = participant_names.get(&collaborator.user_id).cloned();
14006                Some(RemoteSelection {
14007                    replica_id,
14008                    selection,
14009                    cursor_shape,
14010                    line_mode,
14011                    participant_index,
14012                    peer_id: collaborator.peer_id,
14013                    user_name,
14014                })
14015            })
14016    }
14017
14018    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14019        self.display_snapshot.buffer_snapshot.language_at(position)
14020    }
14021
14022    pub fn is_focused(&self) -> bool {
14023        self.is_focused
14024    }
14025
14026    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14027        self.placeholder_text.as_ref()
14028    }
14029
14030    pub fn scroll_position(&self) -> gpui::Point<f32> {
14031        self.scroll_anchor.scroll_position(&self.display_snapshot)
14032    }
14033
14034    fn gutter_dimensions(
14035        &self,
14036        font_id: FontId,
14037        font_size: Pixels,
14038        em_width: Pixels,
14039        em_advance: Pixels,
14040        max_line_number_width: Pixels,
14041        cx: &AppContext,
14042    ) -> GutterDimensions {
14043        if !self.show_gutter {
14044            return GutterDimensions::default();
14045        }
14046        let descent = cx.text_system().descent(font_id, font_size);
14047
14048        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14049            matches!(
14050                ProjectSettings::get_global(cx).git.git_gutter,
14051                Some(GitGutterSetting::TrackedFiles)
14052            )
14053        });
14054        let gutter_settings = EditorSettings::get_global(cx).gutter;
14055        let show_line_numbers = self
14056            .show_line_numbers
14057            .unwrap_or(gutter_settings.line_numbers);
14058        let line_gutter_width = if show_line_numbers {
14059            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14060            let min_width_for_number_on_gutter = em_advance * 4.0;
14061            max_line_number_width.max(min_width_for_number_on_gutter)
14062        } else {
14063            0.0.into()
14064        };
14065
14066        let show_code_actions = self
14067            .show_code_actions
14068            .unwrap_or(gutter_settings.code_actions);
14069
14070        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14071
14072        let git_blame_entries_width =
14073            self.git_blame_gutter_max_author_length
14074                .map(|max_author_length| {
14075                    // Length of the author name, but also space for the commit hash,
14076                    // the spacing and the timestamp.
14077                    let max_char_count = max_author_length
14078                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14079                        + 7 // length of commit sha
14080                        + 14 // length of max relative timestamp ("60 minutes ago")
14081                        + 4; // gaps and margins
14082
14083                    em_advance * max_char_count
14084                });
14085
14086        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14087        left_padding += if show_code_actions || show_runnables {
14088            em_width * 3.0
14089        } else if show_git_gutter && show_line_numbers {
14090            em_width * 2.0
14091        } else if show_git_gutter || show_line_numbers {
14092            em_width
14093        } else {
14094            px(0.)
14095        };
14096
14097        let right_padding = if gutter_settings.folds && show_line_numbers {
14098            em_width * 4.0
14099        } else if gutter_settings.folds {
14100            em_width * 3.0
14101        } else if show_line_numbers {
14102            em_width
14103        } else {
14104            px(0.)
14105        };
14106
14107        GutterDimensions {
14108            left_padding,
14109            right_padding,
14110            width: line_gutter_width + left_padding + right_padding,
14111            margin: -descent,
14112            git_blame_entries_width,
14113        }
14114    }
14115
14116    pub fn render_crease_toggle(
14117        &self,
14118        buffer_row: MultiBufferRow,
14119        row_contains_cursor: bool,
14120        editor: View<Editor>,
14121        cx: &mut WindowContext,
14122    ) -> Option<AnyElement> {
14123        let folded = self.is_line_folded(buffer_row);
14124        let mut is_foldable = false;
14125
14126        if let Some(crease) = self
14127            .crease_snapshot
14128            .query_row(buffer_row, &self.buffer_snapshot)
14129        {
14130            is_foldable = true;
14131            match crease {
14132                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14133                    if let Some(render_toggle) = render_toggle {
14134                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14135                            if folded {
14136                                editor.update(cx, |editor, cx| {
14137                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14138                                });
14139                            } else {
14140                                editor.update(cx, |editor, cx| {
14141                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14142                                });
14143                            }
14144                        });
14145                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14146                    }
14147                }
14148            }
14149        }
14150
14151        is_foldable |= self.starts_indent(buffer_row);
14152
14153        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14154            Some(
14155                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14156                    .toggle_state(folded)
14157                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14158                        if folded {
14159                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14160                        } else {
14161                            this.fold_at(&FoldAt { buffer_row }, cx);
14162                        }
14163                    }))
14164                    .into_any_element(),
14165            )
14166        } else {
14167            None
14168        }
14169    }
14170
14171    pub fn render_crease_trailer(
14172        &self,
14173        buffer_row: MultiBufferRow,
14174        cx: &mut WindowContext,
14175    ) -> Option<AnyElement> {
14176        let folded = self.is_line_folded(buffer_row);
14177        if let Crease::Inline { render_trailer, .. } = self
14178            .crease_snapshot
14179            .query_row(buffer_row, &self.buffer_snapshot)?
14180        {
14181            let render_trailer = render_trailer.as_ref()?;
14182            Some(render_trailer(buffer_row, folded, cx))
14183        } else {
14184            None
14185        }
14186    }
14187}
14188
14189impl Deref for EditorSnapshot {
14190    type Target = DisplaySnapshot;
14191
14192    fn deref(&self) -> &Self::Target {
14193        &self.display_snapshot
14194    }
14195}
14196
14197#[derive(Clone, Debug, PartialEq, Eq)]
14198pub enum EditorEvent {
14199    InputIgnored {
14200        text: Arc<str>,
14201    },
14202    InputHandled {
14203        utf16_range_to_replace: Option<Range<isize>>,
14204        text: Arc<str>,
14205    },
14206    ExcerptsAdded {
14207        buffer: Model<Buffer>,
14208        predecessor: ExcerptId,
14209        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14210    },
14211    ExcerptsRemoved {
14212        ids: Vec<ExcerptId>,
14213    },
14214    BufferFoldToggled {
14215        ids: Vec<ExcerptId>,
14216        folded: bool,
14217    },
14218    ExcerptsEdited {
14219        ids: Vec<ExcerptId>,
14220    },
14221    ExcerptsExpanded {
14222        ids: Vec<ExcerptId>,
14223    },
14224    BufferEdited,
14225    Edited {
14226        transaction_id: clock::Lamport,
14227    },
14228    Reparsed(BufferId),
14229    Focused,
14230    FocusedIn,
14231    Blurred,
14232    DirtyChanged,
14233    Saved,
14234    TitleChanged,
14235    DiffBaseChanged,
14236    SelectionsChanged {
14237        local: bool,
14238    },
14239    ScrollPositionChanged {
14240        local: bool,
14241        autoscroll: bool,
14242    },
14243    Closed,
14244    TransactionUndone {
14245        transaction_id: clock::Lamport,
14246    },
14247    TransactionBegun {
14248        transaction_id: clock::Lamport,
14249    },
14250    Reloaded,
14251    CursorShapeChanged,
14252}
14253
14254impl EventEmitter<EditorEvent> for Editor {}
14255
14256impl FocusableView for Editor {
14257    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14258        self.focus_handle.clone()
14259    }
14260}
14261
14262impl Render for Editor {
14263    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14264        let settings = ThemeSettings::get_global(cx);
14265
14266        let mut text_style = match self.mode {
14267            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14268                color: cx.theme().colors().editor_foreground,
14269                font_family: settings.ui_font.family.clone(),
14270                font_features: settings.ui_font.features.clone(),
14271                font_fallbacks: settings.ui_font.fallbacks.clone(),
14272                font_size: rems(0.875).into(),
14273                font_weight: settings.ui_font.weight,
14274                line_height: relative(settings.buffer_line_height.value()),
14275                ..Default::default()
14276            },
14277            EditorMode::Full => TextStyle {
14278                color: cx.theme().colors().editor_foreground,
14279                font_family: settings.buffer_font.family.clone(),
14280                font_features: settings.buffer_font.features.clone(),
14281                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14282                font_size: settings.buffer_font_size(cx).into(),
14283                font_weight: settings.buffer_font.weight,
14284                line_height: relative(settings.buffer_line_height.value()),
14285                ..Default::default()
14286            },
14287        };
14288        if let Some(text_style_refinement) = &self.text_style_refinement {
14289            text_style.refine(text_style_refinement)
14290        }
14291
14292        let background = match self.mode {
14293            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14294            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14295            EditorMode::Full => cx.theme().colors().editor_background,
14296        };
14297
14298        EditorElement::new(
14299            cx.view(),
14300            EditorStyle {
14301                background,
14302                local_player: cx.theme().players().local(),
14303                text: text_style,
14304                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14305                syntax: cx.theme().syntax().clone(),
14306                status: cx.theme().status().clone(),
14307                inlay_hints_style: make_inlay_hints_style(cx),
14308                inline_completion_styles: make_suggestion_styles(cx),
14309                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14310            },
14311        )
14312    }
14313}
14314
14315impl ViewInputHandler for Editor {
14316    fn text_for_range(
14317        &mut self,
14318        range_utf16: Range<usize>,
14319        adjusted_range: &mut Option<Range<usize>>,
14320        cx: &mut ViewContext<Self>,
14321    ) -> Option<String> {
14322        let snapshot = self.buffer.read(cx).read(cx);
14323        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14324        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14325        if (start.0..end.0) != range_utf16 {
14326            adjusted_range.replace(start.0..end.0);
14327        }
14328        Some(snapshot.text_for_range(start..end).collect())
14329    }
14330
14331    fn selected_text_range(
14332        &mut self,
14333        ignore_disabled_input: bool,
14334        cx: &mut ViewContext<Self>,
14335    ) -> Option<UTF16Selection> {
14336        // Prevent the IME menu from appearing when holding down an alphabetic key
14337        // while input is disabled.
14338        if !ignore_disabled_input && !self.input_enabled {
14339            return None;
14340        }
14341
14342        let selection = self.selections.newest::<OffsetUtf16>(cx);
14343        let range = selection.range();
14344
14345        Some(UTF16Selection {
14346            range: range.start.0..range.end.0,
14347            reversed: selection.reversed,
14348        })
14349    }
14350
14351    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14352        let snapshot = self.buffer.read(cx).read(cx);
14353        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14354        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14355    }
14356
14357    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14358        self.clear_highlights::<InputComposition>(cx);
14359        self.ime_transaction.take();
14360    }
14361
14362    fn replace_text_in_range(
14363        &mut self,
14364        range_utf16: Option<Range<usize>>,
14365        text: &str,
14366        cx: &mut ViewContext<Self>,
14367    ) {
14368        if !self.input_enabled {
14369            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14370            return;
14371        }
14372
14373        self.transact(cx, |this, cx| {
14374            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14375                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14376                Some(this.selection_replacement_ranges(range_utf16, cx))
14377            } else {
14378                this.marked_text_ranges(cx)
14379            };
14380
14381            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14382                let newest_selection_id = this.selections.newest_anchor().id;
14383                this.selections
14384                    .all::<OffsetUtf16>(cx)
14385                    .iter()
14386                    .zip(ranges_to_replace.iter())
14387                    .find_map(|(selection, range)| {
14388                        if selection.id == newest_selection_id {
14389                            Some(
14390                                (range.start.0 as isize - selection.head().0 as isize)
14391                                    ..(range.end.0 as isize - selection.head().0 as isize),
14392                            )
14393                        } else {
14394                            None
14395                        }
14396                    })
14397            });
14398
14399            cx.emit(EditorEvent::InputHandled {
14400                utf16_range_to_replace: range_to_replace,
14401                text: text.into(),
14402            });
14403
14404            if let Some(new_selected_ranges) = new_selected_ranges {
14405                this.change_selections(None, cx, |selections| {
14406                    selections.select_ranges(new_selected_ranges)
14407                });
14408                this.backspace(&Default::default(), cx);
14409            }
14410
14411            this.handle_input(text, cx);
14412        });
14413
14414        if let Some(transaction) = self.ime_transaction {
14415            self.buffer.update(cx, |buffer, cx| {
14416                buffer.group_until_transaction(transaction, cx);
14417            });
14418        }
14419
14420        self.unmark_text(cx);
14421    }
14422
14423    fn replace_and_mark_text_in_range(
14424        &mut self,
14425        range_utf16: Option<Range<usize>>,
14426        text: &str,
14427        new_selected_range_utf16: Option<Range<usize>>,
14428        cx: &mut ViewContext<Self>,
14429    ) {
14430        if !self.input_enabled {
14431            return;
14432        }
14433
14434        let transaction = self.transact(cx, |this, cx| {
14435            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14436                let snapshot = this.buffer.read(cx).read(cx);
14437                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14438                    for marked_range in &mut marked_ranges {
14439                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14440                        marked_range.start.0 += relative_range_utf16.start;
14441                        marked_range.start =
14442                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14443                        marked_range.end =
14444                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14445                    }
14446                }
14447                Some(marked_ranges)
14448            } else if let Some(range_utf16) = range_utf16 {
14449                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14450                Some(this.selection_replacement_ranges(range_utf16, cx))
14451            } else {
14452                None
14453            };
14454
14455            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14456                let newest_selection_id = this.selections.newest_anchor().id;
14457                this.selections
14458                    .all::<OffsetUtf16>(cx)
14459                    .iter()
14460                    .zip(ranges_to_replace.iter())
14461                    .find_map(|(selection, range)| {
14462                        if selection.id == newest_selection_id {
14463                            Some(
14464                                (range.start.0 as isize - selection.head().0 as isize)
14465                                    ..(range.end.0 as isize - selection.head().0 as isize),
14466                            )
14467                        } else {
14468                            None
14469                        }
14470                    })
14471            });
14472
14473            cx.emit(EditorEvent::InputHandled {
14474                utf16_range_to_replace: range_to_replace,
14475                text: text.into(),
14476            });
14477
14478            if let Some(ranges) = ranges_to_replace {
14479                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14480            }
14481
14482            let marked_ranges = {
14483                let snapshot = this.buffer.read(cx).read(cx);
14484                this.selections
14485                    .disjoint_anchors()
14486                    .iter()
14487                    .map(|selection| {
14488                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14489                    })
14490                    .collect::<Vec<_>>()
14491            };
14492
14493            if text.is_empty() {
14494                this.unmark_text(cx);
14495            } else {
14496                this.highlight_text::<InputComposition>(
14497                    marked_ranges.clone(),
14498                    HighlightStyle {
14499                        underline: Some(UnderlineStyle {
14500                            thickness: px(1.),
14501                            color: None,
14502                            wavy: false,
14503                        }),
14504                        ..Default::default()
14505                    },
14506                    cx,
14507                );
14508            }
14509
14510            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14511            let use_autoclose = this.use_autoclose;
14512            let use_auto_surround = this.use_auto_surround;
14513            this.set_use_autoclose(false);
14514            this.set_use_auto_surround(false);
14515            this.handle_input(text, cx);
14516            this.set_use_autoclose(use_autoclose);
14517            this.set_use_auto_surround(use_auto_surround);
14518
14519            if let Some(new_selected_range) = new_selected_range_utf16 {
14520                let snapshot = this.buffer.read(cx).read(cx);
14521                let new_selected_ranges = marked_ranges
14522                    .into_iter()
14523                    .map(|marked_range| {
14524                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14525                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14526                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14527                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14528                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14529                    })
14530                    .collect::<Vec<_>>();
14531
14532                drop(snapshot);
14533                this.change_selections(None, cx, |selections| {
14534                    selections.select_ranges(new_selected_ranges)
14535                });
14536            }
14537        });
14538
14539        self.ime_transaction = self.ime_transaction.or(transaction);
14540        if let Some(transaction) = self.ime_transaction {
14541            self.buffer.update(cx, |buffer, cx| {
14542                buffer.group_until_transaction(transaction, cx);
14543            });
14544        }
14545
14546        if self.text_highlights::<InputComposition>(cx).is_none() {
14547            self.ime_transaction.take();
14548        }
14549    }
14550
14551    fn bounds_for_range(
14552        &mut self,
14553        range_utf16: Range<usize>,
14554        element_bounds: gpui::Bounds<Pixels>,
14555        cx: &mut ViewContext<Self>,
14556    ) -> Option<gpui::Bounds<Pixels>> {
14557        let text_layout_details = self.text_layout_details(cx);
14558        let gpui::Point {
14559            x: em_width,
14560            y: line_height,
14561        } = self.character_size(cx);
14562
14563        let snapshot = self.snapshot(cx);
14564        let scroll_position = snapshot.scroll_position();
14565        let scroll_left = scroll_position.x * em_width;
14566
14567        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14568        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14569            + self.gutter_dimensions.width
14570            + self.gutter_dimensions.margin;
14571        let y = line_height * (start.row().as_f32() - scroll_position.y);
14572
14573        Some(Bounds {
14574            origin: element_bounds.origin + point(x, y),
14575            size: size(em_width, line_height),
14576        })
14577    }
14578}
14579
14580trait SelectionExt {
14581    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14582    fn spanned_rows(
14583        &self,
14584        include_end_if_at_line_start: bool,
14585        map: &DisplaySnapshot,
14586    ) -> Range<MultiBufferRow>;
14587}
14588
14589impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14590    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14591        let start = self
14592            .start
14593            .to_point(&map.buffer_snapshot)
14594            .to_display_point(map);
14595        let end = self
14596            .end
14597            .to_point(&map.buffer_snapshot)
14598            .to_display_point(map);
14599        if self.reversed {
14600            end..start
14601        } else {
14602            start..end
14603        }
14604    }
14605
14606    fn spanned_rows(
14607        &self,
14608        include_end_if_at_line_start: bool,
14609        map: &DisplaySnapshot,
14610    ) -> Range<MultiBufferRow> {
14611        let start = self.start.to_point(&map.buffer_snapshot);
14612        let mut end = self.end.to_point(&map.buffer_snapshot);
14613        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14614            end.row -= 1;
14615        }
14616
14617        let buffer_start = map.prev_line_boundary(start).0;
14618        let buffer_end = map.next_line_boundary(end).0;
14619        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14620    }
14621}
14622
14623impl<T: InvalidationRegion> InvalidationStack<T> {
14624    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14625    where
14626        S: Clone + ToOffset,
14627    {
14628        while let Some(region) = self.last() {
14629            let all_selections_inside_invalidation_ranges =
14630                if selections.len() == region.ranges().len() {
14631                    selections
14632                        .iter()
14633                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14634                        .all(|(selection, invalidation_range)| {
14635                            let head = selection.head().to_offset(buffer);
14636                            invalidation_range.start <= head && invalidation_range.end >= head
14637                        })
14638                } else {
14639                    false
14640                };
14641
14642            if all_selections_inside_invalidation_ranges {
14643                break;
14644            } else {
14645                self.pop();
14646            }
14647        }
14648    }
14649}
14650
14651impl<T> Default for InvalidationStack<T> {
14652    fn default() -> Self {
14653        Self(Default::default())
14654    }
14655}
14656
14657impl<T> Deref for InvalidationStack<T> {
14658    type Target = Vec<T>;
14659
14660    fn deref(&self) -> &Self::Target {
14661        &self.0
14662    }
14663}
14664
14665impl<T> DerefMut for InvalidationStack<T> {
14666    fn deref_mut(&mut self) -> &mut Self::Target {
14667        &mut self.0
14668    }
14669}
14670
14671impl InvalidationRegion for SnippetState {
14672    fn ranges(&self) -> &[Range<Anchor>] {
14673        &self.ranges[self.active_index]
14674    }
14675}
14676
14677pub fn diagnostic_block_renderer(
14678    diagnostic: Diagnostic,
14679    max_message_rows: Option<u8>,
14680    allow_closing: bool,
14681    _is_valid: bool,
14682) -> RenderBlock {
14683    let (text_without_backticks, code_ranges) =
14684        highlight_diagnostic_message(&diagnostic, max_message_rows);
14685
14686    Arc::new(move |cx: &mut BlockContext| {
14687        let group_id: SharedString = cx.block_id.to_string().into();
14688
14689        let mut text_style = cx.text_style().clone();
14690        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14691        let theme_settings = ThemeSettings::get_global(cx);
14692        text_style.font_family = theme_settings.buffer_font.family.clone();
14693        text_style.font_style = theme_settings.buffer_font.style;
14694        text_style.font_features = theme_settings.buffer_font.features.clone();
14695        text_style.font_weight = theme_settings.buffer_font.weight;
14696
14697        let multi_line_diagnostic = diagnostic.message.contains('\n');
14698
14699        let buttons = |diagnostic: &Diagnostic| {
14700            if multi_line_diagnostic {
14701                v_flex()
14702            } else {
14703                h_flex()
14704            }
14705            .when(allow_closing, |div| {
14706                div.children(diagnostic.is_primary.then(|| {
14707                    IconButton::new("close-block", IconName::XCircle)
14708                        .icon_color(Color::Muted)
14709                        .size(ButtonSize::Compact)
14710                        .style(ButtonStyle::Transparent)
14711                        .visible_on_hover(group_id.clone())
14712                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14713                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14714                }))
14715            })
14716            .child(
14717                IconButton::new("copy-block", IconName::Copy)
14718                    .icon_color(Color::Muted)
14719                    .size(ButtonSize::Compact)
14720                    .style(ButtonStyle::Transparent)
14721                    .visible_on_hover(group_id.clone())
14722                    .on_click({
14723                        let message = diagnostic.message.clone();
14724                        move |_click, cx| {
14725                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14726                        }
14727                    })
14728                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14729            )
14730        };
14731
14732        let icon_size = buttons(&diagnostic)
14733            .into_any_element()
14734            .layout_as_root(AvailableSpace::min_size(), cx);
14735
14736        h_flex()
14737            .id(cx.block_id)
14738            .group(group_id.clone())
14739            .relative()
14740            .size_full()
14741            .block_mouse_down()
14742            .pl(cx.gutter_dimensions.width)
14743            .w(cx.max_width - cx.gutter_dimensions.full_width())
14744            .child(
14745                div()
14746                    .flex()
14747                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14748                    .flex_shrink(),
14749            )
14750            .child(buttons(&diagnostic))
14751            .child(div().flex().flex_shrink_0().child(
14752                StyledText::new(text_without_backticks.clone()).with_highlights(
14753                    &text_style,
14754                    code_ranges.iter().map(|range| {
14755                        (
14756                            range.clone(),
14757                            HighlightStyle {
14758                                font_weight: Some(FontWeight::BOLD),
14759                                ..Default::default()
14760                            },
14761                        )
14762                    }),
14763                ),
14764            ))
14765            .into_any_element()
14766    })
14767}
14768
14769fn inline_completion_edit_text(
14770    editor_snapshot: &EditorSnapshot,
14771    edits: &Vec<(Range<Anchor>, String)>,
14772    include_deletions: bool,
14773    cx: &WindowContext,
14774) -> InlineCompletionText {
14775    let edit_start = edits
14776        .first()
14777        .unwrap()
14778        .0
14779        .start
14780        .to_display_point(editor_snapshot);
14781
14782    let mut text = String::new();
14783    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14784    let mut highlights = Vec::new();
14785    for (old_range, new_text) in edits {
14786        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14787        text.extend(
14788            editor_snapshot
14789                .buffer_snapshot
14790                .chunks(offset..old_offset_range.start, false)
14791                .map(|chunk| chunk.text),
14792        );
14793        offset = old_offset_range.end;
14794
14795        let start = text.len();
14796        let color = if include_deletions && new_text.is_empty() {
14797            text.extend(
14798                editor_snapshot
14799                    .buffer_snapshot
14800                    .chunks(old_offset_range.start..offset, false)
14801                    .map(|chunk| chunk.text),
14802            );
14803            cx.theme().status().deleted_background
14804        } else {
14805            text.push_str(new_text);
14806            cx.theme().status().created_background
14807        };
14808        let end = text.len();
14809
14810        highlights.push((
14811            start..end,
14812            HighlightStyle {
14813                background_color: Some(color),
14814                ..Default::default()
14815            },
14816        ));
14817    }
14818
14819    let edit_end = edits
14820        .last()
14821        .unwrap()
14822        .0
14823        .end
14824        .to_display_point(editor_snapshot);
14825    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14826        .to_offset(editor_snapshot, Bias::Right);
14827    text.extend(
14828        editor_snapshot
14829            .buffer_snapshot
14830            .chunks(offset..end_of_line, false)
14831            .map(|chunk| chunk.text),
14832    );
14833
14834    InlineCompletionText::Edit {
14835        text: text.into(),
14836        highlights,
14837    }
14838}
14839
14840pub fn highlight_diagnostic_message(
14841    diagnostic: &Diagnostic,
14842    mut max_message_rows: Option<u8>,
14843) -> (SharedString, Vec<Range<usize>>) {
14844    let mut text_without_backticks = String::new();
14845    let mut code_ranges = Vec::new();
14846
14847    if let Some(source) = &diagnostic.source {
14848        text_without_backticks.push_str(source);
14849        code_ranges.push(0..source.len());
14850        text_without_backticks.push_str(": ");
14851    }
14852
14853    let mut prev_offset = 0;
14854    let mut in_code_block = false;
14855    let has_row_limit = max_message_rows.is_some();
14856    let mut newline_indices = diagnostic
14857        .message
14858        .match_indices('\n')
14859        .filter(|_| has_row_limit)
14860        .map(|(ix, _)| ix)
14861        .fuse()
14862        .peekable();
14863
14864    for (quote_ix, _) in diagnostic
14865        .message
14866        .match_indices('`')
14867        .chain([(diagnostic.message.len(), "")])
14868    {
14869        let mut first_newline_ix = None;
14870        let mut last_newline_ix = None;
14871        while let Some(newline_ix) = newline_indices.peek() {
14872            if *newline_ix < quote_ix {
14873                if first_newline_ix.is_none() {
14874                    first_newline_ix = Some(*newline_ix);
14875                }
14876                last_newline_ix = Some(*newline_ix);
14877
14878                if let Some(rows_left) = &mut max_message_rows {
14879                    if *rows_left == 0 {
14880                        break;
14881                    } else {
14882                        *rows_left -= 1;
14883                    }
14884                }
14885                let _ = newline_indices.next();
14886            } else {
14887                break;
14888            }
14889        }
14890        let prev_len = text_without_backticks.len();
14891        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14892        text_without_backticks.push_str(new_text);
14893        if in_code_block {
14894            code_ranges.push(prev_len..text_without_backticks.len());
14895        }
14896        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14897        in_code_block = !in_code_block;
14898        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14899            text_without_backticks.push_str("...");
14900            break;
14901        }
14902    }
14903
14904    (text_without_backticks.into(), code_ranges)
14905}
14906
14907fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14908    match severity {
14909        DiagnosticSeverity::ERROR => colors.error,
14910        DiagnosticSeverity::WARNING => colors.warning,
14911        DiagnosticSeverity::INFORMATION => colors.info,
14912        DiagnosticSeverity::HINT => colors.info,
14913        _ => colors.ignored,
14914    }
14915}
14916
14917pub fn styled_runs_for_code_label<'a>(
14918    label: &'a CodeLabel,
14919    syntax_theme: &'a theme::SyntaxTheme,
14920) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14921    let fade_out = HighlightStyle {
14922        fade_out: Some(0.35),
14923        ..Default::default()
14924    };
14925
14926    let mut prev_end = label.filter_range.end;
14927    label
14928        .runs
14929        .iter()
14930        .enumerate()
14931        .flat_map(move |(ix, (range, highlight_id))| {
14932            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14933                style
14934            } else {
14935                return Default::default();
14936            };
14937            let mut muted_style = style;
14938            muted_style.highlight(fade_out);
14939
14940            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14941            if range.start >= label.filter_range.end {
14942                if range.start > prev_end {
14943                    runs.push((prev_end..range.start, fade_out));
14944                }
14945                runs.push((range.clone(), muted_style));
14946            } else if range.end <= label.filter_range.end {
14947                runs.push((range.clone(), style));
14948            } else {
14949                runs.push((range.start..label.filter_range.end, style));
14950                runs.push((label.filter_range.end..range.end, muted_style));
14951            }
14952            prev_end = cmp::max(prev_end, range.end);
14953
14954            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14955                runs.push((prev_end..label.text.len(), fade_out));
14956            }
14957
14958            runs
14959        })
14960}
14961
14962pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14963    let mut prev_index = 0;
14964    let mut prev_codepoint: Option<char> = None;
14965    text.char_indices()
14966        .chain([(text.len(), '\0')])
14967        .filter_map(move |(index, codepoint)| {
14968            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14969            let is_boundary = index == text.len()
14970                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14971                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14972            if is_boundary {
14973                let chunk = &text[prev_index..index];
14974                prev_index = index;
14975                Some(chunk)
14976            } else {
14977                None
14978            }
14979        })
14980}
14981
14982pub trait RangeToAnchorExt: Sized {
14983    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14984
14985    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14986        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14987        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14988    }
14989}
14990
14991impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14992    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14993        let start_offset = self.start.to_offset(snapshot);
14994        let end_offset = self.end.to_offset(snapshot);
14995        if start_offset == end_offset {
14996            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14997        } else {
14998            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14999        }
15000    }
15001}
15002
15003pub trait RowExt {
15004    fn as_f32(&self) -> f32;
15005
15006    fn next_row(&self) -> Self;
15007
15008    fn previous_row(&self) -> Self;
15009
15010    fn minus(&self, other: Self) -> u32;
15011}
15012
15013impl RowExt for DisplayRow {
15014    fn as_f32(&self) -> f32 {
15015        self.0 as f32
15016    }
15017
15018    fn next_row(&self) -> Self {
15019        Self(self.0 + 1)
15020    }
15021
15022    fn previous_row(&self) -> Self {
15023        Self(self.0.saturating_sub(1))
15024    }
15025
15026    fn minus(&self, other: Self) -> u32 {
15027        self.0 - other.0
15028    }
15029}
15030
15031impl RowExt for MultiBufferRow {
15032    fn as_f32(&self) -> f32 {
15033        self.0 as f32
15034    }
15035
15036    fn next_row(&self) -> Self {
15037        Self(self.0 + 1)
15038    }
15039
15040    fn previous_row(&self) -> Self {
15041        Self(self.0.saturating_sub(1))
15042    }
15043
15044    fn minus(&self, other: Self) -> u32 {
15045        self.0 - other.0
15046    }
15047}
15048
15049trait RowRangeExt {
15050    type Row;
15051
15052    fn len(&self) -> usize;
15053
15054    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15055}
15056
15057impl RowRangeExt for Range<MultiBufferRow> {
15058    type Row = MultiBufferRow;
15059
15060    fn len(&self) -> usize {
15061        (self.end.0 - self.start.0) as usize
15062    }
15063
15064    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15065        (self.start.0..self.end.0).map(MultiBufferRow)
15066    }
15067}
15068
15069impl RowRangeExt for Range<DisplayRow> {
15070    type Row = DisplayRow;
15071
15072    fn len(&self) -> usize {
15073        (self.end.0 - self.start.0) as usize
15074    }
15075
15076    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15077        (self.start.0..self.end.0).map(DisplayRow)
15078    }
15079}
15080
15081fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15082    if hunk.diff_base_byte_range.is_empty() {
15083        DiffHunkStatus::Added
15084    } else if hunk.row_range.is_empty() {
15085        DiffHunkStatus::Removed
15086    } else {
15087        DiffHunkStatus::Modified
15088    }
15089}
15090
15091/// If select range has more than one line, we
15092/// just point the cursor to range.start.
15093fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15094    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15095        range
15096    } else {
15097        range.start..range.start
15098    }
15099}
15100
15101pub struct KillRing(ClipboardItem);
15102impl Global for KillRing {}
15103
15104const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);