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().iter().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            .filter(|s| !s.is_empty())
10264            .collect_vec();
10265
10266        Some(self.perform_format(
10267            project,
10268            FormatTrigger::Manual,
10269            FormatTarget::Ranges(ranges),
10270            cx,
10271        ))
10272    }
10273
10274    fn perform_format(
10275        &mut self,
10276        project: Model<Project>,
10277        trigger: FormatTrigger,
10278        target: FormatTarget,
10279        cx: &mut ViewContext<Self>,
10280    ) -> Task<Result<()>> {
10281        let buffer = self.buffer.clone();
10282        let (buffers, target) = match target {
10283            FormatTarget::Buffers => {
10284                let mut buffers = buffer.read(cx).all_buffers();
10285                if trigger == FormatTrigger::Save {
10286                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
10287                }
10288                (buffers, LspFormatTarget::Buffers)
10289            }
10290            FormatTarget::Ranges(selection_ranges) => {
10291                let multi_buffer = buffer.read(cx);
10292                let snapshot = multi_buffer.read(cx);
10293                let mut buffers = HashSet::default();
10294                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
10295                    BTreeMap::new();
10296                for selection_range in selection_ranges {
10297                    for (excerpt, buffer_range) in snapshot.range_to_buffer_ranges(selection_range)
10298                    {
10299                        let buffer_id = excerpt.buffer_id();
10300                        let start = excerpt.buffer().anchor_before(buffer_range.start);
10301                        let end = excerpt.buffer().anchor_after(buffer_range.end);
10302                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
10303                        buffer_id_to_ranges
10304                            .entry(buffer_id)
10305                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
10306                            .or_insert_with(|| vec![start..end]);
10307                    }
10308                }
10309                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
10310            }
10311        };
10312
10313        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10314        let format = project.update(cx, |project, cx| {
10315            project.format(buffers, target, true, trigger, cx)
10316        });
10317
10318        cx.spawn(|_, mut cx| async move {
10319            let transaction = futures::select_biased! {
10320                () = timeout => {
10321                    log::warn!("timed out waiting for formatting");
10322                    None
10323                }
10324                transaction = format.log_err().fuse() => transaction,
10325            };
10326
10327            buffer
10328                .update(&mut cx, |buffer, cx| {
10329                    if let Some(transaction) = transaction {
10330                        if !buffer.is_singleton() {
10331                            buffer.push_transaction(&transaction.0, cx);
10332                        }
10333                    }
10334
10335                    cx.notify();
10336                })
10337                .ok();
10338
10339            Ok(())
10340        })
10341    }
10342
10343    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10344        if let Some(project) = self.project.clone() {
10345            self.buffer.update(cx, |multi_buffer, cx| {
10346                project.update(cx, |project, cx| {
10347                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10348                });
10349            })
10350        }
10351    }
10352
10353    fn cancel_language_server_work(
10354        &mut self,
10355        _: &actions::CancelLanguageServerWork,
10356        cx: &mut ViewContext<Self>,
10357    ) {
10358        if let Some(project) = self.project.clone() {
10359            self.buffer.update(cx, |multi_buffer, cx| {
10360                project.update(cx, |project, cx| {
10361                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10362                });
10363            })
10364        }
10365    }
10366
10367    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10368        cx.show_character_palette();
10369    }
10370
10371    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10372        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10373            let buffer = self.buffer.read(cx).snapshot(cx);
10374            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10375            let is_valid = buffer
10376                .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10377                .any(|entry| {
10378                    let range = entry.range.to_offset(&buffer);
10379                    entry.diagnostic.is_primary
10380                        && !range.is_empty()
10381                        && range.start == primary_range_start
10382                        && entry.diagnostic.message == active_diagnostics.primary_message
10383                });
10384
10385            if is_valid != active_diagnostics.is_valid {
10386                active_diagnostics.is_valid = is_valid;
10387                let mut new_styles = HashMap::default();
10388                for (block_id, diagnostic) in &active_diagnostics.blocks {
10389                    new_styles.insert(
10390                        *block_id,
10391                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10392                    );
10393                }
10394                self.display_map.update(cx, |display_map, _cx| {
10395                    display_map.replace_blocks(new_styles)
10396                });
10397            }
10398        }
10399    }
10400
10401    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10402        self.dismiss_diagnostics(cx);
10403        let snapshot = self.snapshot(cx);
10404        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10405            let buffer = self.buffer.read(cx).snapshot(cx);
10406
10407            let mut primary_range = None;
10408            let mut primary_message = None;
10409            let mut group_end = Point::zero();
10410            let diagnostic_group = buffer
10411                .diagnostic_group(group_id)
10412                .filter_map(|entry| {
10413                    let start = entry.range.start.to_point(&buffer);
10414                    let end = entry.range.end.to_point(&buffer);
10415                    if snapshot.is_line_folded(MultiBufferRow(start.row))
10416                        && (start.row == end.row
10417                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
10418                    {
10419                        return None;
10420                    }
10421                    if end > group_end {
10422                        group_end = end;
10423                    }
10424                    if entry.diagnostic.is_primary {
10425                        primary_range = Some(entry.range.clone());
10426                        primary_message = Some(entry.diagnostic.message.clone());
10427                    }
10428                    Some(entry)
10429                })
10430                .collect::<Vec<_>>();
10431            let primary_range = primary_range?;
10432            let primary_message = primary_message?;
10433
10434            let blocks = display_map
10435                .insert_blocks(
10436                    diagnostic_group.iter().map(|entry| {
10437                        let diagnostic = entry.diagnostic.clone();
10438                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10439                        BlockProperties {
10440                            style: BlockStyle::Fixed,
10441                            placement: BlockPlacement::Below(
10442                                buffer.anchor_after(entry.range.start),
10443                            ),
10444                            height: message_height,
10445                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10446                            priority: 0,
10447                        }
10448                    }),
10449                    cx,
10450                )
10451                .into_iter()
10452                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10453                .collect();
10454
10455            Some(ActiveDiagnosticGroup {
10456                primary_range,
10457                primary_message,
10458                group_id,
10459                blocks,
10460                is_valid: true,
10461            })
10462        });
10463    }
10464
10465    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10466        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10467            self.display_map.update(cx, |display_map, cx| {
10468                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10469            });
10470            cx.notify();
10471        }
10472    }
10473
10474    pub fn set_selections_from_remote(
10475        &mut self,
10476        selections: Vec<Selection<Anchor>>,
10477        pending_selection: Option<Selection<Anchor>>,
10478        cx: &mut ViewContext<Self>,
10479    ) {
10480        let old_cursor_position = self.selections.newest_anchor().head();
10481        self.selections.change_with(cx, |s| {
10482            s.select_anchors(selections);
10483            if let Some(pending_selection) = pending_selection {
10484                s.set_pending(pending_selection, SelectMode::Character);
10485            } else {
10486                s.clear_pending();
10487            }
10488        });
10489        self.selections_did_change(false, &old_cursor_position, true, cx);
10490    }
10491
10492    fn push_to_selection_history(&mut self) {
10493        self.selection_history.push(SelectionHistoryEntry {
10494            selections: self.selections.disjoint_anchors(),
10495            select_next_state: self.select_next_state.clone(),
10496            select_prev_state: self.select_prev_state.clone(),
10497            add_selections_state: self.add_selections_state.clone(),
10498        });
10499    }
10500
10501    pub fn transact(
10502        &mut self,
10503        cx: &mut ViewContext<Self>,
10504        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10505    ) -> Option<TransactionId> {
10506        self.start_transaction_at(Instant::now(), cx);
10507        update(self, cx);
10508        self.end_transaction_at(Instant::now(), cx)
10509    }
10510
10511    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10512        self.end_selection(cx);
10513        if let Some(tx_id) = self
10514            .buffer
10515            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10516        {
10517            self.selection_history
10518                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10519            cx.emit(EditorEvent::TransactionBegun {
10520                transaction_id: tx_id,
10521            })
10522        }
10523    }
10524
10525    pub fn end_transaction_at(
10526        &mut self,
10527        now: Instant,
10528        cx: &mut ViewContext<Self>,
10529    ) -> Option<TransactionId> {
10530        if let Some(transaction_id) = self
10531            .buffer
10532            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10533        {
10534            if let Some((_, end_selections)) =
10535                self.selection_history.transaction_mut(transaction_id)
10536            {
10537                *end_selections = Some(self.selections.disjoint_anchors());
10538            } else {
10539                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10540            }
10541
10542            cx.emit(EditorEvent::Edited { transaction_id });
10543            Some(transaction_id)
10544        } else {
10545            None
10546        }
10547    }
10548
10549    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10550        if self.is_singleton(cx) {
10551            let selection = self.selections.newest::<Point>(cx);
10552
10553            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10554            let range = if selection.is_empty() {
10555                let point = selection.head().to_display_point(&display_map);
10556                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10557                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10558                    .to_point(&display_map);
10559                start..end
10560            } else {
10561                selection.range()
10562            };
10563            if display_map.folds_in_range(range).next().is_some() {
10564                self.unfold_lines(&Default::default(), cx)
10565            } else {
10566                self.fold(&Default::default(), cx)
10567            }
10568        } else {
10569            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10570            let mut toggled_buffers = HashSet::default();
10571            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10572                self.selections
10573                    .disjoint_anchors()
10574                    .into_iter()
10575                    .map(|selection| selection.range()),
10576            ) {
10577                let buffer_id = buffer_snapshot.remote_id();
10578                if toggled_buffers.insert(buffer_id) {
10579                    if self.buffer_folded(buffer_id, cx) {
10580                        self.unfold_buffer(buffer_id, cx);
10581                    } else {
10582                        self.fold_buffer(buffer_id, cx);
10583                    }
10584                }
10585            }
10586        }
10587    }
10588
10589    pub fn toggle_fold_recursive(
10590        &mut self,
10591        _: &actions::ToggleFoldRecursive,
10592        cx: &mut ViewContext<Self>,
10593    ) {
10594        let selection = self.selections.newest::<Point>(cx);
10595
10596        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10597        let range = if selection.is_empty() {
10598            let point = selection.head().to_display_point(&display_map);
10599            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10600            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10601                .to_point(&display_map);
10602            start..end
10603        } else {
10604            selection.range()
10605        };
10606        if display_map.folds_in_range(range).next().is_some() {
10607            self.unfold_recursive(&Default::default(), cx)
10608        } else {
10609            self.fold_recursive(&Default::default(), cx)
10610        }
10611    }
10612
10613    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10614        if self.is_singleton(cx) {
10615            let mut to_fold = Vec::new();
10616            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10617            let selections = self.selections.all_adjusted(cx);
10618
10619            for selection in selections {
10620                let range = selection.range().sorted();
10621                let buffer_start_row = range.start.row;
10622
10623                if range.start.row != range.end.row {
10624                    let mut found = false;
10625                    let mut row = range.start.row;
10626                    while row <= range.end.row {
10627                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10628                        {
10629                            found = true;
10630                            row = crease.range().end.row + 1;
10631                            to_fold.push(crease);
10632                        } else {
10633                            row += 1
10634                        }
10635                    }
10636                    if found {
10637                        continue;
10638                    }
10639                }
10640
10641                for row in (0..=range.start.row).rev() {
10642                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10643                        if crease.range().end.row >= buffer_start_row {
10644                            to_fold.push(crease);
10645                            if row <= range.start.row {
10646                                break;
10647                            }
10648                        }
10649                    }
10650                }
10651            }
10652
10653            self.fold_creases(to_fold, true, cx);
10654        } else {
10655            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10656            let mut folded_buffers = HashSet::default();
10657            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10658                self.selections
10659                    .disjoint_anchors()
10660                    .into_iter()
10661                    .map(|selection| selection.range()),
10662            ) {
10663                let buffer_id = buffer_snapshot.remote_id();
10664                if folded_buffers.insert(buffer_id) {
10665                    self.fold_buffer(buffer_id, cx);
10666                }
10667            }
10668        }
10669    }
10670
10671    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10672        if !self.buffer.read(cx).is_singleton() {
10673            return;
10674        }
10675
10676        let fold_at_level = fold_at.level;
10677        let snapshot = self.buffer.read(cx).snapshot(cx);
10678        let mut to_fold = Vec::new();
10679        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10680
10681        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10682            while start_row < end_row {
10683                match self
10684                    .snapshot(cx)
10685                    .crease_for_buffer_row(MultiBufferRow(start_row))
10686                {
10687                    Some(crease) => {
10688                        let nested_start_row = crease.range().start.row + 1;
10689                        let nested_end_row = crease.range().end.row;
10690
10691                        if current_level < fold_at_level {
10692                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10693                        } else if current_level == fold_at_level {
10694                            to_fold.push(crease);
10695                        }
10696
10697                        start_row = nested_end_row + 1;
10698                    }
10699                    None => start_row += 1,
10700                }
10701            }
10702        }
10703
10704        self.fold_creases(to_fold, true, cx);
10705    }
10706
10707    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10708        if self.buffer.read(cx).is_singleton() {
10709            let mut fold_ranges = Vec::new();
10710            let snapshot = self.buffer.read(cx).snapshot(cx);
10711
10712            for row in 0..snapshot.max_row().0 {
10713                if let Some(foldable_range) =
10714                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10715                {
10716                    fold_ranges.push(foldable_range);
10717                }
10718            }
10719
10720            self.fold_creases(fold_ranges, true, cx);
10721        } else {
10722            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10723                editor
10724                    .update(&mut cx, |editor, cx| {
10725                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10726                            editor.fold_buffer(buffer_id, cx);
10727                        }
10728                    })
10729                    .ok();
10730            });
10731        }
10732    }
10733
10734    pub fn fold_function_bodies(
10735        &mut self,
10736        _: &actions::FoldFunctionBodies,
10737        cx: &mut ViewContext<Self>,
10738    ) {
10739        let snapshot = self.buffer.read(cx).snapshot(cx);
10740        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10741            return;
10742        };
10743        let creases = buffer
10744            .function_body_fold_ranges(0..buffer.len())
10745            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10746            .collect();
10747
10748        self.fold_creases(creases, true, cx);
10749    }
10750
10751    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10752        let mut to_fold = Vec::new();
10753        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10754        let selections = self.selections.all_adjusted(cx);
10755
10756        for selection in selections {
10757            let range = selection.range().sorted();
10758            let buffer_start_row = range.start.row;
10759
10760            if range.start.row != range.end.row {
10761                let mut found = false;
10762                for row in range.start.row..=range.end.row {
10763                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10764                        found = true;
10765                        to_fold.push(crease);
10766                    }
10767                }
10768                if found {
10769                    continue;
10770                }
10771            }
10772
10773            for row in (0..=range.start.row).rev() {
10774                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10775                    if crease.range().end.row >= buffer_start_row {
10776                        to_fold.push(crease);
10777                    } else {
10778                        break;
10779                    }
10780                }
10781            }
10782        }
10783
10784        self.fold_creases(to_fold, true, cx);
10785    }
10786
10787    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10788        let buffer_row = fold_at.buffer_row;
10789        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10790
10791        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10792            let autoscroll = self
10793                .selections
10794                .all::<Point>(cx)
10795                .iter()
10796                .any(|selection| crease.range().overlaps(&selection.range()));
10797
10798            self.fold_creases(vec![crease], autoscroll, cx);
10799        }
10800    }
10801
10802    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10803        if self.is_singleton(cx) {
10804            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10805            let buffer = &display_map.buffer_snapshot;
10806            let selections = self.selections.all::<Point>(cx);
10807            let ranges = selections
10808                .iter()
10809                .map(|s| {
10810                    let range = s.display_range(&display_map).sorted();
10811                    let mut start = range.start.to_point(&display_map);
10812                    let mut end = range.end.to_point(&display_map);
10813                    start.column = 0;
10814                    end.column = buffer.line_len(MultiBufferRow(end.row));
10815                    start..end
10816                })
10817                .collect::<Vec<_>>();
10818
10819            self.unfold_ranges(&ranges, true, true, cx);
10820        } else {
10821            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10822            let mut unfolded_buffers = HashSet::default();
10823            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10824                self.selections
10825                    .disjoint_anchors()
10826                    .into_iter()
10827                    .map(|selection| selection.range()),
10828            ) {
10829                let buffer_id = buffer_snapshot.remote_id();
10830                if unfolded_buffers.insert(buffer_id) {
10831                    self.unfold_buffer(buffer_id, cx);
10832                }
10833            }
10834        }
10835    }
10836
10837    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10838        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10839        let selections = self.selections.all::<Point>(cx);
10840        let ranges = selections
10841            .iter()
10842            .map(|s| {
10843                let mut range = s.display_range(&display_map).sorted();
10844                *range.start.column_mut() = 0;
10845                *range.end.column_mut() = display_map.line_len(range.end.row());
10846                let start = range.start.to_point(&display_map);
10847                let end = range.end.to_point(&display_map);
10848                start..end
10849            })
10850            .collect::<Vec<_>>();
10851
10852        self.unfold_ranges(&ranges, true, true, cx);
10853    }
10854
10855    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10856        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10857
10858        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10859            ..Point::new(
10860                unfold_at.buffer_row.0,
10861                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10862            );
10863
10864        let autoscroll = self
10865            .selections
10866            .all::<Point>(cx)
10867            .iter()
10868            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10869
10870        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10871    }
10872
10873    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10874        if self.buffer.read(cx).is_singleton() {
10875            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10876            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10877        } else {
10878            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10879                editor
10880                    .update(&mut cx, |editor, cx| {
10881                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10882                            editor.unfold_buffer(buffer_id, cx);
10883                        }
10884                    })
10885                    .ok();
10886            });
10887        }
10888    }
10889
10890    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10891        let selections = self.selections.all::<Point>(cx);
10892        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10893        let line_mode = self.selections.line_mode;
10894        let ranges = selections
10895            .into_iter()
10896            .map(|s| {
10897                if line_mode {
10898                    let start = Point::new(s.start.row, 0);
10899                    let end = Point::new(
10900                        s.end.row,
10901                        display_map
10902                            .buffer_snapshot
10903                            .line_len(MultiBufferRow(s.end.row)),
10904                    );
10905                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10906                } else {
10907                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10908                }
10909            })
10910            .collect::<Vec<_>>();
10911        self.fold_creases(ranges, true, cx);
10912    }
10913
10914    pub fn fold_creases<T: ToOffset + Clone>(
10915        &mut self,
10916        creases: Vec<Crease<T>>,
10917        auto_scroll: bool,
10918        cx: &mut ViewContext<Self>,
10919    ) {
10920        if creases.is_empty() {
10921            return;
10922        }
10923
10924        let mut buffers_affected = HashSet::default();
10925        let multi_buffer = self.buffer().read(cx);
10926        for crease in &creases {
10927            if let Some((_, buffer, _)) =
10928                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10929            {
10930                buffers_affected.insert(buffer.read(cx).remote_id());
10931            };
10932        }
10933
10934        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10935
10936        if auto_scroll {
10937            self.request_autoscroll(Autoscroll::fit(), cx);
10938        }
10939
10940        for buffer_id in buffers_affected {
10941            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10942        }
10943
10944        cx.notify();
10945
10946        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10947            // Clear diagnostics block when folding a range that contains it.
10948            let snapshot = self.snapshot(cx);
10949            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10950                drop(snapshot);
10951                self.active_diagnostics = Some(active_diagnostics);
10952                self.dismiss_diagnostics(cx);
10953            } else {
10954                self.active_diagnostics = Some(active_diagnostics);
10955            }
10956        }
10957
10958        self.scrollbar_marker_state.dirty = true;
10959    }
10960
10961    /// Removes any folds whose ranges intersect any of the given ranges.
10962    pub fn unfold_ranges<T: ToOffset + Clone>(
10963        &mut self,
10964        ranges: &[Range<T>],
10965        inclusive: bool,
10966        auto_scroll: bool,
10967        cx: &mut ViewContext<Self>,
10968    ) {
10969        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10970            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10971        });
10972    }
10973
10974    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10975        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10976            return;
10977        }
10978        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10979            return;
10980        };
10981        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10982        self.display_map
10983            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10984        cx.emit(EditorEvent::BufferFoldToggled {
10985            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10986            folded: true,
10987        });
10988        cx.notify();
10989    }
10990
10991    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10992        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10993            return;
10994        }
10995        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10996            return;
10997        };
10998        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10999        self.display_map.update(cx, |display_map, cx| {
11000            display_map.unfold_buffer(buffer_id, cx);
11001        });
11002        cx.emit(EditorEvent::BufferFoldToggled {
11003            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
11004            folded: false,
11005        });
11006        cx.notify();
11007    }
11008
11009    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
11010        self.display_map.read(cx).buffer_folded(buffer)
11011    }
11012
11013    /// Removes any folds with the given ranges.
11014    pub fn remove_folds_with_type<T: ToOffset + Clone>(
11015        &mut self,
11016        ranges: &[Range<T>],
11017        type_id: TypeId,
11018        auto_scroll: bool,
11019        cx: &mut ViewContext<Self>,
11020    ) {
11021        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11022            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11023        });
11024    }
11025
11026    fn remove_folds_with<T: ToOffset + Clone>(
11027        &mut self,
11028        ranges: &[Range<T>],
11029        auto_scroll: bool,
11030        cx: &mut ViewContext<Self>,
11031        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11032    ) {
11033        if ranges.is_empty() {
11034            return;
11035        }
11036
11037        let mut buffers_affected = HashSet::default();
11038        let multi_buffer = self.buffer().read(cx);
11039        for range in ranges {
11040            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11041                buffers_affected.insert(buffer.read(cx).remote_id());
11042            };
11043        }
11044
11045        self.display_map.update(cx, update);
11046
11047        if auto_scroll {
11048            self.request_autoscroll(Autoscroll::fit(), cx);
11049        }
11050
11051        for buffer_id in buffers_affected {
11052            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11053        }
11054
11055        cx.notify();
11056        self.scrollbar_marker_state.dirty = true;
11057        self.active_indent_guides_state.dirty = true;
11058    }
11059
11060    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11061        self.display_map.read(cx).fold_placeholder.clone()
11062    }
11063
11064    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11065        if hovered != self.gutter_hovered {
11066            self.gutter_hovered = hovered;
11067            cx.notify();
11068        }
11069    }
11070
11071    pub fn insert_blocks(
11072        &mut self,
11073        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11074        autoscroll: Option<Autoscroll>,
11075        cx: &mut ViewContext<Self>,
11076    ) -> Vec<CustomBlockId> {
11077        let blocks = self
11078            .display_map
11079            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11080        if let Some(autoscroll) = autoscroll {
11081            self.request_autoscroll(autoscroll, cx);
11082        }
11083        cx.notify();
11084        blocks
11085    }
11086
11087    pub fn resize_blocks(
11088        &mut self,
11089        heights: HashMap<CustomBlockId, u32>,
11090        autoscroll: Option<Autoscroll>,
11091        cx: &mut ViewContext<Self>,
11092    ) {
11093        self.display_map
11094            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11095        if let Some(autoscroll) = autoscroll {
11096            self.request_autoscroll(autoscroll, cx);
11097        }
11098        cx.notify();
11099    }
11100
11101    pub fn replace_blocks(
11102        &mut self,
11103        renderers: HashMap<CustomBlockId, RenderBlock>,
11104        autoscroll: Option<Autoscroll>,
11105        cx: &mut ViewContext<Self>,
11106    ) {
11107        self.display_map
11108            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11109        if let Some(autoscroll) = autoscroll {
11110            self.request_autoscroll(autoscroll, cx);
11111        }
11112        cx.notify();
11113    }
11114
11115    pub fn remove_blocks(
11116        &mut self,
11117        block_ids: HashSet<CustomBlockId>,
11118        autoscroll: Option<Autoscroll>,
11119        cx: &mut ViewContext<Self>,
11120    ) {
11121        self.display_map.update(cx, |display_map, cx| {
11122            display_map.remove_blocks(block_ids, cx)
11123        });
11124        if let Some(autoscroll) = autoscroll {
11125            self.request_autoscroll(autoscroll, cx);
11126        }
11127        cx.notify();
11128    }
11129
11130    pub fn row_for_block(
11131        &self,
11132        block_id: CustomBlockId,
11133        cx: &mut ViewContext<Self>,
11134    ) -> Option<DisplayRow> {
11135        self.display_map
11136            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11137    }
11138
11139    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11140        self.focused_block = Some(focused_block);
11141    }
11142
11143    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11144        self.focused_block.take()
11145    }
11146
11147    pub fn insert_creases(
11148        &mut self,
11149        creases: impl IntoIterator<Item = Crease<Anchor>>,
11150        cx: &mut ViewContext<Self>,
11151    ) -> Vec<CreaseId> {
11152        self.display_map
11153            .update(cx, |map, cx| map.insert_creases(creases, cx))
11154    }
11155
11156    pub fn remove_creases(
11157        &mut self,
11158        ids: impl IntoIterator<Item = CreaseId>,
11159        cx: &mut ViewContext<Self>,
11160    ) {
11161        self.display_map
11162            .update(cx, |map, cx| map.remove_creases(ids, cx));
11163    }
11164
11165    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11166        self.display_map
11167            .update(cx, |map, cx| map.snapshot(cx))
11168            .longest_row()
11169    }
11170
11171    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11172        self.display_map
11173            .update(cx, |map, cx| map.snapshot(cx))
11174            .max_point()
11175    }
11176
11177    pub fn text(&self, cx: &AppContext) -> String {
11178        self.buffer.read(cx).read(cx).text()
11179    }
11180
11181    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11182        let text = self.text(cx);
11183        let text = text.trim();
11184
11185        if text.is_empty() {
11186            return None;
11187        }
11188
11189        Some(text.to_string())
11190    }
11191
11192    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11193        self.transact(cx, |this, cx| {
11194            this.buffer
11195                .read(cx)
11196                .as_singleton()
11197                .expect("you can only call set_text on editors for singleton buffers")
11198                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11199        });
11200    }
11201
11202    pub fn display_text(&self, cx: &mut AppContext) -> String {
11203        self.display_map
11204            .update(cx, |map, cx| map.snapshot(cx))
11205            .text()
11206    }
11207
11208    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11209        let mut wrap_guides = smallvec::smallvec![];
11210
11211        if self.show_wrap_guides == Some(false) {
11212            return wrap_guides;
11213        }
11214
11215        let settings = self.buffer.read(cx).settings_at(0, cx);
11216        if settings.show_wrap_guides {
11217            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11218                wrap_guides.push((soft_wrap as usize, true));
11219            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11220                wrap_guides.push((soft_wrap as usize, true));
11221            }
11222            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11223        }
11224
11225        wrap_guides
11226    }
11227
11228    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11229        let settings = self.buffer.read(cx).settings_at(0, cx);
11230        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11231        match mode {
11232            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11233                SoftWrap::None
11234            }
11235            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11236            language_settings::SoftWrap::PreferredLineLength => {
11237                SoftWrap::Column(settings.preferred_line_length)
11238            }
11239            language_settings::SoftWrap::Bounded => {
11240                SoftWrap::Bounded(settings.preferred_line_length)
11241            }
11242        }
11243    }
11244
11245    pub fn set_soft_wrap_mode(
11246        &mut self,
11247        mode: language_settings::SoftWrap,
11248        cx: &mut ViewContext<Self>,
11249    ) {
11250        self.soft_wrap_mode_override = Some(mode);
11251        cx.notify();
11252    }
11253
11254    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11255        self.text_style_refinement = Some(style);
11256    }
11257
11258    /// called by the Element so we know what style we were most recently rendered with.
11259    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11260        let rem_size = cx.rem_size();
11261        self.display_map.update(cx, |map, cx| {
11262            map.set_font(
11263                style.text.font(),
11264                style.text.font_size.to_pixels(rem_size),
11265                cx,
11266            )
11267        });
11268        self.style = Some(style);
11269    }
11270
11271    pub fn style(&self) -> Option<&EditorStyle> {
11272        self.style.as_ref()
11273    }
11274
11275    // Called by the element. This method is not designed to be called outside of the editor
11276    // element's layout code because it does not notify when rewrapping is computed synchronously.
11277    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11278        self.display_map
11279            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11280    }
11281
11282    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11283        if self.soft_wrap_mode_override.is_some() {
11284            self.soft_wrap_mode_override.take();
11285        } else {
11286            let soft_wrap = match self.soft_wrap_mode(cx) {
11287                SoftWrap::GitDiff => return,
11288                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11289                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11290                    language_settings::SoftWrap::None
11291                }
11292            };
11293            self.soft_wrap_mode_override = Some(soft_wrap);
11294        }
11295        cx.notify();
11296    }
11297
11298    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11299        let Some(workspace) = self.workspace() else {
11300            return;
11301        };
11302        let fs = workspace.read(cx).app_state().fs.clone();
11303        let current_show = TabBarSettings::get_global(cx).show;
11304        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11305            setting.show = Some(!current_show);
11306        });
11307    }
11308
11309    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11310        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11311            self.buffer
11312                .read(cx)
11313                .settings_at(0, cx)
11314                .indent_guides
11315                .enabled
11316        });
11317        self.show_indent_guides = Some(!currently_enabled);
11318        cx.notify();
11319    }
11320
11321    fn should_show_indent_guides(&self) -> Option<bool> {
11322        self.show_indent_guides
11323    }
11324
11325    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11326        let mut editor_settings = EditorSettings::get_global(cx).clone();
11327        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11328        EditorSettings::override_global(editor_settings, cx);
11329    }
11330
11331    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11332        self.use_relative_line_numbers
11333            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11334    }
11335
11336    pub fn toggle_relative_line_numbers(
11337        &mut self,
11338        _: &ToggleRelativeLineNumbers,
11339        cx: &mut ViewContext<Self>,
11340    ) {
11341        let is_relative = self.should_use_relative_line_numbers(cx);
11342        self.set_relative_line_number(Some(!is_relative), cx)
11343    }
11344
11345    pub fn set_relative_line_number(
11346        &mut self,
11347        is_relative: Option<bool>,
11348        cx: &mut ViewContext<Self>,
11349    ) {
11350        self.use_relative_line_numbers = is_relative;
11351        cx.notify();
11352    }
11353
11354    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11355        self.show_gutter = show_gutter;
11356        cx.notify();
11357    }
11358
11359    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11360        self.show_scrollbars = show_scrollbars;
11361        cx.notify();
11362    }
11363
11364    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11365        self.show_line_numbers = Some(show_line_numbers);
11366        cx.notify();
11367    }
11368
11369    pub fn set_show_git_diff_gutter(
11370        &mut self,
11371        show_git_diff_gutter: bool,
11372        cx: &mut ViewContext<Self>,
11373    ) {
11374        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11375        cx.notify();
11376    }
11377
11378    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11379        self.show_code_actions = Some(show_code_actions);
11380        cx.notify();
11381    }
11382
11383    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11384        self.show_runnables = Some(show_runnables);
11385        cx.notify();
11386    }
11387
11388    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11389        if self.display_map.read(cx).masked != masked {
11390            self.display_map.update(cx, |map, _| map.masked = masked);
11391        }
11392        cx.notify()
11393    }
11394
11395    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11396        self.show_wrap_guides = Some(show_wrap_guides);
11397        cx.notify();
11398    }
11399
11400    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11401        self.show_indent_guides = Some(show_indent_guides);
11402        cx.notify();
11403    }
11404
11405    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11406        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11407            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11408                if let Some(dir) = file.abs_path(cx).parent() {
11409                    return Some(dir.to_owned());
11410                }
11411            }
11412
11413            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11414                return Some(project_path.path.to_path_buf());
11415            }
11416        }
11417
11418        None
11419    }
11420
11421    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11422        self.active_excerpt(cx)?
11423            .1
11424            .read(cx)
11425            .file()
11426            .and_then(|f| f.as_local())
11427    }
11428
11429    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11430        if let Some(target) = self.target_file(cx) {
11431            cx.reveal_path(&target.abs_path(cx));
11432        }
11433    }
11434
11435    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11436        if let Some(file) = self.target_file(cx) {
11437            if let Some(path) = file.abs_path(cx).to_str() {
11438                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11439            }
11440        }
11441    }
11442
11443    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11444        if let Some(file) = self.target_file(cx) {
11445            if let Some(path) = file.path().to_str() {
11446                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11447            }
11448        }
11449    }
11450
11451    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11452        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11453
11454        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11455            self.start_git_blame(true, cx);
11456        }
11457
11458        cx.notify();
11459    }
11460
11461    pub fn toggle_git_blame_inline(
11462        &mut self,
11463        _: &ToggleGitBlameInline,
11464        cx: &mut ViewContext<Self>,
11465    ) {
11466        self.toggle_git_blame_inline_internal(true, cx);
11467        cx.notify();
11468    }
11469
11470    pub fn git_blame_inline_enabled(&self) -> bool {
11471        self.git_blame_inline_enabled
11472    }
11473
11474    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11475        self.show_selection_menu = self
11476            .show_selection_menu
11477            .map(|show_selections_menu| !show_selections_menu)
11478            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11479
11480        cx.notify();
11481    }
11482
11483    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11484        self.show_selection_menu
11485            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11486    }
11487
11488    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11489        if let Some(project) = self.project.as_ref() {
11490            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11491                return;
11492            };
11493
11494            if buffer.read(cx).file().is_none() {
11495                return;
11496            }
11497
11498            let focused = self.focus_handle(cx).contains_focused(cx);
11499
11500            let project = project.clone();
11501            let blame =
11502                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11503            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11504            self.blame = Some(blame);
11505        }
11506    }
11507
11508    fn toggle_git_blame_inline_internal(
11509        &mut self,
11510        user_triggered: bool,
11511        cx: &mut ViewContext<Self>,
11512    ) {
11513        if self.git_blame_inline_enabled {
11514            self.git_blame_inline_enabled = false;
11515            self.show_git_blame_inline = false;
11516            self.show_git_blame_inline_delay_task.take();
11517        } else {
11518            self.git_blame_inline_enabled = true;
11519            self.start_git_blame_inline(user_triggered, cx);
11520        }
11521
11522        cx.notify();
11523    }
11524
11525    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11526        self.start_git_blame(user_triggered, cx);
11527
11528        if ProjectSettings::get_global(cx)
11529            .git
11530            .inline_blame_delay()
11531            .is_some()
11532        {
11533            self.start_inline_blame_timer(cx);
11534        } else {
11535            self.show_git_blame_inline = true
11536        }
11537    }
11538
11539    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11540        self.blame.as_ref()
11541    }
11542
11543    pub fn show_git_blame_gutter(&self) -> bool {
11544        self.show_git_blame_gutter
11545    }
11546
11547    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11548        self.show_git_blame_gutter && self.has_blame_entries(cx)
11549    }
11550
11551    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11552        self.show_git_blame_inline
11553            && self.focus_handle.is_focused(cx)
11554            && !self.newest_selection_head_on_empty_line(cx)
11555            && self.has_blame_entries(cx)
11556    }
11557
11558    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11559        self.blame()
11560            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11561    }
11562
11563    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11564        let cursor_anchor = self.selections.newest_anchor().head();
11565
11566        let snapshot = self.buffer.read(cx).snapshot(cx);
11567        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11568
11569        snapshot.line_len(buffer_row) == 0
11570    }
11571
11572    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11573        let buffer_and_selection = maybe!({
11574            let selection = self.selections.newest::<Point>(cx);
11575            let selection_range = selection.range();
11576
11577            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11578                (buffer, selection_range.start.row..selection_range.end.row)
11579            } else {
11580                let multi_buffer = self.buffer().read(cx);
11581                let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11582                let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11583
11584                let (excerpt, range) = if selection.reversed {
11585                    buffer_ranges.first()
11586                } else {
11587                    buffer_ranges.last()
11588                }?;
11589
11590                let snapshot = excerpt.buffer();
11591                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11592                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11593                (
11594                    multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11595                    selection,
11596                )
11597            };
11598
11599            Some((buffer, selection))
11600        });
11601
11602        let Some((buffer, selection)) = buffer_and_selection else {
11603            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11604        };
11605
11606        let Some(project) = self.project.as_ref() else {
11607            return Task::ready(Err(anyhow!("editor does not have project")));
11608        };
11609
11610        project.update(cx, |project, cx| {
11611            project.get_permalink_to_line(&buffer, selection, cx)
11612        })
11613    }
11614
11615    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11616        let permalink_task = self.get_permalink_to_line(cx);
11617        let workspace = self.workspace();
11618
11619        cx.spawn(|_, mut cx| async move {
11620            match permalink_task.await {
11621                Ok(permalink) => {
11622                    cx.update(|cx| {
11623                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11624                    })
11625                    .ok();
11626                }
11627                Err(err) => {
11628                    let message = format!("Failed to copy permalink: {err}");
11629
11630                    Err::<(), anyhow::Error>(err).log_err();
11631
11632                    if let Some(workspace) = workspace {
11633                        workspace
11634                            .update(&mut cx, |workspace, cx| {
11635                                struct CopyPermalinkToLine;
11636
11637                                workspace.show_toast(
11638                                    Toast::new(
11639                                        NotificationId::unique::<CopyPermalinkToLine>(),
11640                                        message,
11641                                    ),
11642                                    cx,
11643                                )
11644                            })
11645                            .ok();
11646                    }
11647                }
11648            }
11649        })
11650        .detach();
11651    }
11652
11653    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11654        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11655        if let Some(file) = self.target_file(cx) {
11656            if let Some(path) = file.path().to_str() {
11657                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11658            }
11659        }
11660    }
11661
11662    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11663        let permalink_task = self.get_permalink_to_line(cx);
11664        let workspace = self.workspace();
11665
11666        cx.spawn(|_, mut cx| async move {
11667            match permalink_task.await {
11668                Ok(permalink) => {
11669                    cx.update(|cx| {
11670                        cx.open_url(permalink.as_ref());
11671                    })
11672                    .ok();
11673                }
11674                Err(err) => {
11675                    let message = format!("Failed to open permalink: {err}");
11676
11677                    Err::<(), anyhow::Error>(err).log_err();
11678
11679                    if let Some(workspace) = workspace {
11680                        workspace
11681                            .update(&mut cx, |workspace, cx| {
11682                                struct OpenPermalinkToLine;
11683
11684                                workspace.show_toast(
11685                                    Toast::new(
11686                                        NotificationId::unique::<OpenPermalinkToLine>(),
11687                                        message,
11688                                    ),
11689                                    cx,
11690                                )
11691                            })
11692                            .ok();
11693                    }
11694                }
11695            }
11696        })
11697        .detach();
11698    }
11699
11700    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11701        self.insert_uuid(UuidVersion::V4, cx);
11702    }
11703
11704    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11705        self.insert_uuid(UuidVersion::V7, cx);
11706    }
11707
11708    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11709        self.transact(cx, |this, cx| {
11710            let edits = this
11711                .selections
11712                .all::<Point>(cx)
11713                .into_iter()
11714                .map(|selection| {
11715                    let uuid = match version {
11716                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11717                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11718                    };
11719
11720                    (selection.range(), uuid.to_string())
11721                });
11722            this.edit(edits, cx);
11723            this.refresh_inline_completion(true, false, cx);
11724        });
11725    }
11726
11727    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11728    /// last highlight added will be used.
11729    ///
11730    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11731    pub fn highlight_rows<T: 'static>(
11732        &mut self,
11733        range: Range<Anchor>,
11734        color: Hsla,
11735        should_autoscroll: bool,
11736        cx: &mut ViewContext<Self>,
11737    ) {
11738        let snapshot = self.buffer().read(cx).snapshot(cx);
11739        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11740        let ix = row_highlights.binary_search_by(|highlight| {
11741            Ordering::Equal
11742                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11743                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11744        });
11745
11746        if let Err(mut ix) = ix {
11747            let index = post_inc(&mut self.highlight_order);
11748
11749            // If this range intersects with the preceding highlight, then merge it with
11750            // the preceding highlight. Otherwise insert a new highlight.
11751            let mut merged = false;
11752            if ix > 0 {
11753                let prev_highlight = &mut row_highlights[ix - 1];
11754                if prev_highlight
11755                    .range
11756                    .end
11757                    .cmp(&range.start, &snapshot)
11758                    .is_ge()
11759                {
11760                    ix -= 1;
11761                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11762                        prev_highlight.range.end = range.end;
11763                    }
11764                    merged = true;
11765                    prev_highlight.index = index;
11766                    prev_highlight.color = color;
11767                    prev_highlight.should_autoscroll = should_autoscroll;
11768                }
11769            }
11770
11771            if !merged {
11772                row_highlights.insert(
11773                    ix,
11774                    RowHighlight {
11775                        range: range.clone(),
11776                        index,
11777                        color,
11778                        should_autoscroll,
11779                    },
11780                );
11781            }
11782
11783            // If any of the following highlights intersect with this one, merge them.
11784            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11785                let highlight = &row_highlights[ix];
11786                if next_highlight
11787                    .range
11788                    .start
11789                    .cmp(&highlight.range.end, &snapshot)
11790                    .is_le()
11791                {
11792                    if next_highlight
11793                        .range
11794                        .end
11795                        .cmp(&highlight.range.end, &snapshot)
11796                        .is_gt()
11797                    {
11798                        row_highlights[ix].range.end = next_highlight.range.end;
11799                    }
11800                    row_highlights.remove(ix + 1);
11801                } else {
11802                    break;
11803                }
11804            }
11805        }
11806    }
11807
11808    /// Remove any highlighted row ranges of the given type that intersect the
11809    /// given ranges.
11810    pub fn remove_highlighted_rows<T: 'static>(
11811        &mut self,
11812        ranges_to_remove: Vec<Range<Anchor>>,
11813        cx: &mut ViewContext<Self>,
11814    ) {
11815        let snapshot = self.buffer().read(cx).snapshot(cx);
11816        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11817        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11818        row_highlights.retain(|highlight| {
11819            while let Some(range_to_remove) = ranges_to_remove.peek() {
11820                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11821                    Ordering::Less | Ordering::Equal => {
11822                        ranges_to_remove.next();
11823                    }
11824                    Ordering::Greater => {
11825                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11826                            Ordering::Less | Ordering::Equal => {
11827                                return false;
11828                            }
11829                            Ordering::Greater => break,
11830                        }
11831                    }
11832                }
11833            }
11834
11835            true
11836        })
11837    }
11838
11839    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11840    pub fn clear_row_highlights<T: 'static>(&mut self) {
11841        self.highlighted_rows.remove(&TypeId::of::<T>());
11842    }
11843
11844    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11845    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11846        self.highlighted_rows
11847            .get(&TypeId::of::<T>())
11848            .map_or(&[] as &[_], |vec| vec.as_slice())
11849            .iter()
11850            .map(|highlight| (highlight.range.clone(), highlight.color))
11851    }
11852
11853    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11854    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11855    /// Allows to ignore certain kinds of highlights.
11856    pub fn highlighted_display_rows(
11857        &mut self,
11858        cx: &mut WindowContext,
11859    ) -> BTreeMap<DisplayRow, Hsla> {
11860        let snapshot = self.snapshot(cx);
11861        let mut used_highlight_orders = HashMap::default();
11862        self.highlighted_rows
11863            .iter()
11864            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11865            .fold(
11866                BTreeMap::<DisplayRow, Hsla>::new(),
11867                |mut unique_rows, highlight| {
11868                    let start = highlight.range.start.to_display_point(&snapshot);
11869                    let end = highlight.range.end.to_display_point(&snapshot);
11870                    let start_row = start.row().0;
11871                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11872                        && end.column() == 0
11873                    {
11874                        end.row().0.saturating_sub(1)
11875                    } else {
11876                        end.row().0
11877                    };
11878                    for row in start_row..=end_row {
11879                        let used_index =
11880                            used_highlight_orders.entry(row).or_insert(highlight.index);
11881                        if highlight.index >= *used_index {
11882                            *used_index = highlight.index;
11883                            unique_rows.insert(DisplayRow(row), highlight.color);
11884                        }
11885                    }
11886                    unique_rows
11887                },
11888            )
11889    }
11890
11891    pub fn highlighted_display_row_for_autoscroll(
11892        &self,
11893        snapshot: &DisplaySnapshot,
11894    ) -> Option<DisplayRow> {
11895        self.highlighted_rows
11896            .values()
11897            .flat_map(|highlighted_rows| highlighted_rows.iter())
11898            .filter_map(|highlight| {
11899                if highlight.should_autoscroll {
11900                    Some(highlight.range.start.to_display_point(snapshot).row())
11901                } else {
11902                    None
11903                }
11904            })
11905            .min()
11906    }
11907
11908    pub fn set_search_within_ranges(
11909        &mut self,
11910        ranges: &[Range<Anchor>],
11911        cx: &mut ViewContext<Self>,
11912    ) {
11913        self.highlight_background::<SearchWithinRange>(
11914            ranges,
11915            |colors| colors.editor_document_highlight_read_background,
11916            cx,
11917        )
11918    }
11919
11920    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11921        self.breadcrumb_header = Some(new_header);
11922    }
11923
11924    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11925        self.clear_background_highlights::<SearchWithinRange>(cx);
11926    }
11927
11928    pub fn highlight_background<T: 'static>(
11929        &mut self,
11930        ranges: &[Range<Anchor>],
11931        color_fetcher: fn(&ThemeColors) -> Hsla,
11932        cx: &mut ViewContext<Self>,
11933    ) {
11934        self.background_highlights
11935            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11936        self.scrollbar_marker_state.dirty = true;
11937        cx.notify();
11938    }
11939
11940    pub fn clear_background_highlights<T: 'static>(
11941        &mut self,
11942        cx: &mut ViewContext<Self>,
11943    ) -> Option<BackgroundHighlight> {
11944        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11945        if !text_highlights.1.is_empty() {
11946            self.scrollbar_marker_state.dirty = true;
11947            cx.notify();
11948        }
11949        Some(text_highlights)
11950    }
11951
11952    pub fn highlight_gutter<T: 'static>(
11953        &mut self,
11954        ranges: &[Range<Anchor>],
11955        color_fetcher: fn(&AppContext) -> Hsla,
11956        cx: &mut ViewContext<Self>,
11957    ) {
11958        self.gutter_highlights
11959            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11960        cx.notify();
11961    }
11962
11963    pub fn clear_gutter_highlights<T: 'static>(
11964        &mut self,
11965        cx: &mut ViewContext<Self>,
11966    ) -> Option<GutterHighlight> {
11967        cx.notify();
11968        self.gutter_highlights.remove(&TypeId::of::<T>())
11969    }
11970
11971    #[cfg(feature = "test-support")]
11972    pub fn all_text_background_highlights(
11973        &mut self,
11974        cx: &mut ViewContext<Self>,
11975    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11976        let snapshot = self.snapshot(cx);
11977        let buffer = &snapshot.buffer_snapshot;
11978        let start = buffer.anchor_before(0);
11979        let end = buffer.anchor_after(buffer.len());
11980        let theme = cx.theme().colors();
11981        self.background_highlights_in_range(start..end, &snapshot, theme)
11982    }
11983
11984    #[cfg(feature = "test-support")]
11985    pub fn search_background_highlights(
11986        &mut self,
11987        cx: &mut ViewContext<Self>,
11988    ) -> Vec<Range<Point>> {
11989        let snapshot = self.buffer().read(cx).snapshot(cx);
11990
11991        let highlights = self
11992            .background_highlights
11993            .get(&TypeId::of::<items::BufferSearchHighlights>());
11994
11995        if let Some((_color, ranges)) = highlights {
11996            ranges
11997                .iter()
11998                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11999                .collect_vec()
12000        } else {
12001            vec![]
12002        }
12003    }
12004
12005    fn document_highlights_for_position<'a>(
12006        &'a self,
12007        position: Anchor,
12008        buffer: &'a MultiBufferSnapshot,
12009    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
12010        let read_highlights = self
12011            .background_highlights
12012            .get(&TypeId::of::<DocumentHighlightRead>())
12013            .map(|h| &h.1);
12014        let write_highlights = self
12015            .background_highlights
12016            .get(&TypeId::of::<DocumentHighlightWrite>())
12017            .map(|h| &h.1);
12018        let left_position = position.bias_left(buffer);
12019        let right_position = position.bias_right(buffer);
12020        read_highlights
12021            .into_iter()
12022            .chain(write_highlights)
12023            .flat_map(move |ranges| {
12024                let start_ix = match ranges.binary_search_by(|probe| {
12025                    let cmp = probe.end.cmp(&left_position, buffer);
12026                    if cmp.is_ge() {
12027                        Ordering::Greater
12028                    } else {
12029                        Ordering::Less
12030                    }
12031                }) {
12032                    Ok(i) | Err(i) => i,
12033                };
12034
12035                ranges[start_ix..]
12036                    .iter()
12037                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12038            })
12039    }
12040
12041    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12042        self.background_highlights
12043            .get(&TypeId::of::<T>())
12044            .map_or(false, |(_, highlights)| !highlights.is_empty())
12045    }
12046
12047    pub fn background_highlights_in_range(
12048        &self,
12049        search_range: Range<Anchor>,
12050        display_snapshot: &DisplaySnapshot,
12051        theme: &ThemeColors,
12052    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12053        let mut results = Vec::new();
12054        for (color_fetcher, ranges) in self.background_highlights.values() {
12055            let color = color_fetcher(theme);
12056            let start_ix = match ranges.binary_search_by(|probe| {
12057                let cmp = probe
12058                    .end
12059                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12060                if cmp.is_gt() {
12061                    Ordering::Greater
12062                } else {
12063                    Ordering::Less
12064                }
12065            }) {
12066                Ok(i) | Err(i) => i,
12067            };
12068            for range in &ranges[start_ix..] {
12069                if range
12070                    .start
12071                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12072                    .is_ge()
12073                {
12074                    break;
12075                }
12076
12077                let start = range.start.to_display_point(display_snapshot);
12078                let end = range.end.to_display_point(display_snapshot);
12079                results.push((start..end, color))
12080            }
12081        }
12082        results
12083    }
12084
12085    pub fn background_highlight_row_ranges<T: 'static>(
12086        &self,
12087        search_range: Range<Anchor>,
12088        display_snapshot: &DisplaySnapshot,
12089        count: usize,
12090    ) -> Vec<RangeInclusive<DisplayPoint>> {
12091        let mut results = Vec::new();
12092        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12093            return vec![];
12094        };
12095
12096        let start_ix = match ranges.binary_search_by(|probe| {
12097            let cmp = probe
12098                .end
12099                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12100            if cmp.is_gt() {
12101                Ordering::Greater
12102            } else {
12103                Ordering::Less
12104            }
12105        }) {
12106            Ok(i) | Err(i) => i,
12107        };
12108        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12109            if let (Some(start_display), Some(end_display)) = (start, end) {
12110                results.push(
12111                    start_display.to_display_point(display_snapshot)
12112                        ..=end_display.to_display_point(display_snapshot),
12113                );
12114            }
12115        };
12116        let mut start_row: Option<Point> = None;
12117        let mut end_row: Option<Point> = None;
12118        if ranges.len() > count {
12119            return Vec::new();
12120        }
12121        for range in &ranges[start_ix..] {
12122            if range
12123                .start
12124                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12125                .is_ge()
12126            {
12127                break;
12128            }
12129            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12130            if let Some(current_row) = &end_row {
12131                if end.row == current_row.row {
12132                    continue;
12133                }
12134            }
12135            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12136            if start_row.is_none() {
12137                assert_eq!(end_row, None);
12138                start_row = Some(start);
12139                end_row = Some(end);
12140                continue;
12141            }
12142            if let Some(current_end) = end_row.as_mut() {
12143                if start.row > current_end.row + 1 {
12144                    push_region(start_row, end_row);
12145                    start_row = Some(start);
12146                    end_row = Some(end);
12147                } else {
12148                    // Merge two hunks.
12149                    *current_end = end;
12150                }
12151            } else {
12152                unreachable!();
12153            }
12154        }
12155        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12156        push_region(start_row, end_row);
12157        results
12158    }
12159
12160    pub fn gutter_highlights_in_range(
12161        &self,
12162        search_range: Range<Anchor>,
12163        display_snapshot: &DisplaySnapshot,
12164        cx: &AppContext,
12165    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12166        let mut results = Vec::new();
12167        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12168            let color = color_fetcher(cx);
12169            let start_ix = match ranges.binary_search_by(|probe| {
12170                let cmp = probe
12171                    .end
12172                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12173                if cmp.is_gt() {
12174                    Ordering::Greater
12175                } else {
12176                    Ordering::Less
12177                }
12178            }) {
12179                Ok(i) | Err(i) => i,
12180            };
12181            for range in &ranges[start_ix..] {
12182                if range
12183                    .start
12184                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12185                    .is_ge()
12186                {
12187                    break;
12188                }
12189
12190                let start = range.start.to_display_point(display_snapshot);
12191                let end = range.end.to_display_point(display_snapshot);
12192                results.push((start..end, color))
12193            }
12194        }
12195        results
12196    }
12197
12198    /// Get the text ranges corresponding to the redaction query
12199    pub fn redacted_ranges(
12200        &self,
12201        search_range: Range<Anchor>,
12202        display_snapshot: &DisplaySnapshot,
12203        cx: &WindowContext,
12204    ) -> Vec<Range<DisplayPoint>> {
12205        display_snapshot
12206            .buffer_snapshot
12207            .redacted_ranges(search_range, |file| {
12208                if let Some(file) = file {
12209                    file.is_private()
12210                        && EditorSettings::get(
12211                            Some(SettingsLocation {
12212                                worktree_id: file.worktree_id(cx),
12213                                path: file.path().as_ref(),
12214                            }),
12215                            cx,
12216                        )
12217                        .redact_private_values
12218                } else {
12219                    false
12220                }
12221            })
12222            .map(|range| {
12223                range.start.to_display_point(display_snapshot)
12224                    ..range.end.to_display_point(display_snapshot)
12225            })
12226            .collect()
12227    }
12228
12229    pub fn highlight_text<T: 'static>(
12230        &mut self,
12231        ranges: Vec<Range<Anchor>>,
12232        style: HighlightStyle,
12233        cx: &mut ViewContext<Self>,
12234    ) {
12235        self.display_map.update(cx, |map, _| {
12236            map.highlight_text(TypeId::of::<T>(), ranges, style)
12237        });
12238        cx.notify();
12239    }
12240
12241    pub(crate) fn highlight_inlays<T: 'static>(
12242        &mut self,
12243        highlights: Vec<InlayHighlight>,
12244        style: HighlightStyle,
12245        cx: &mut ViewContext<Self>,
12246    ) {
12247        self.display_map.update(cx, |map, _| {
12248            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12249        });
12250        cx.notify();
12251    }
12252
12253    pub fn text_highlights<'a, T: 'static>(
12254        &'a self,
12255        cx: &'a AppContext,
12256    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12257        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12258    }
12259
12260    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12261        let cleared = self
12262            .display_map
12263            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12264        if cleared {
12265            cx.notify();
12266        }
12267    }
12268
12269    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12270        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12271            && self.focus_handle.is_focused(cx)
12272    }
12273
12274    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12275        self.show_cursor_when_unfocused = is_enabled;
12276        cx.notify();
12277    }
12278
12279    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12280        self.project
12281            .as_ref()
12282            .map(|project| project.read(cx).lsp_store())
12283    }
12284
12285    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12286        cx.notify();
12287    }
12288
12289    fn on_buffer_event(
12290        &mut self,
12291        multibuffer: Model<MultiBuffer>,
12292        event: &multi_buffer::Event,
12293        cx: &mut ViewContext<Self>,
12294    ) {
12295        match event {
12296            multi_buffer::Event::Edited {
12297                singleton_buffer_edited,
12298                edited_buffer: buffer_edited,
12299            } => {
12300                self.scrollbar_marker_state.dirty = true;
12301                self.active_indent_guides_state.dirty = true;
12302                self.refresh_active_diagnostics(cx);
12303                self.refresh_code_actions(cx);
12304                if self.has_active_inline_completion() {
12305                    self.update_visible_inline_completion(cx);
12306                }
12307                if let Some(buffer) = buffer_edited {
12308                    let buffer_id = buffer.read(cx).remote_id();
12309                    if !self.registered_buffers.contains_key(&buffer_id) {
12310                        if let Some(lsp_store) = self.lsp_store(cx) {
12311                            lsp_store.update(cx, |lsp_store, cx| {
12312                                self.registered_buffers.insert(
12313                                    buffer_id,
12314                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12315                                );
12316                            })
12317                        }
12318                    }
12319                }
12320                cx.emit(EditorEvent::BufferEdited);
12321                cx.emit(SearchEvent::MatchesInvalidated);
12322                if *singleton_buffer_edited {
12323                    if let Some(project) = &self.project {
12324                        let project = project.read(cx);
12325                        #[allow(clippy::mutable_key_type)]
12326                        let languages_affected = multibuffer
12327                            .read(cx)
12328                            .all_buffers()
12329                            .into_iter()
12330                            .filter_map(|buffer| {
12331                                let buffer = buffer.read(cx);
12332                                let language = buffer.language()?;
12333                                if project.is_local()
12334                                    && project
12335                                        .language_servers_for_local_buffer(buffer, cx)
12336                                        .count()
12337                                        == 0
12338                                {
12339                                    None
12340                                } else {
12341                                    Some(language)
12342                                }
12343                            })
12344                            .cloned()
12345                            .collect::<HashSet<_>>();
12346                        if !languages_affected.is_empty() {
12347                            self.refresh_inlay_hints(
12348                                InlayHintRefreshReason::BufferEdited(languages_affected),
12349                                cx,
12350                            );
12351                        }
12352                    }
12353                }
12354
12355                let Some(project) = &self.project else { return };
12356                let (telemetry, is_via_ssh) = {
12357                    let project = project.read(cx);
12358                    let telemetry = project.client().telemetry().clone();
12359                    let is_via_ssh = project.is_via_ssh();
12360                    (telemetry, is_via_ssh)
12361                };
12362                refresh_linked_ranges(self, cx);
12363                telemetry.log_edit_event("editor", is_via_ssh);
12364            }
12365            multi_buffer::Event::ExcerptsAdded {
12366                buffer,
12367                predecessor,
12368                excerpts,
12369            } => {
12370                self.tasks_update_task = Some(self.refresh_runnables(cx));
12371                let buffer_id = buffer.read(cx).remote_id();
12372                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12373                    if let Some(project) = &self.project {
12374                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12375                    }
12376                }
12377                cx.emit(EditorEvent::ExcerptsAdded {
12378                    buffer: buffer.clone(),
12379                    predecessor: *predecessor,
12380                    excerpts: excerpts.clone(),
12381                });
12382                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12383            }
12384            multi_buffer::Event::ExcerptsRemoved { ids } => {
12385                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12386                let buffer = self.buffer.read(cx);
12387                self.registered_buffers
12388                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12389                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12390            }
12391            multi_buffer::Event::ExcerptsEdited { ids } => {
12392                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12393            }
12394            multi_buffer::Event::ExcerptsExpanded { ids } => {
12395                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12396            }
12397            multi_buffer::Event::Reparsed(buffer_id) => {
12398                self.tasks_update_task = Some(self.refresh_runnables(cx));
12399
12400                cx.emit(EditorEvent::Reparsed(*buffer_id));
12401            }
12402            multi_buffer::Event::LanguageChanged(buffer_id) => {
12403                linked_editing_ranges::refresh_linked_ranges(self, cx);
12404                cx.emit(EditorEvent::Reparsed(*buffer_id));
12405                cx.notify();
12406            }
12407            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12408            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12409            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12410                cx.emit(EditorEvent::TitleChanged)
12411            }
12412            // multi_buffer::Event::DiffBaseChanged => {
12413            //     self.scrollbar_marker_state.dirty = true;
12414            //     cx.emit(EditorEvent::DiffBaseChanged);
12415            //     cx.notify();
12416            // }
12417            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12418            multi_buffer::Event::DiagnosticsUpdated => {
12419                self.refresh_active_diagnostics(cx);
12420                self.scrollbar_marker_state.dirty = true;
12421                cx.notify();
12422            }
12423            _ => {}
12424        };
12425    }
12426
12427    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12428        cx.notify();
12429    }
12430
12431    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12432        self.tasks_update_task = Some(self.refresh_runnables(cx));
12433        self.refresh_inline_completion(true, false, cx);
12434        self.refresh_inlay_hints(
12435            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12436                self.selections.newest_anchor().head(),
12437                &self.buffer.read(cx).snapshot(cx),
12438                cx,
12439            )),
12440            cx,
12441        );
12442
12443        let old_cursor_shape = self.cursor_shape;
12444
12445        {
12446            let editor_settings = EditorSettings::get_global(cx);
12447            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12448            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12449            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12450        }
12451
12452        if old_cursor_shape != self.cursor_shape {
12453            cx.emit(EditorEvent::CursorShapeChanged);
12454        }
12455
12456        let project_settings = ProjectSettings::get_global(cx);
12457        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12458
12459        if self.mode == EditorMode::Full {
12460            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12461            if self.git_blame_inline_enabled != inline_blame_enabled {
12462                self.toggle_git_blame_inline_internal(false, cx);
12463            }
12464        }
12465
12466        cx.notify();
12467    }
12468
12469    pub fn set_searchable(&mut self, searchable: bool) {
12470        self.searchable = searchable;
12471    }
12472
12473    pub fn searchable(&self) -> bool {
12474        self.searchable
12475    }
12476
12477    fn open_proposed_changes_editor(
12478        &mut self,
12479        _: &OpenProposedChangesEditor,
12480        cx: &mut ViewContext<Self>,
12481    ) {
12482        let Some(workspace) = self.workspace() else {
12483            cx.propagate();
12484            return;
12485        };
12486
12487        let selections = self.selections.all::<usize>(cx);
12488        let multi_buffer = self.buffer.read(cx);
12489        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12490        let mut new_selections_by_buffer = HashMap::default();
12491        for selection in selections {
12492            for (excerpt, range) in
12493                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12494            {
12495                let mut range = range.to_point(excerpt.buffer());
12496                range.start.column = 0;
12497                range.end.column = excerpt.buffer().line_len(range.end.row);
12498                new_selections_by_buffer
12499                    .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12500                    .or_insert(Vec::new())
12501                    .push(range)
12502            }
12503        }
12504
12505        let proposed_changes_buffers = new_selections_by_buffer
12506            .into_iter()
12507            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12508            .collect::<Vec<_>>();
12509        let proposed_changes_editor = cx.new_view(|cx| {
12510            ProposedChangesEditor::new(
12511                "Proposed changes",
12512                proposed_changes_buffers,
12513                self.project.clone(),
12514                cx,
12515            )
12516        });
12517
12518        cx.window_context().defer(move |cx| {
12519            workspace.update(cx, |workspace, cx| {
12520                workspace.active_pane().update(cx, |pane, cx| {
12521                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12522                });
12523            });
12524        });
12525    }
12526
12527    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12528        self.open_excerpts_common(None, true, cx)
12529    }
12530
12531    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12532        self.open_excerpts_common(None, false, cx)
12533    }
12534
12535    fn open_excerpts_common(
12536        &mut self,
12537        jump_data: Option<JumpData>,
12538        split: bool,
12539        cx: &mut ViewContext<Self>,
12540    ) {
12541        let Some(workspace) = self.workspace() else {
12542            cx.propagate();
12543            return;
12544        };
12545
12546        if self.buffer.read(cx).is_singleton() {
12547            cx.propagate();
12548            return;
12549        }
12550
12551        let mut new_selections_by_buffer = HashMap::default();
12552        match &jump_data {
12553            Some(JumpData::MultiBufferPoint {
12554                excerpt_id,
12555                position,
12556                anchor,
12557                line_offset_from_top,
12558            }) => {
12559                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12560                if let Some(buffer) = multi_buffer_snapshot
12561                    .buffer_id_for_excerpt(*excerpt_id)
12562                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12563                {
12564                    let buffer_snapshot = buffer.read(cx).snapshot();
12565                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12566                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12567                    } else {
12568                        buffer_snapshot.clip_point(*position, Bias::Left)
12569                    };
12570                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12571                    new_selections_by_buffer.insert(
12572                        buffer,
12573                        (
12574                            vec![jump_to_offset..jump_to_offset],
12575                            Some(*line_offset_from_top),
12576                        ),
12577                    );
12578                }
12579            }
12580            Some(JumpData::MultiBufferRow {
12581                row,
12582                line_offset_from_top,
12583            }) => {
12584                let point = MultiBufferPoint::new(row.0, 0);
12585                if let Some((buffer, buffer_point, _)) =
12586                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12587                {
12588                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12589                    new_selections_by_buffer
12590                        .entry(buffer)
12591                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12592                        .0
12593                        .push(buffer_offset..buffer_offset)
12594                }
12595            }
12596            None => {
12597                let selections = self.selections.all::<usize>(cx);
12598                let multi_buffer = self.buffer.read(cx);
12599                for selection in selections {
12600                    for (excerpt, mut range) in multi_buffer
12601                        .snapshot(cx)
12602                        .range_to_buffer_ranges(selection.range())
12603                    {
12604                        // When editing branch buffers, jump to the corresponding location
12605                        // in their base buffer.
12606                        let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12607                        let buffer = buffer_handle.read(cx);
12608                        if let Some(base_buffer) = buffer.base_buffer() {
12609                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12610                            buffer_handle = base_buffer;
12611                        }
12612
12613                        if selection.reversed {
12614                            mem::swap(&mut range.start, &mut range.end);
12615                        }
12616                        new_selections_by_buffer
12617                            .entry(buffer_handle)
12618                            .or_insert((Vec::new(), None))
12619                            .0
12620                            .push(range)
12621                    }
12622                }
12623            }
12624        }
12625
12626        if new_selections_by_buffer.is_empty() {
12627            return;
12628        }
12629
12630        // We defer the pane interaction because we ourselves are a workspace item
12631        // and activating a new item causes the pane to call a method on us reentrantly,
12632        // which panics if we're on the stack.
12633        cx.window_context().defer(move |cx| {
12634            workspace.update(cx, |workspace, cx| {
12635                let pane = if split {
12636                    workspace.adjacent_pane(cx)
12637                } else {
12638                    workspace.active_pane().clone()
12639                };
12640
12641                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12642                    let editor = buffer
12643                        .read(cx)
12644                        .file()
12645                        .is_none()
12646                        .then(|| {
12647                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12648                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12649                            // Instead, we try to activate the existing editor in the pane first.
12650                            let (editor, pane_item_index) =
12651                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12652                                    let editor = item.downcast::<Editor>()?;
12653                                    let singleton_buffer =
12654                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12655                                    if singleton_buffer == buffer {
12656                                        Some((editor, i))
12657                                    } else {
12658                                        None
12659                                    }
12660                                })?;
12661                            pane.update(cx, |pane, cx| {
12662                                pane.activate_item(pane_item_index, true, true, cx)
12663                            });
12664                            Some(editor)
12665                        })
12666                        .flatten()
12667                        .unwrap_or_else(|| {
12668                            workspace.open_project_item::<Self>(
12669                                pane.clone(),
12670                                buffer,
12671                                true,
12672                                true,
12673                                cx,
12674                            )
12675                        });
12676
12677                    editor.update(cx, |editor, cx| {
12678                        let autoscroll = match scroll_offset {
12679                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12680                            None => Autoscroll::newest(),
12681                        };
12682                        let nav_history = editor.nav_history.take();
12683                        editor.change_selections(Some(autoscroll), cx, |s| {
12684                            s.select_ranges(ranges);
12685                        });
12686                        editor.nav_history = nav_history;
12687                    });
12688                }
12689            })
12690        });
12691    }
12692
12693    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12694        let snapshot = self.buffer.read(cx).read(cx);
12695        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12696        Some(
12697            ranges
12698                .iter()
12699                .map(move |range| {
12700                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12701                })
12702                .collect(),
12703        )
12704    }
12705
12706    fn selection_replacement_ranges(
12707        &self,
12708        range: Range<OffsetUtf16>,
12709        cx: &mut AppContext,
12710    ) -> Vec<Range<OffsetUtf16>> {
12711        let selections = self.selections.all::<OffsetUtf16>(cx);
12712        let newest_selection = selections
12713            .iter()
12714            .max_by_key(|selection| selection.id)
12715            .unwrap();
12716        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12717        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12718        let snapshot = self.buffer.read(cx).read(cx);
12719        selections
12720            .into_iter()
12721            .map(|mut selection| {
12722                selection.start.0 =
12723                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12724                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12725                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12726                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12727            })
12728            .collect()
12729    }
12730
12731    fn report_editor_event(
12732        &self,
12733        event_type: &'static str,
12734        file_extension: Option<String>,
12735        cx: &AppContext,
12736    ) {
12737        if cfg!(any(test, feature = "test-support")) {
12738            return;
12739        }
12740
12741        let Some(project) = &self.project else { return };
12742
12743        // If None, we are in a file without an extension
12744        let file = self
12745            .buffer
12746            .read(cx)
12747            .as_singleton()
12748            .and_then(|b| b.read(cx).file());
12749        let file_extension = file_extension.or(file
12750            .as_ref()
12751            .and_then(|file| Path::new(file.file_name(cx)).extension())
12752            .and_then(|e| e.to_str())
12753            .map(|a| a.to_string()));
12754
12755        let vim_mode = cx
12756            .global::<SettingsStore>()
12757            .raw_user_settings()
12758            .get("vim_mode")
12759            == Some(&serde_json::Value::Bool(true));
12760
12761        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12762            == language::language_settings::InlineCompletionProvider::Copilot;
12763        let copilot_enabled_for_language = self
12764            .buffer
12765            .read(cx)
12766            .settings_at(0, cx)
12767            .show_inline_completions;
12768
12769        let project = project.read(cx);
12770        telemetry::event!(
12771            event_type,
12772            file_extension,
12773            vim_mode,
12774            copilot_enabled,
12775            copilot_enabled_for_language,
12776            is_via_ssh = project.is_via_ssh(),
12777        );
12778    }
12779
12780    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12781    /// with each line being an array of {text, highlight} objects.
12782    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12783        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12784            return;
12785        };
12786
12787        #[derive(Serialize)]
12788        struct Chunk<'a> {
12789            text: String,
12790            highlight: Option<&'a str>,
12791        }
12792
12793        let snapshot = buffer.read(cx).snapshot();
12794        let range = self
12795            .selected_text_range(false, cx)
12796            .and_then(|selection| {
12797                if selection.range.is_empty() {
12798                    None
12799                } else {
12800                    Some(selection.range)
12801                }
12802            })
12803            .unwrap_or_else(|| 0..snapshot.len());
12804
12805        let chunks = snapshot.chunks(range, true);
12806        let mut lines = Vec::new();
12807        let mut line: VecDeque<Chunk> = VecDeque::new();
12808
12809        let Some(style) = self.style.as_ref() else {
12810            return;
12811        };
12812
12813        for chunk in chunks {
12814            let highlight = chunk
12815                .syntax_highlight_id
12816                .and_then(|id| id.name(&style.syntax));
12817            let mut chunk_lines = chunk.text.split('\n').peekable();
12818            while let Some(text) = chunk_lines.next() {
12819                let mut merged_with_last_token = false;
12820                if let Some(last_token) = line.back_mut() {
12821                    if last_token.highlight == highlight {
12822                        last_token.text.push_str(text);
12823                        merged_with_last_token = true;
12824                    }
12825                }
12826
12827                if !merged_with_last_token {
12828                    line.push_back(Chunk {
12829                        text: text.into(),
12830                        highlight,
12831                    });
12832                }
12833
12834                if chunk_lines.peek().is_some() {
12835                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12836                        line.pop_front();
12837                    }
12838                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12839                        line.pop_back();
12840                    }
12841
12842                    lines.push(mem::take(&mut line));
12843                }
12844            }
12845        }
12846
12847        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12848            return;
12849        };
12850        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12851    }
12852
12853    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12854        self.request_autoscroll(Autoscroll::newest(), cx);
12855        let position = self.selections.newest_display(cx).start;
12856        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12857    }
12858
12859    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12860        &self.inlay_hint_cache
12861    }
12862
12863    pub fn replay_insert_event(
12864        &mut self,
12865        text: &str,
12866        relative_utf16_range: Option<Range<isize>>,
12867        cx: &mut ViewContext<Self>,
12868    ) {
12869        if !self.input_enabled {
12870            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12871            return;
12872        }
12873        if let Some(relative_utf16_range) = relative_utf16_range {
12874            let selections = self.selections.all::<OffsetUtf16>(cx);
12875            self.change_selections(None, cx, |s| {
12876                let new_ranges = selections.into_iter().map(|range| {
12877                    let start = OffsetUtf16(
12878                        range
12879                            .head()
12880                            .0
12881                            .saturating_add_signed(relative_utf16_range.start),
12882                    );
12883                    let end = OffsetUtf16(
12884                        range
12885                            .head()
12886                            .0
12887                            .saturating_add_signed(relative_utf16_range.end),
12888                    );
12889                    start..end
12890                });
12891                s.select_ranges(new_ranges);
12892            });
12893        }
12894
12895        self.handle_input(text, cx);
12896    }
12897
12898    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12899        let Some(provider) = self.semantics_provider.as_ref() else {
12900            return false;
12901        };
12902
12903        let mut supports = false;
12904        self.buffer().read(cx).for_each_buffer(|buffer| {
12905            supports |= provider.supports_inlay_hints(buffer, cx);
12906        });
12907        supports
12908    }
12909
12910    pub fn focus(&self, cx: &mut WindowContext) {
12911        cx.focus(&self.focus_handle)
12912    }
12913
12914    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12915        self.focus_handle.is_focused(cx)
12916    }
12917
12918    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12919        cx.emit(EditorEvent::Focused);
12920
12921        if let Some(descendant) = self
12922            .last_focused_descendant
12923            .take()
12924            .and_then(|descendant| descendant.upgrade())
12925        {
12926            cx.focus(&descendant);
12927        } else {
12928            if let Some(blame) = self.blame.as_ref() {
12929                blame.update(cx, GitBlame::focus)
12930            }
12931
12932            self.blink_manager.update(cx, BlinkManager::enable);
12933            self.show_cursor_names(cx);
12934            self.buffer.update(cx, |buffer, cx| {
12935                buffer.finalize_last_transaction(cx);
12936                if self.leader_peer_id.is_none() {
12937                    buffer.set_active_selections(
12938                        &self.selections.disjoint_anchors(),
12939                        self.selections.line_mode,
12940                        self.cursor_shape,
12941                        cx,
12942                    );
12943                }
12944            });
12945        }
12946    }
12947
12948    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12949        cx.emit(EditorEvent::FocusedIn)
12950    }
12951
12952    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12953        if event.blurred != self.focus_handle {
12954            self.last_focused_descendant = Some(event.blurred);
12955        }
12956    }
12957
12958    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12959        self.blink_manager.update(cx, BlinkManager::disable);
12960        self.buffer
12961            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12962
12963        if let Some(blame) = self.blame.as_ref() {
12964            blame.update(cx, GitBlame::blur)
12965        }
12966        if !self.hover_state.focused(cx) {
12967            hide_hover(self, cx);
12968        }
12969
12970        self.hide_context_menu(cx);
12971        cx.emit(EditorEvent::Blurred);
12972        cx.notify();
12973    }
12974
12975    pub fn register_action<A: Action>(
12976        &mut self,
12977        listener: impl Fn(&A, &mut WindowContext) + 'static,
12978    ) -> Subscription {
12979        let id = self.next_editor_action_id.post_inc();
12980        let listener = Arc::new(listener);
12981        self.editor_actions.borrow_mut().insert(
12982            id,
12983            Box::new(move |cx| {
12984                let cx = cx.window_context();
12985                let listener = listener.clone();
12986                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12987                    let action = action.downcast_ref().unwrap();
12988                    if phase == DispatchPhase::Bubble {
12989                        listener(action, cx)
12990                    }
12991                })
12992            }),
12993        );
12994
12995        let editor_actions = self.editor_actions.clone();
12996        Subscription::new(move || {
12997            editor_actions.borrow_mut().remove(&id);
12998        })
12999    }
13000
13001    pub fn file_header_size(&self) -> u32 {
13002        FILE_HEADER_HEIGHT
13003    }
13004
13005    pub fn revert(
13006        &mut self,
13007        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
13008        cx: &mut ViewContext<Self>,
13009    ) {
13010        self.buffer().update(cx, |multi_buffer, cx| {
13011            for (buffer_id, changes) in revert_changes {
13012                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
13013                    buffer.update(cx, |buffer, cx| {
13014                        buffer.edit(
13015                            changes.into_iter().map(|(range, text)| {
13016                                (range, text.to_string().map(Arc::<str>::from))
13017                            }),
13018                            None,
13019                            cx,
13020                        );
13021                    });
13022                }
13023            }
13024        });
13025        self.change_selections(None, cx, |selections| selections.refresh());
13026    }
13027
13028    pub fn to_pixel_point(
13029        &mut self,
13030        source: multi_buffer::Anchor,
13031        editor_snapshot: &EditorSnapshot,
13032        cx: &mut ViewContext<Self>,
13033    ) -> Option<gpui::Point<Pixels>> {
13034        let source_point = source.to_display_point(editor_snapshot);
13035        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13036    }
13037
13038    pub fn display_to_pixel_point(
13039        &self,
13040        source: DisplayPoint,
13041        editor_snapshot: &EditorSnapshot,
13042        cx: &WindowContext,
13043    ) -> Option<gpui::Point<Pixels>> {
13044        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13045        let text_layout_details = self.text_layout_details(cx);
13046        let scroll_top = text_layout_details
13047            .scroll_anchor
13048            .scroll_position(editor_snapshot)
13049            .y;
13050
13051        if source.row().as_f32() < scroll_top.floor() {
13052            return None;
13053        }
13054        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13055        let source_y = line_height * (source.row().as_f32() - scroll_top);
13056        Some(gpui::Point::new(source_x, source_y))
13057    }
13058
13059    pub fn has_active_completions_menu(&self) -> bool {
13060        self.context_menu.borrow().as_ref().map_or(false, |menu| {
13061            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13062        })
13063    }
13064
13065    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13066        self.addons
13067            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13068    }
13069
13070    pub fn unregister_addon<T: Addon>(&mut self) {
13071        self.addons.remove(&std::any::TypeId::of::<T>());
13072    }
13073
13074    pub fn addon<T: Addon>(&self) -> Option<&T> {
13075        let type_id = std::any::TypeId::of::<T>();
13076        self.addons
13077            .get(&type_id)
13078            .and_then(|item| item.to_any().downcast_ref::<T>())
13079    }
13080
13081    pub fn add_change_set(
13082        &mut self,
13083        change_set: Model<BufferChangeSet>,
13084        cx: &mut ViewContext<Self>,
13085    ) {
13086        self.diff_map.add_change_set(change_set, cx);
13087    }
13088
13089    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13090        let text_layout_details = self.text_layout_details(cx);
13091        let style = &text_layout_details.editor_style;
13092        let font_id = cx.text_system().resolve_font(&style.text.font());
13093        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13094        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13095
13096        let em_width = cx
13097            .text_system()
13098            .typographic_bounds(font_id, font_size, 'm')
13099            .unwrap()
13100            .size
13101            .width;
13102
13103        gpui::Point::new(em_width, line_height)
13104    }
13105}
13106
13107fn get_unstaged_changes_for_buffers(
13108    project: &Model<Project>,
13109    buffers: impl IntoIterator<Item = Model<Buffer>>,
13110    cx: &mut ViewContext<Editor>,
13111) {
13112    let mut tasks = Vec::new();
13113    project.update(cx, |project, cx| {
13114        for buffer in buffers {
13115            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13116        }
13117    });
13118    cx.spawn(|this, mut cx| async move {
13119        let change_sets = futures::future::join_all(tasks).await;
13120        this.update(&mut cx, |this, cx| {
13121            for change_set in change_sets {
13122                if let Some(change_set) = change_set.log_err() {
13123                    this.diff_map.add_change_set(change_set, cx);
13124                }
13125            }
13126        })
13127        .ok();
13128    })
13129    .detach();
13130}
13131
13132fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13133    let tab_size = tab_size.get() as usize;
13134    let mut width = offset;
13135
13136    for ch in text.chars() {
13137        width += if ch == '\t' {
13138            tab_size - (width % tab_size)
13139        } else {
13140            1
13141        };
13142    }
13143
13144    width - offset
13145}
13146
13147#[cfg(test)]
13148mod tests {
13149    use super::*;
13150
13151    #[test]
13152    fn test_string_size_with_expanded_tabs() {
13153        let nz = |val| NonZeroU32::new(val).unwrap();
13154        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13155        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13156        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13157        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13158        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13159        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13160        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13161        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13162    }
13163}
13164
13165/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13166struct WordBreakingTokenizer<'a> {
13167    input: &'a str,
13168}
13169
13170impl<'a> WordBreakingTokenizer<'a> {
13171    fn new(input: &'a str) -> Self {
13172        Self { input }
13173    }
13174}
13175
13176fn is_char_ideographic(ch: char) -> bool {
13177    use unicode_script::Script::*;
13178    use unicode_script::UnicodeScript;
13179    matches!(ch.script(), Han | Tangut | Yi)
13180}
13181
13182fn is_grapheme_ideographic(text: &str) -> bool {
13183    text.chars().any(is_char_ideographic)
13184}
13185
13186fn is_grapheme_whitespace(text: &str) -> bool {
13187    text.chars().any(|x| x.is_whitespace())
13188}
13189
13190fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13191    text.chars().next().map_or(false, |ch| {
13192        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13193    })
13194}
13195
13196#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13197struct WordBreakToken<'a> {
13198    token: &'a str,
13199    grapheme_len: usize,
13200    is_whitespace: bool,
13201}
13202
13203impl<'a> Iterator for WordBreakingTokenizer<'a> {
13204    /// Yields a span, the count of graphemes in the token, and whether it was
13205    /// whitespace. Note that it also breaks at word boundaries.
13206    type Item = WordBreakToken<'a>;
13207
13208    fn next(&mut self) -> Option<Self::Item> {
13209        use unicode_segmentation::UnicodeSegmentation;
13210        if self.input.is_empty() {
13211            return None;
13212        }
13213
13214        let mut iter = self.input.graphemes(true).peekable();
13215        let mut offset = 0;
13216        let mut graphemes = 0;
13217        if let Some(first_grapheme) = iter.next() {
13218            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13219            offset += first_grapheme.len();
13220            graphemes += 1;
13221            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13222                if let Some(grapheme) = iter.peek().copied() {
13223                    if should_stay_with_preceding_ideograph(grapheme) {
13224                        offset += grapheme.len();
13225                        graphemes += 1;
13226                    }
13227                }
13228            } else {
13229                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13230                let mut next_word_bound = words.peek().copied();
13231                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13232                    next_word_bound = words.next();
13233                }
13234                while let Some(grapheme) = iter.peek().copied() {
13235                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13236                        break;
13237                    };
13238                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13239                        break;
13240                    };
13241                    offset += grapheme.len();
13242                    graphemes += 1;
13243                    iter.next();
13244                }
13245            }
13246            let token = &self.input[..offset];
13247            self.input = &self.input[offset..];
13248            if is_whitespace {
13249                Some(WordBreakToken {
13250                    token: " ",
13251                    grapheme_len: 1,
13252                    is_whitespace: true,
13253                })
13254            } else {
13255                Some(WordBreakToken {
13256                    token,
13257                    grapheme_len: graphemes,
13258                    is_whitespace: false,
13259                })
13260            }
13261        } else {
13262            None
13263        }
13264    }
13265}
13266
13267#[test]
13268fn test_word_breaking_tokenizer() {
13269    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13270        ("", &[]),
13271        ("  ", &[(" ", 1, true)]),
13272        ("Ʒ", &[("Ʒ", 1, false)]),
13273        ("Ǽ", &[("Ǽ", 1, false)]),
13274        ("", &[("", 1, false)]),
13275        ("⋑⋑", &[("⋑⋑", 2, false)]),
13276        (
13277            "原理,进而",
13278            &[
13279                ("", 1, false),
13280                ("理,", 2, false),
13281                ("", 1, false),
13282                ("", 1, false),
13283            ],
13284        ),
13285        (
13286            "hello world",
13287            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13288        ),
13289        (
13290            "hello, world",
13291            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13292        ),
13293        (
13294            "  hello world",
13295            &[
13296                (" ", 1, true),
13297                ("hello", 5, false),
13298                (" ", 1, true),
13299                ("world", 5, false),
13300            ],
13301        ),
13302        (
13303            "这是什么 \n 钢笔",
13304            &[
13305                ("", 1, false),
13306                ("", 1, false),
13307                ("", 1, false),
13308                ("", 1, false),
13309                (" ", 1, true),
13310                ("", 1, false),
13311                ("", 1, false),
13312            ],
13313        ),
13314        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13315    ];
13316
13317    for (input, result) in tests {
13318        assert_eq!(
13319            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13320            result
13321                .iter()
13322                .copied()
13323                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13324                    token,
13325                    grapheme_len,
13326                    is_whitespace,
13327                })
13328                .collect::<Vec<_>>()
13329        );
13330    }
13331}
13332
13333fn wrap_with_prefix(
13334    line_prefix: String,
13335    unwrapped_text: String,
13336    wrap_column: usize,
13337    tab_size: NonZeroU32,
13338) -> String {
13339    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13340    let mut wrapped_text = String::new();
13341    let mut current_line = line_prefix.clone();
13342
13343    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13344    let mut current_line_len = line_prefix_len;
13345    for WordBreakToken {
13346        token,
13347        grapheme_len,
13348        is_whitespace,
13349    } in tokenizer
13350    {
13351        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13352            wrapped_text.push_str(current_line.trim_end());
13353            wrapped_text.push('\n');
13354            current_line.truncate(line_prefix.len());
13355            current_line_len = line_prefix_len;
13356            if !is_whitespace {
13357                current_line.push_str(token);
13358                current_line_len += grapheme_len;
13359            }
13360        } else if !is_whitespace {
13361            current_line.push_str(token);
13362            current_line_len += grapheme_len;
13363        } else if current_line_len != line_prefix_len {
13364            current_line.push(' ');
13365            current_line_len += 1;
13366        }
13367    }
13368
13369    if !current_line.is_empty() {
13370        wrapped_text.push_str(&current_line);
13371    }
13372    wrapped_text
13373}
13374
13375#[test]
13376fn test_wrap_with_prefix() {
13377    assert_eq!(
13378        wrap_with_prefix(
13379            "# ".to_string(),
13380            "abcdefg".to_string(),
13381            4,
13382            NonZeroU32::new(4).unwrap()
13383        ),
13384        "# abcdefg"
13385    );
13386    assert_eq!(
13387        wrap_with_prefix(
13388            "".to_string(),
13389            "\thello world".to_string(),
13390            8,
13391            NonZeroU32::new(4).unwrap()
13392        ),
13393        "hello\nworld"
13394    );
13395    assert_eq!(
13396        wrap_with_prefix(
13397            "// ".to_string(),
13398            "xx \nyy zz aa bb cc".to_string(),
13399            12,
13400            NonZeroU32::new(4).unwrap()
13401        ),
13402        "// xx yy zz\n// aa bb cc"
13403    );
13404    assert_eq!(
13405        wrap_with_prefix(
13406            String::new(),
13407            "这是什么 \n 钢笔".to_string(),
13408            3,
13409            NonZeroU32::new(4).unwrap()
13410        ),
13411        "这是什\n么 钢\n"
13412    );
13413}
13414
13415fn hunks_for_selections(
13416    snapshot: &EditorSnapshot,
13417    selections: &[Selection<Point>],
13418) -> Vec<MultiBufferDiffHunk> {
13419    hunks_for_ranges(
13420        selections.iter().map(|selection| selection.range()),
13421        snapshot,
13422    )
13423}
13424
13425pub fn hunks_for_ranges(
13426    ranges: impl Iterator<Item = Range<Point>>,
13427    snapshot: &EditorSnapshot,
13428) -> Vec<MultiBufferDiffHunk> {
13429    let mut hunks = Vec::new();
13430    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13431        HashMap::default();
13432    for query_range in ranges {
13433        let query_rows =
13434            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13435        for hunk in snapshot.diff_map.diff_hunks_in_range(
13436            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13437            &snapshot.buffer_snapshot,
13438        ) {
13439            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13440            // when the caret is just above or just below the deleted hunk.
13441            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13442            let related_to_selection = if allow_adjacent {
13443                hunk.row_range.overlaps(&query_rows)
13444                    || hunk.row_range.start == query_rows.end
13445                    || hunk.row_range.end == query_rows.start
13446            } else {
13447                hunk.row_range.overlaps(&query_rows)
13448            };
13449            if related_to_selection {
13450                if !processed_buffer_rows
13451                    .entry(hunk.buffer_id)
13452                    .or_default()
13453                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13454                {
13455                    continue;
13456                }
13457                hunks.push(hunk);
13458            }
13459        }
13460    }
13461
13462    hunks
13463}
13464
13465pub trait CollaborationHub {
13466    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13467    fn user_participant_indices<'a>(
13468        &self,
13469        cx: &'a AppContext,
13470    ) -> &'a HashMap<u64, ParticipantIndex>;
13471    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13472}
13473
13474impl CollaborationHub for Model<Project> {
13475    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13476        self.read(cx).collaborators()
13477    }
13478
13479    fn user_participant_indices<'a>(
13480        &self,
13481        cx: &'a AppContext,
13482    ) -> &'a HashMap<u64, ParticipantIndex> {
13483        self.read(cx).user_store().read(cx).participant_indices()
13484    }
13485
13486    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13487        let this = self.read(cx);
13488        let user_ids = this.collaborators().values().map(|c| c.user_id);
13489        this.user_store().read_with(cx, |user_store, cx| {
13490            user_store.participant_names(user_ids, cx)
13491        })
13492    }
13493}
13494
13495pub trait SemanticsProvider {
13496    fn hover(
13497        &self,
13498        buffer: &Model<Buffer>,
13499        position: text::Anchor,
13500        cx: &mut AppContext,
13501    ) -> Option<Task<Vec<project::Hover>>>;
13502
13503    fn inlay_hints(
13504        &self,
13505        buffer_handle: Model<Buffer>,
13506        range: Range<text::Anchor>,
13507        cx: &mut AppContext,
13508    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13509
13510    fn resolve_inlay_hint(
13511        &self,
13512        hint: InlayHint,
13513        buffer_handle: Model<Buffer>,
13514        server_id: LanguageServerId,
13515        cx: &mut AppContext,
13516    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13517
13518    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13519
13520    fn document_highlights(
13521        &self,
13522        buffer: &Model<Buffer>,
13523        position: text::Anchor,
13524        cx: &mut AppContext,
13525    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13526
13527    fn definitions(
13528        &self,
13529        buffer: &Model<Buffer>,
13530        position: text::Anchor,
13531        kind: GotoDefinitionKind,
13532        cx: &mut AppContext,
13533    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13534
13535    fn range_for_rename(
13536        &self,
13537        buffer: &Model<Buffer>,
13538        position: text::Anchor,
13539        cx: &mut AppContext,
13540    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13541
13542    fn perform_rename(
13543        &self,
13544        buffer: &Model<Buffer>,
13545        position: text::Anchor,
13546        new_name: String,
13547        cx: &mut AppContext,
13548    ) -> Option<Task<Result<ProjectTransaction>>>;
13549}
13550
13551pub trait CompletionProvider {
13552    fn completions(
13553        &self,
13554        buffer: &Model<Buffer>,
13555        buffer_position: text::Anchor,
13556        trigger: CompletionContext,
13557        cx: &mut ViewContext<Editor>,
13558    ) -> Task<Result<Vec<Completion>>>;
13559
13560    fn resolve_completions(
13561        &self,
13562        buffer: Model<Buffer>,
13563        completion_indices: Vec<usize>,
13564        completions: Rc<RefCell<Box<[Completion]>>>,
13565        cx: &mut ViewContext<Editor>,
13566    ) -> Task<Result<bool>>;
13567
13568    fn apply_additional_edits_for_completion(
13569        &self,
13570        _buffer: Model<Buffer>,
13571        _completions: Rc<RefCell<Box<[Completion]>>>,
13572        _completion_index: usize,
13573        _push_to_history: bool,
13574        _cx: &mut ViewContext<Editor>,
13575    ) -> Task<Result<Option<language::Transaction>>> {
13576        Task::ready(Ok(None))
13577    }
13578
13579    fn is_completion_trigger(
13580        &self,
13581        buffer: &Model<Buffer>,
13582        position: language::Anchor,
13583        text: &str,
13584        trigger_in_words: bool,
13585        cx: &mut ViewContext<Editor>,
13586    ) -> bool;
13587
13588    fn sort_completions(&self) -> bool {
13589        true
13590    }
13591}
13592
13593pub trait CodeActionProvider {
13594    fn code_actions(
13595        &self,
13596        buffer: &Model<Buffer>,
13597        range: Range<text::Anchor>,
13598        cx: &mut WindowContext,
13599    ) -> Task<Result<Vec<CodeAction>>>;
13600
13601    fn apply_code_action(
13602        &self,
13603        buffer_handle: Model<Buffer>,
13604        action: CodeAction,
13605        excerpt_id: ExcerptId,
13606        push_to_history: bool,
13607        cx: &mut WindowContext,
13608    ) -> Task<Result<ProjectTransaction>>;
13609}
13610
13611impl CodeActionProvider for Model<Project> {
13612    fn code_actions(
13613        &self,
13614        buffer: &Model<Buffer>,
13615        range: Range<text::Anchor>,
13616        cx: &mut WindowContext,
13617    ) -> Task<Result<Vec<CodeAction>>> {
13618        self.update(cx, |project, cx| {
13619            project.code_actions(buffer, range, None, cx)
13620        })
13621    }
13622
13623    fn apply_code_action(
13624        &self,
13625        buffer_handle: Model<Buffer>,
13626        action: CodeAction,
13627        _excerpt_id: ExcerptId,
13628        push_to_history: bool,
13629        cx: &mut WindowContext,
13630    ) -> Task<Result<ProjectTransaction>> {
13631        self.update(cx, |project, cx| {
13632            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13633        })
13634    }
13635}
13636
13637fn snippet_completions(
13638    project: &Project,
13639    buffer: &Model<Buffer>,
13640    buffer_position: text::Anchor,
13641    cx: &mut AppContext,
13642) -> Task<Result<Vec<Completion>>> {
13643    let language = buffer.read(cx).language_at(buffer_position);
13644    let language_name = language.as_ref().map(|language| language.lsp_id());
13645    let snippet_store = project.snippets().read(cx);
13646    let snippets = snippet_store.snippets_for(language_name, cx);
13647
13648    if snippets.is_empty() {
13649        return Task::ready(Ok(vec![]));
13650    }
13651    let snapshot = buffer.read(cx).text_snapshot();
13652    let chars: String = snapshot
13653        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13654        .collect();
13655
13656    let scope = language.map(|language| language.default_scope());
13657    let executor = cx.background_executor().clone();
13658
13659    cx.background_executor().spawn(async move {
13660        let classifier = CharClassifier::new(scope).for_completion(true);
13661        let mut last_word = chars
13662            .chars()
13663            .take_while(|c| classifier.is_word(*c))
13664            .collect::<String>();
13665        last_word = last_word.chars().rev().collect();
13666
13667        if last_word.is_empty() {
13668            return Ok(vec![]);
13669        }
13670
13671        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13672        let to_lsp = |point: &text::Anchor| {
13673            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13674            point_to_lsp(end)
13675        };
13676        let lsp_end = to_lsp(&buffer_position);
13677
13678        let candidates = snippets
13679            .iter()
13680            .enumerate()
13681            .flat_map(|(ix, snippet)| {
13682                snippet
13683                    .prefix
13684                    .iter()
13685                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13686            })
13687            .collect::<Vec<StringMatchCandidate>>();
13688
13689        let mut matches = fuzzy::match_strings(
13690            &candidates,
13691            &last_word,
13692            last_word.chars().any(|c| c.is_uppercase()),
13693            100,
13694            &Default::default(),
13695            executor,
13696        )
13697        .await;
13698
13699        // Remove all candidates where the query's start does not match the start of any word in the candidate
13700        if let Some(query_start) = last_word.chars().next() {
13701            matches.retain(|string_match| {
13702                split_words(&string_match.string).any(|word| {
13703                    // Check that the first codepoint of the word as lowercase matches the first
13704                    // codepoint of the query as lowercase
13705                    word.chars()
13706                        .flat_map(|codepoint| codepoint.to_lowercase())
13707                        .zip(query_start.to_lowercase())
13708                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13709                })
13710            });
13711        }
13712
13713        let matched_strings = matches
13714            .into_iter()
13715            .map(|m| m.string)
13716            .collect::<HashSet<_>>();
13717
13718        let result: Vec<Completion> = snippets
13719            .into_iter()
13720            .filter_map(|snippet| {
13721                let matching_prefix = snippet
13722                    .prefix
13723                    .iter()
13724                    .find(|prefix| matched_strings.contains(*prefix))?;
13725                let start = as_offset - last_word.len();
13726                let start = snapshot.anchor_before(start);
13727                let range = start..buffer_position;
13728                let lsp_start = to_lsp(&start);
13729                let lsp_range = lsp::Range {
13730                    start: lsp_start,
13731                    end: lsp_end,
13732                };
13733                Some(Completion {
13734                    old_range: range,
13735                    new_text: snippet.body.clone(),
13736                    resolved: false,
13737                    label: CodeLabel {
13738                        text: matching_prefix.clone(),
13739                        runs: vec![],
13740                        filter_range: 0..matching_prefix.len(),
13741                    },
13742                    server_id: LanguageServerId(usize::MAX),
13743                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13744                    lsp_completion: lsp::CompletionItem {
13745                        label: snippet.prefix.first().unwrap().clone(),
13746                        kind: Some(CompletionItemKind::SNIPPET),
13747                        label_details: snippet.description.as_ref().map(|description| {
13748                            lsp::CompletionItemLabelDetails {
13749                                detail: Some(description.clone()),
13750                                description: None,
13751                            }
13752                        }),
13753                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13754                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13755                            lsp::InsertReplaceEdit {
13756                                new_text: snippet.body.clone(),
13757                                insert: lsp_range,
13758                                replace: lsp_range,
13759                            },
13760                        )),
13761                        filter_text: Some(snippet.body.clone()),
13762                        sort_text: Some(char::MAX.to_string()),
13763                        ..Default::default()
13764                    },
13765                    confirm: None,
13766                })
13767            })
13768            .collect();
13769
13770        Ok(result)
13771    })
13772}
13773
13774impl CompletionProvider for Model<Project> {
13775    fn completions(
13776        &self,
13777        buffer: &Model<Buffer>,
13778        buffer_position: text::Anchor,
13779        options: CompletionContext,
13780        cx: &mut ViewContext<Editor>,
13781    ) -> Task<Result<Vec<Completion>>> {
13782        self.update(cx, |project, cx| {
13783            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13784            let project_completions = project.completions(buffer, buffer_position, options, cx);
13785            cx.background_executor().spawn(async move {
13786                let mut completions = project_completions.await?;
13787                let snippets_completions = snippets.await?;
13788                completions.extend(snippets_completions);
13789                Ok(completions)
13790            })
13791        })
13792    }
13793
13794    fn resolve_completions(
13795        &self,
13796        buffer: Model<Buffer>,
13797        completion_indices: Vec<usize>,
13798        completions: Rc<RefCell<Box<[Completion]>>>,
13799        cx: &mut ViewContext<Editor>,
13800    ) -> Task<Result<bool>> {
13801        self.update(cx, |project, cx| {
13802            project.lsp_store().update(cx, |lsp_store, cx| {
13803                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13804            })
13805        })
13806    }
13807
13808    fn apply_additional_edits_for_completion(
13809        &self,
13810        buffer: Model<Buffer>,
13811        completions: Rc<RefCell<Box<[Completion]>>>,
13812        completion_index: usize,
13813        push_to_history: bool,
13814        cx: &mut ViewContext<Editor>,
13815    ) -> Task<Result<Option<language::Transaction>>> {
13816        self.update(cx, |project, cx| {
13817            project.lsp_store().update(cx, |lsp_store, cx| {
13818                lsp_store.apply_additional_edits_for_completion(
13819                    buffer,
13820                    completions,
13821                    completion_index,
13822                    push_to_history,
13823                    cx,
13824                )
13825            })
13826        })
13827    }
13828
13829    fn is_completion_trigger(
13830        &self,
13831        buffer: &Model<Buffer>,
13832        position: language::Anchor,
13833        text: &str,
13834        trigger_in_words: bool,
13835        cx: &mut ViewContext<Editor>,
13836    ) -> bool {
13837        let mut chars = text.chars();
13838        let char = if let Some(char) = chars.next() {
13839            char
13840        } else {
13841            return false;
13842        };
13843        if chars.next().is_some() {
13844            return false;
13845        }
13846
13847        let buffer = buffer.read(cx);
13848        let snapshot = buffer.snapshot();
13849        if !snapshot.settings_at(position, cx).show_completions_on_input {
13850            return false;
13851        }
13852        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13853        if trigger_in_words && classifier.is_word(char) {
13854            return true;
13855        }
13856
13857        buffer.completion_triggers().contains(text)
13858    }
13859}
13860
13861impl SemanticsProvider for Model<Project> {
13862    fn hover(
13863        &self,
13864        buffer: &Model<Buffer>,
13865        position: text::Anchor,
13866        cx: &mut AppContext,
13867    ) -> Option<Task<Vec<project::Hover>>> {
13868        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13869    }
13870
13871    fn document_highlights(
13872        &self,
13873        buffer: &Model<Buffer>,
13874        position: text::Anchor,
13875        cx: &mut AppContext,
13876    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13877        Some(self.update(cx, |project, cx| {
13878            project.document_highlights(buffer, position, cx)
13879        }))
13880    }
13881
13882    fn definitions(
13883        &self,
13884        buffer: &Model<Buffer>,
13885        position: text::Anchor,
13886        kind: GotoDefinitionKind,
13887        cx: &mut AppContext,
13888    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13889        Some(self.update(cx, |project, cx| match kind {
13890            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13891            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13892            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13893            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13894        }))
13895    }
13896
13897    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13898        // TODO: make this work for remote projects
13899        self.read(cx)
13900            .language_servers_for_local_buffer(buffer.read(cx), cx)
13901            .any(
13902                |(_, server)| match server.capabilities().inlay_hint_provider {
13903                    Some(lsp::OneOf::Left(enabled)) => enabled,
13904                    Some(lsp::OneOf::Right(_)) => true,
13905                    None => false,
13906                },
13907            )
13908    }
13909
13910    fn inlay_hints(
13911        &self,
13912        buffer_handle: Model<Buffer>,
13913        range: Range<text::Anchor>,
13914        cx: &mut AppContext,
13915    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13916        Some(self.update(cx, |project, cx| {
13917            project.inlay_hints(buffer_handle, range, cx)
13918        }))
13919    }
13920
13921    fn resolve_inlay_hint(
13922        &self,
13923        hint: InlayHint,
13924        buffer_handle: Model<Buffer>,
13925        server_id: LanguageServerId,
13926        cx: &mut AppContext,
13927    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13928        Some(self.update(cx, |project, cx| {
13929            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13930        }))
13931    }
13932
13933    fn range_for_rename(
13934        &self,
13935        buffer: &Model<Buffer>,
13936        position: text::Anchor,
13937        cx: &mut AppContext,
13938    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13939        Some(self.update(cx, |project, cx| {
13940            project.prepare_rename(buffer.clone(), position, cx)
13941        }))
13942    }
13943
13944    fn perform_rename(
13945        &self,
13946        buffer: &Model<Buffer>,
13947        position: text::Anchor,
13948        new_name: String,
13949        cx: &mut AppContext,
13950    ) -> Option<Task<Result<ProjectTransaction>>> {
13951        Some(self.update(cx, |project, cx| {
13952            project.perform_rename(buffer.clone(), position, new_name, cx)
13953        }))
13954    }
13955}
13956
13957fn inlay_hint_settings(
13958    location: Anchor,
13959    snapshot: &MultiBufferSnapshot,
13960    cx: &mut ViewContext<Editor>,
13961) -> InlayHintSettings {
13962    let file = snapshot.file_at(location);
13963    let language = snapshot.language_at(location).map(|l| l.name());
13964    language_settings(language, file, cx).inlay_hints
13965}
13966
13967fn consume_contiguous_rows(
13968    contiguous_row_selections: &mut Vec<Selection<Point>>,
13969    selection: &Selection<Point>,
13970    display_map: &DisplaySnapshot,
13971    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13972) -> (MultiBufferRow, MultiBufferRow) {
13973    contiguous_row_selections.push(selection.clone());
13974    let start_row = MultiBufferRow(selection.start.row);
13975    let mut end_row = ending_row(selection, display_map);
13976
13977    while let Some(next_selection) = selections.peek() {
13978        if next_selection.start.row <= end_row.0 {
13979            end_row = ending_row(next_selection, display_map);
13980            contiguous_row_selections.push(selections.next().unwrap().clone());
13981        } else {
13982            break;
13983        }
13984    }
13985    (start_row, end_row)
13986}
13987
13988fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13989    if next_selection.end.column > 0 || next_selection.is_empty() {
13990        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13991    } else {
13992        MultiBufferRow(next_selection.end.row)
13993    }
13994}
13995
13996impl EditorSnapshot {
13997    pub fn remote_selections_in_range<'a>(
13998        &'a self,
13999        range: &'a Range<Anchor>,
14000        collaboration_hub: &dyn CollaborationHub,
14001        cx: &'a AppContext,
14002    ) -> impl 'a + Iterator<Item = RemoteSelection> {
14003        let participant_names = collaboration_hub.user_names(cx);
14004        let participant_indices = collaboration_hub.user_participant_indices(cx);
14005        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
14006        let collaborators_by_replica_id = collaborators_by_peer_id
14007            .iter()
14008            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
14009            .collect::<HashMap<_, _>>();
14010        self.buffer_snapshot
14011            .selections_in_range(range, false)
14012            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14013                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14014                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14015                let user_name = participant_names.get(&collaborator.user_id).cloned();
14016                Some(RemoteSelection {
14017                    replica_id,
14018                    selection,
14019                    cursor_shape,
14020                    line_mode,
14021                    participant_index,
14022                    peer_id: collaborator.peer_id,
14023                    user_name,
14024                })
14025            })
14026    }
14027
14028    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14029        self.display_snapshot.buffer_snapshot.language_at(position)
14030    }
14031
14032    pub fn is_focused(&self) -> bool {
14033        self.is_focused
14034    }
14035
14036    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14037        self.placeholder_text.as_ref()
14038    }
14039
14040    pub fn scroll_position(&self) -> gpui::Point<f32> {
14041        self.scroll_anchor.scroll_position(&self.display_snapshot)
14042    }
14043
14044    fn gutter_dimensions(
14045        &self,
14046        font_id: FontId,
14047        font_size: Pixels,
14048        em_width: Pixels,
14049        em_advance: Pixels,
14050        max_line_number_width: Pixels,
14051        cx: &AppContext,
14052    ) -> GutterDimensions {
14053        if !self.show_gutter {
14054            return GutterDimensions::default();
14055        }
14056        let descent = cx.text_system().descent(font_id, font_size);
14057
14058        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14059            matches!(
14060                ProjectSettings::get_global(cx).git.git_gutter,
14061                Some(GitGutterSetting::TrackedFiles)
14062            )
14063        });
14064        let gutter_settings = EditorSettings::get_global(cx).gutter;
14065        let show_line_numbers = self
14066            .show_line_numbers
14067            .unwrap_or(gutter_settings.line_numbers);
14068        let line_gutter_width = if show_line_numbers {
14069            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14070            let min_width_for_number_on_gutter = em_advance * 4.0;
14071            max_line_number_width.max(min_width_for_number_on_gutter)
14072        } else {
14073            0.0.into()
14074        };
14075
14076        let show_code_actions = self
14077            .show_code_actions
14078            .unwrap_or(gutter_settings.code_actions);
14079
14080        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14081
14082        let git_blame_entries_width =
14083            self.git_blame_gutter_max_author_length
14084                .map(|max_author_length| {
14085                    // Length of the author name, but also space for the commit hash,
14086                    // the spacing and the timestamp.
14087                    let max_char_count = max_author_length
14088                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14089                        + 7 // length of commit sha
14090                        + 14 // length of max relative timestamp ("60 minutes ago")
14091                        + 4; // gaps and margins
14092
14093                    em_advance * max_char_count
14094                });
14095
14096        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14097        left_padding += if show_code_actions || show_runnables {
14098            em_width * 3.0
14099        } else if show_git_gutter && show_line_numbers {
14100            em_width * 2.0
14101        } else if show_git_gutter || show_line_numbers {
14102            em_width
14103        } else {
14104            px(0.)
14105        };
14106
14107        let right_padding = if gutter_settings.folds && show_line_numbers {
14108            em_width * 4.0
14109        } else if gutter_settings.folds {
14110            em_width * 3.0
14111        } else if show_line_numbers {
14112            em_width
14113        } else {
14114            px(0.)
14115        };
14116
14117        GutterDimensions {
14118            left_padding,
14119            right_padding,
14120            width: line_gutter_width + left_padding + right_padding,
14121            margin: -descent,
14122            git_blame_entries_width,
14123        }
14124    }
14125
14126    pub fn render_crease_toggle(
14127        &self,
14128        buffer_row: MultiBufferRow,
14129        row_contains_cursor: bool,
14130        editor: View<Editor>,
14131        cx: &mut WindowContext,
14132    ) -> Option<AnyElement> {
14133        let folded = self.is_line_folded(buffer_row);
14134        let mut is_foldable = false;
14135
14136        if let Some(crease) = self
14137            .crease_snapshot
14138            .query_row(buffer_row, &self.buffer_snapshot)
14139        {
14140            is_foldable = true;
14141            match crease {
14142                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14143                    if let Some(render_toggle) = render_toggle {
14144                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14145                            if folded {
14146                                editor.update(cx, |editor, cx| {
14147                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14148                                });
14149                            } else {
14150                                editor.update(cx, |editor, cx| {
14151                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14152                                });
14153                            }
14154                        });
14155                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14156                    }
14157                }
14158            }
14159        }
14160
14161        is_foldable |= self.starts_indent(buffer_row);
14162
14163        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14164            Some(
14165                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14166                    .toggle_state(folded)
14167                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14168                        if folded {
14169                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14170                        } else {
14171                            this.fold_at(&FoldAt { buffer_row }, cx);
14172                        }
14173                    }))
14174                    .into_any_element(),
14175            )
14176        } else {
14177            None
14178        }
14179    }
14180
14181    pub fn render_crease_trailer(
14182        &self,
14183        buffer_row: MultiBufferRow,
14184        cx: &mut WindowContext,
14185    ) -> Option<AnyElement> {
14186        let folded = self.is_line_folded(buffer_row);
14187        if let Crease::Inline { render_trailer, .. } = self
14188            .crease_snapshot
14189            .query_row(buffer_row, &self.buffer_snapshot)?
14190        {
14191            let render_trailer = render_trailer.as_ref()?;
14192            Some(render_trailer(buffer_row, folded, cx))
14193        } else {
14194            None
14195        }
14196    }
14197}
14198
14199impl Deref for EditorSnapshot {
14200    type Target = DisplaySnapshot;
14201
14202    fn deref(&self) -> &Self::Target {
14203        &self.display_snapshot
14204    }
14205}
14206
14207#[derive(Clone, Debug, PartialEq, Eq)]
14208pub enum EditorEvent {
14209    InputIgnored {
14210        text: Arc<str>,
14211    },
14212    InputHandled {
14213        utf16_range_to_replace: Option<Range<isize>>,
14214        text: Arc<str>,
14215    },
14216    ExcerptsAdded {
14217        buffer: Model<Buffer>,
14218        predecessor: ExcerptId,
14219        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14220    },
14221    ExcerptsRemoved {
14222        ids: Vec<ExcerptId>,
14223    },
14224    BufferFoldToggled {
14225        ids: Vec<ExcerptId>,
14226        folded: bool,
14227    },
14228    ExcerptsEdited {
14229        ids: Vec<ExcerptId>,
14230    },
14231    ExcerptsExpanded {
14232        ids: Vec<ExcerptId>,
14233    },
14234    BufferEdited,
14235    Edited {
14236        transaction_id: clock::Lamport,
14237    },
14238    Reparsed(BufferId),
14239    Focused,
14240    FocusedIn,
14241    Blurred,
14242    DirtyChanged,
14243    Saved,
14244    TitleChanged,
14245    DiffBaseChanged,
14246    SelectionsChanged {
14247        local: bool,
14248    },
14249    ScrollPositionChanged {
14250        local: bool,
14251        autoscroll: bool,
14252    },
14253    Closed,
14254    TransactionUndone {
14255        transaction_id: clock::Lamport,
14256    },
14257    TransactionBegun {
14258        transaction_id: clock::Lamport,
14259    },
14260    Reloaded,
14261    CursorShapeChanged,
14262}
14263
14264impl EventEmitter<EditorEvent> for Editor {}
14265
14266impl FocusableView for Editor {
14267    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14268        self.focus_handle.clone()
14269    }
14270}
14271
14272impl Render for Editor {
14273    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14274        let settings = ThemeSettings::get_global(cx);
14275
14276        let mut text_style = match self.mode {
14277            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14278                color: cx.theme().colors().editor_foreground,
14279                font_family: settings.ui_font.family.clone(),
14280                font_features: settings.ui_font.features.clone(),
14281                font_fallbacks: settings.ui_font.fallbacks.clone(),
14282                font_size: rems(0.875).into(),
14283                font_weight: settings.ui_font.weight,
14284                line_height: relative(settings.buffer_line_height.value()),
14285                ..Default::default()
14286            },
14287            EditorMode::Full => TextStyle {
14288                color: cx.theme().colors().editor_foreground,
14289                font_family: settings.buffer_font.family.clone(),
14290                font_features: settings.buffer_font.features.clone(),
14291                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14292                font_size: settings.buffer_font_size(cx).into(),
14293                font_weight: settings.buffer_font.weight,
14294                line_height: relative(settings.buffer_line_height.value()),
14295                ..Default::default()
14296            },
14297        };
14298        if let Some(text_style_refinement) = &self.text_style_refinement {
14299            text_style.refine(text_style_refinement)
14300        }
14301
14302        let background = match self.mode {
14303            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14304            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14305            EditorMode::Full => cx.theme().colors().editor_background,
14306        };
14307
14308        EditorElement::new(
14309            cx.view(),
14310            EditorStyle {
14311                background,
14312                local_player: cx.theme().players().local(),
14313                text: text_style,
14314                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14315                syntax: cx.theme().syntax().clone(),
14316                status: cx.theme().status().clone(),
14317                inlay_hints_style: make_inlay_hints_style(cx),
14318                inline_completion_styles: make_suggestion_styles(cx),
14319                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14320            },
14321        )
14322    }
14323}
14324
14325impl ViewInputHandler for Editor {
14326    fn text_for_range(
14327        &mut self,
14328        range_utf16: Range<usize>,
14329        adjusted_range: &mut Option<Range<usize>>,
14330        cx: &mut ViewContext<Self>,
14331    ) -> Option<String> {
14332        let snapshot = self.buffer.read(cx).read(cx);
14333        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14334        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14335        if (start.0..end.0) != range_utf16 {
14336            adjusted_range.replace(start.0..end.0);
14337        }
14338        Some(snapshot.text_for_range(start..end).collect())
14339    }
14340
14341    fn selected_text_range(
14342        &mut self,
14343        ignore_disabled_input: bool,
14344        cx: &mut ViewContext<Self>,
14345    ) -> Option<UTF16Selection> {
14346        // Prevent the IME menu from appearing when holding down an alphabetic key
14347        // while input is disabled.
14348        if !ignore_disabled_input && !self.input_enabled {
14349            return None;
14350        }
14351
14352        let selection = self.selections.newest::<OffsetUtf16>(cx);
14353        let range = selection.range();
14354
14355        Some(UTF16Selection {
14356            range: range.start.0..range.end.0,
14357            reversed: selection.reversed,
14358        })
14359    }
14360
14361    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14362        let snapshot = self.buffer.read(cx).read(cx);
14363        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14364        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14365    }
14366
14367    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14368        self.clear_highlights::<InputComposition>(cx);
14369        self.ime_transaction.take();
14370    }
14371
14372    fn replace_text_in_range(
14373        &mut self,
14374        range_utf16: Option<Range<usize>>,
14375        text: &str,
14376        cx: &mut ViewContext<Self>,
14377    ) {
14378        if !self.input_enabled {
14379            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14380            return;
14381        }
14382
14383        self.transact(cx, |this, cx| {
14384            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14385                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14386                Some(this.selection_replacement_ranges(range_utf16, cx))
14387            } else {
14388                this.marked_text_ranges(cx)
14389            };
14390
14391            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14392                let newest_selection_id = this.selections.newest_anchor().id;
14393                this.selections
14394                    .all::<OffsetUtf16>(cx)
14395                    .iter()
14396                    .zip(ranges_to_replace.iter())
14397                    .find_map(|(selection, range)| {
14398                        if selection.id == newest_selection_id {
14399                            Some(
14400                                (range.start.0 as isize - selection.head().0 as isize)
14401                                    ..(range.end.0 as isize - selection.head().0 as isize),
14402                            )
14403                        } else {
14404                            None
14405                        }
14406                    })
14407            });
14408
14409            cx.emit(EditorEvent::InputHandled {
14410                utf16_range_to_replace: range_to_replace,
14411                text: text.into(),
14412            });
14413
14414            if let Some(new_selected_ranges) = new_selected_ranges {
14415                this.change_selections(None, cx, |selections| {
14416                    selections.select_ranges(new_selected_ranges)
14417                });
14418                this.backspace(&Default::default(), cx);
14419            }
14420
14421            this.handle_input(text, cx);
14422        });
14423
14424        if let Some(transaction) = self.ime_transaction {
14425            self.buffer.update(cx, |buffer, cx| {
14426                buffer.group_until_transaction(transaction, cx);
14427            });
14428        }
14429
14430        self.unmark_text(cx);
14431    }
14432
14433    fn replace_and_mark_text_in_range(
14434        &mut self,
14435        range_utf16: Option<Range<usize>>,
14436        text: &str,
14437        new_selected_range_utf16: Option<Range<usize>>,
14438        cx: &mut ViewContext<Self>,
14439    ) {
14440        if !self.input_enabled {
14441            return;
14442        }
14443
14444        let transaction = self.transact(cx, |this, cx| {
14445            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14446                let snapshot = this.buffer.read(cx).read(cx);
14447                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14448                    for marked_range in &mut marked_ranges {
14449                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14450                        marked_range.start.0 += relative_range_utf16.start;
14451                        marked_range.start =
14452                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14453                        marked_range.end =
14454                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14455                    }
14456                }
14457                Some(marked_ranges)
14458            } else if let Some(range_utf16) = range_utf16 {
14459                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14460                Some(this.selection_replacement_ranges(range_utf16, cx))
14461            } else {
14462                None
14463            };
14464
14465            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14466                let newest_selection_id = this.selections.newest_anchor().id;
14467                this.selections
14468                    .all::<OffsetUtf16>(cx)
14469                    .iter()
14470                    .zip(ranges_to_replace.iter())
14471                    .find_map(|(selection, range)| {
14472                        if selection.id == newest_selection_id {
14473                            Some(
14474                                (range.start.0 as isize - selection.head().0 as isize)
14475                                    ..(range.end.0 as isize - selection.head().0 as isize),
14476                            )
14477                        } else {
14478                            None
14479                        }
14480                    })
14481            });
14482
14483            cx.emit(EditorEvent::InputHandled {
14484                utf16_range_to_replace: range_to_replace,
14485                text: text.into(),
14486            });
14487
14488            if let Some(ranges) = ranges_to_replace {
14489                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14490            }
14491
14492            let marked_ranges = {
14493                let snapshot = this.buffer.read(cx).read(cx);
14494                this.selections
14495                    .disjoint_anchors()
14496                    .iter()
14497                    .map(|selection| {
14498                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14499                    })
14500                    .collect::<Vec<_>>()
14501            };
14502
14503            if text.is_empty() {
14504                this.unmark_text(cx);
14505            } else {
14506                this.highlight_text::<InputComposition>(
14507                    marked_ranges.clone(),
14508                    HighlightStyle {
14509                        underline: Some(UnderlineStyle {
14510                            thickness: px(1.),
14511                            color: None,
14512                            wavy: false,
14513                        }),
14514                        ..Default::default()
14515                    },
14516                    cx,
14517                );
14518            }
14519
14520            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14521            let use_autoclose = this.use_autoclose;
14522            let use_auto_surround = this.use_auto_surround;
14523            this.set_use_autoclose(false);
14524            this.set_use_auto_surround(false);
14525            this.handle_input(text, cx);
14526            this.set_use_autoclose(use_autoclose);
14527            this.set_use_auto_surround(use_auto_surround);
14528
14529            if let Some(new_selected_range) = new_selected_range_utf16 {
14530                let snapshot = this.buffer.read(cx).read(cx);
14531                let new_selected_ranges = marked_ranges
14532                    .into_iter()
14533                    .map(|marked_range| {
14534                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14535                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14536                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14537                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14538                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14539                    })
14540                    .collect::<Vec<_>>();
14541
14542                drop(snapshot);
14543                this.change_selections(None, cx, |selections| {
14544                    selections.select_ranges(new_selected_ranges)
14545                });
14546            }
14547        });
14548
14549        self.ime_transaction = self.ime_transaction.or(transaction);
14550        if let Some(transaction) = self.ime_transaction {
14551            self.buffer.update(cx, |buffer, cx| {
14552                buffer.group_until_transaction(transaction, cx);
14553            });
14554        }
14555
14556        if self.text_highlights::<InputComposition>(cx).is_none() {
14557            self.ime_transaction.take();
14558        }
14559    }
14560
14561    fn bounds_for_range(
14562        &mut self,
14563        range_utf16: Range<usize>,
14564        element_bounds: gpui::Bounds<Pixels>,
14565        cx: &mut ViewContext<Self>,
14566    ) -> Option<gpui::Bounds<Pixels>> {
14567        let text_layout_details = self.text_layout_details(cx);
14568        let gpui::Point {
14569            x: em_width,
14570            y: line_height,
14571        } = self.character_size(cx);
14572
14573        let snapshot = self.snapshot(cx);
14574        let scroll_position = snapshot.scroll_position();
14575        let scroll_left = scroll_position.x * em_width;
14576
14577        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14578        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14579            + self.gutter_dimensions.width
14580            + self.gutter_dimensions.margin;
14581        let y = line_height * (start.row().as_f32() - scroll_position.y);
14582
14583        Some(Bounds {
14584            origin: element_bounds.origin + point(x, y),
14585            size: size(em_width, line_height),
14586        })
14587    }
14588}
14589
14590trait SelectionExt {
14591    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14592    fn spanned_rows(
14593        &self,
14594        include_end_if_at_line_start: bool,
14595        map: &DisplaySnapshot,
14596    ) -> Range<MultiBufferRow>;
14597}
14598
14599impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14600    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14601        let start = self
14602            .start
14603            .to_point(&map.buffer_snapshot)
14604            .to_display_point(map);
14605        let end = self
14606            .end
14607            .to_point(&map.buffer_snapshot)
14608            .to_display_point(map);
14609        if self.reversed {
14610            end..start
14611        } else {
14612            start..end
14613        }
14614    }
14615
14616    fn spanned_rows(
14617        &self,
14618        include_end_if_at_line_start: bool,
14619        map: &DisplaySnapshot,
14620    ) -> Range<MultiBufferRow> {
14621        let start = self.start.to_point(&map.buffer_snapshot);
14622        let mut end = self.end.to_point(&map.buffer_snapshot);
14623        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14624            end.row -= 1;
14625        }
14626
14627        let buffer_start = map.prev_line_boundary(start).0;
14628        let buffer_end = map.next_line_boundary(end).0;
14629        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14630    }
14631}
14632
14633impl<T: InvalidationRegion> InvalidationStack<T> {
14634    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14635    where
14636        S: Clone + ToOffset,
14637    {
14638        while let Some(region) = self.last() {
14639            let all_selections_inside_invalidation_ranges =
14640                if selections.len() == region.ranges().len() {
14641                    selections
14642                        .iter()
14643                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14644                        .all(|(selection, invalidation_range)| {
14645                            let head = selection.head().to_offset(buffer);
14646                            invalidation_range.start <= head && invalidation_range.end >= head
14647                        })
14648                } else {
14649                    false
14650                };
14651
14652            if all_selections_inside_invalidation_ranges {
14653                break;
14654            } else {
14655                self.pop();
14656            }
14657        }
14658    }
14659}
14660
14661impl<T> Default for InvalidationStack<T> {
14662    fn default() -> Self {
14663        Self(Default::default())
14664    }
14665}
14666
14667impl<T> Deref for InvalidationStack<T> {
14668    type Target = Vec<T>;
14669
14670    fn deref(&self) -> &Self::Target {
14671        &self.0
14672    }
14673}
14674
14675impl<T> DerefMut for InvalidationStack<T> {
14676    fn deref_mut(&mut self) -> &mut Self::Target {
14677        &mut self.0
14678    }
14679}
14680
14681impl InvalidationRegion for SnippetState {
14682    fn ranges(&self) -> &[Range<Anchor>] {
14683        &self.ranges[self.active_index]
14684    }
14685}
14686
14687pub fn diagnostic_block_renderer(
14688    diagnostic: Diagnostic,
14689    max_message_rows: Option<u8>,
14690    allow_closing: bool,
14691    _is_valid: bool,
14692) -> RenderBlock {
14693    let (text_without_backticks, code_ranges) =
14694        highlight_diagnostic_message(&diagnostic, max_message_rows);
14695
14696    Arc::new(move |cx: &mut BlockContext| {
14697        let group_id: SharedString = cx.block_id.to_string().into();
14698
14699        let mut text_style = cx.text_style().clone();
14700        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14701        let theme_settings = ThemeSettings::get_global(cx);
14702        text_style.font_family = theme_settings.buffer_font.family.clone();
14703        text_style.font_style = theme_settings.buffer_font.style;
14704        text_style.font_features = theme_settings.buffer_font.features.clone();
14705        text_style.font_weight = theme_settings.buffer_font.weight;
14706
14707        let multi_line_diagnostic = diagnostic.message.contains('\n');
14708
14709        let buttons = |diagnostic: &Diagnostic| {
14710            if multi_line_diagnostic {
14711                v_flex()
14712            } else {
14713                h_flex()
14714            }
14715            .when(allow_closing, |div| {
14716                div.children(diagnostic.is_primary.then(|| {
14717                    IconButton::new("close-block", IconName::XCircle)
14718                        .icon_color(Color::Muted)
14719                        .size(ButtonSize::Compact)
14720                        .style(ButtonStyle::Transparent)
14721                        .visible_on_hover(group_id.clone())
14722                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14723                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14724                }))
14725            })
14726            .child(
14727                IconButton::new("copy-block", IconName::Copy)
14728                    .icon_color(Color::Muted)
14729                    .size(ButtonSize::Compact)
14730                    .style(ButtonStyle::Transparent)
14731                    .visible_on_hover(group_id.clone())
14732                    .on_click({
14733                        let message = diagnostic.message.clone();
14734                        move |_click, cx| {
14735                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14736                        }
14737                    })
14738                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14739            )
14740        };
14741
14742        let icon_size = buttons(&diagnostic)
14743            .into_any_element()
14744            .layout_as_root(AvailableSpace::min_size(), cx);
14745
14746        h_flex()
14747            .id(cx.block_id)
14748            .group(group_id.clone())
14749            .relative()
14750            .size_full()
14751            .block_mouse_down()
14752            .pl(cx.gutter_dimensions.width)
14753            .w(cx.max_width - cx.gutter_dimensions.full_width())
14754            .child(
14755                div()
14756                    .flex()
14757                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14758                    .flex_shrink(),
14759            )
14760            .child(buttons(&diagnostic))
14761            .child(div().flex().flex_shrink_0().child(
14762                StyledText::new(text_without_backticks.clone()).with_highlights(
14763                    &text_style,
14764                    code_ranges.iter().map(|range| {
14765                        (
14766                            range.clone(),
14767                            HighlightStyle {
14768                                font_weight: Some(FontWeight::BOLD),
14769                                ..Default::default()
14770                            },
14771                        )
14772                    }),
14773                ),
14774            ))
14775            .into_any_element()
14776    })
14777}
14778
14779fn inline_completion_edit_text(
14780    editor_snapshot: &EditorSnapshot,
14781    edits: &Vec<(Range<Anchor>, String)>,
14782    include_deletions: bool,
14783    cx: &WindowContext,
14784) -> InlineCompletionText {
14785    let edit_start = edits
14786        .first()
14787        .unwrap()
14788        .0
14789        .start
14790        .to_display_point(editor_snapshot);
14791
14792    let mut text = String::new();
14793    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14794    let mut highlights = Vec::new();
14795    for (old_range, new_text) in edits {
14796        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14797        text.extend(
14798            editor_snapshot
14799                .buffer_snapshot
14800                .chunks(offset..old_offset_range.start, false)
14801                .map(|chunk| chunk.text),
14802        );
14803        offset = old_offset_range.end;
14804
14805        let start = text.len();
14806        let color = if include_deletions && new_text.is_empty() {
14807            text.extend(
14808                editor_snapshot
14809                    .buffer_snapshot
14810                    .chunks(old_offset_range.start..offset, false)
14811                    .map(|chunk| chunk.text),
14812            );
14813            cx.theme().status().deleted_background
14814        } else {
14815            text.push_str(new_text);
14816            cx.theme().status().created_background
14817        };
14818        let end = text.len();
14819
14820        highlights.push((
14821            start..end,
14822            HighlightStyle {
14823                background_color: Some(color),
14824                ..Default::default()
14825            },
14826        ));
14827    }
14828
14829    let edit_end = edits
14830        .last()
14831        .unwrap()
14832        .0
14833        .end
14834        .to_display_point(editor_snapshot);
14835    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14836        .to_offset(editor_snapshot, Bias::Right);
14837    text.extend(
14838        editor_snapshot
14839            .buffer_snapshot
14840            .chunks(offset..end_of_line, false)
14841            .map(|chunk| chunk.text),
14842    );
14843
14844    InlineCompletionText::Edit {
14845        text: text.into(),
14846        highlights,
14847    }
14848}
14849
14850pub fn highlight_diagnostic_message(
14851    diagnostic: &Diagnostic,
14852    mut max_message_rows: Option<u8>,
14853) -> (SharedString, Vec<Range<usize>>) {
14854    let mut text_without_backticks = String::new();
14855    let mut code_ranges = Vec::new();
14856
14857    if let Some(source) = &diagnostic.source {
14858        text_without_backticks.push_str(source);
14859        code_ranges.push(0..source.len());
14860        text_without_backticks.push_str(": ");
14861    }
14862
14863    let mut prev_offset = 0;
14864    let mut in_code_block = false;
14865    let has_row_limit = max_message_rows.is_some();
14866    let mut newline_indices = diagnostic
14867        .message
14868        .match_indices('\n')
14869        .filter(|_| has_row_limit)
14870        .map(|(ix, _)| ix)
14871        .fuse()
14872        .peekable();
14873
14874    for (quote_ix, _) in diagnostic
14875        .message
14876        .match_indices('`')
14877        .chain([(diagnostic.message.len(), "")])
14878    {
14879        let mut first_newline_ix = None;
14880        let mut last_newline_ix = None;
14881        while let Some(newline_ix) = newline_indices.peek() {
14882            if *newline_ix < quote_ix {
14883                if first_newline_ix.is_none() {
14884                    first_newline_ix = Some(*newline_ix);
14885                }
14886                last_newline_ix = Some(*newline_ix);
14887
14888                if let Some(rows_left) = &mut max_message_rows {
14889                    if *rows_left == 0 {
14890                        break;
14891                    } else {
14892                        *rows_left -= 1;
14893                    }
14894                }
14895                let _ = newline_indices.next();
14896            } else {
14897                break;
14898            }
14899        }
14900        let prev_len = text_without_backticks.len();
14901        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14902        text_without_backticks.push_str(new_text);
14903        if in_code_block {
14904            code_ranges.push(prev_len..text_without_backticks.len());
14905        }
14906        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14907        in_code_block = !in_code_block;
14908        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14909            text_without_backticks.push_str("...");
14910            break;
14911        }
14912    }
14913
14914    (text_without_backticks.into(), code_ranges)
14915}
14916
14917fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14918    match severity {
14919        DiagnosticSeverity::ERROR => colors.error,
14920        DiagnosticSeverity::WARNING => colors.warning,
14921        DiagnosticSeverity::INFORMATION => colors.info,
14922        DiagnosticSeverity::HINT => colors.info,
14923        _ => colors.ignored,
14924    }
14925}
14926
14927pub fn styled_runs_for_code_label<'a>(
14928    label: &'a CodeLabel,
14929    syntax_theme: &'a theme::SyntaxTheme,
14930) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14931    let fade_out = HighlightStyle {
14932        fade_out: Some(0.35),
14933        ..Default::default()
14934    };
14935
14936    let mut prev_end = label.filter_range.end;
14937    label
14938        .runs
14939        .iter()
14940        .enumerate()
14941        .flat_map(move |(ix, (range, highlight_id))| {
14942            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14943                style
14944            } else {
14945                return Default::default();
14946            };
14947            let mut muted_style = style;
14948            muted_style.highlight(fade_out);
14949
14950            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14951            if range.start >= label.filter_range.end {
14952                if range.start > prev_end {
14953                    runs.push((prev_end..range.start, fade_out));
14954                }
14955                runs.push((range.clone(), muted_style));
14956            } else if range.end <= label.filter_range.end {
14957                runs.push((range.clone(), style));
14958            } else {
14959                runs.push((range.start..label.filter_range.end, style));
14960                runs.push((label.filter_range.end..range.end, muted_style));
14961            }
14962            prev_end = cmp::max(prev_end, range.end);
14963
14964            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14965                runs.push((prev_end..label.text.len(), fade_out));
14966            }
14967
14968            runs
14969        })
14970}
14971
14972pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14973    let mut prev_index = 0;
14974    let mut prev_codepoint: Option<char> = None;
14975    text.char_indices()
14976        .chain([(text.len(), '\0')])
14977        .filter_map(move |(index, codepoint)| {
14978            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14979            let is_boundary = index == text.len()
14980                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14981                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14982            if is_boundary {
14983                let chunk = &text[prev_index..index];
14984                prev_index = index;
14985                Some(chunk)
14986            } else {
14987                None
14988            }
14989        })
14990}
14991
14992pub trait RangeToAnchorExt: Sized {
14993    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14994
14995    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14996        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14997        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14998    }
14999}
15000
15001impl<T: ToOffset> RangeToAnchorExt for Range<T> {
15002    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
15003        let start_offset = self.start.to_offset(snapshot);
15004        let end_offset = self.end.to_offset(snapshot);
15005        if start_offset == end_offset {
15006            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
15007        } else {
15008            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
15009        }
15010    }
15011}
15012
15013pub trait RowExt {
15014    fn as_f32(&self) -> f32;
15015
15016    fn next_row(&self) -> Self;
15017
15018    fn previous_row(&self) -> Self;
15019
15020    fn minus(&self, other: Self) -> u32;
15021}
15022
15023impl RowExt for DisplayRow {
15024    fn as_f32(&self) -> f32 {
15025        self.0 as f32
15026    }
15027
15028    fn next_row(&self) -> Self {
15029        Self(self.0 + 1)
15030    }
15031
15032    fn previous_row(&self) -> Self {
15033        Self(self.0.saturating_sub(1))
15034    }
15035
15036    fn minus(&self, other: Self) -> u32 {
15037        self.0 - other.0
15038    }
15039}
15040
15041impl RowExt for MultiBufferRow {
15042    fn as_f32(&self) -> f32 {
15043        self.0 as f32
15044    }
15045
15046    fn next_row(&self) -> Self {
15047        Self(self.0 + 1)
15048    }
15049
15050    fn previous_row(&self) -> Self {
15051        Self(self.0.saturating_sub(1))
15052    }
15053
15054    fn minus(&self, other: Self) -> u32 {
15055        self.0 - other.0
15056    }
15057}
15058
15059trait RowRangeExt {
15060    type Row;
15061
15062    fn len(&self) -> usize;
15063
15064    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15065}
15066
15067impl RowRangeExt for Range<MultiBufferRow> {
15068    type Row = MultiBufferRow;
15069
15070    fn len(&self) -> usize {
15071        (self.end.0 - self.start.0) as usize
15072    }
15073
15074    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15075        (self.start.0..self.end.0).map(MultiBufferRow)
15076    }
15077}
15078
15079impl RowRangeExt for Range<DisplayRow> {
15080    type Row = DisplayRow;
15081
15082    fn len(&self) -> usize {
15083        (self.end.0 - self.start.0) as usize
15084    }
15085
15086    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
15087        (self.start.0..self.end.0).map(DisplayRow)
15088    }
15089}
15090
15091fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15092    if hunk.diff_base_byte_range.is_empty() {
15093        DiffHunkStatus::Added
15094    } else if hunk.row_range.is_empty() {
15095        DiffHunkStatus::Removed
15096    } else {
15097        DiffHunkStatus::Modified
15098    }
15099}
15100
15101/// If select range has more than one line, we
15102/// just point the cursor to range.start.
15103fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15104    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15105        range
15106    } else {
15107        range.start..range.start
15108    }
15109}
15110
15111pub struct KillRing(ClipboardItem);
15112impl Global for KillRing {}
15113
15114const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);