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