editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51use ::git::diff::DiffHunkStatus;
   52pub(crate) use actions::*;
   53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{anyhow, Context as _, Result};
   56use blink_manager::BlinkManager;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::StringMatchCandidate;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   87    WeakView, WindowContext,
   88};
   89use highlight_matching_bracket::refresh_matching_bracket_highlights;
   90use hover_popover::{hide_hover, HoverState};
   91pub(crate) use hunk_diff::HoveredHunk;
   92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, DiagnosticEntry, Documentation, IndentKind, IndentSize, Language,
  103    OffsetRangeExt, Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    buffer_store::BufferChangeSet,
  132    lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
  133    project_settings::{GitGutterSetting, ProjectSettings},
  134    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  135    LspStore, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  136};
  137use rand::prelude::*;
  138use rpc::{proto::*, ErrorExt};
  139use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  140use selections_collection::{
  141    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  142};
  143use serde::{Deserialize, Serialize};
  144use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  145use smallvec::SmallVec;
  146use snippet::Snippet;
  147use std::{
  148    any::TypeId,
  149    borrow::Cow,
  150    cell::RefCell,
  151    cmp::{self, Ordering, Reverse},
  152    mem,
  153    num::NonZeroU32,
  154    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  155    path::{Path, PathBuf},
  156    rc::Rc,
  157    sync::Arc,
  158    time::{Duration, Instant},
  159};
  160pub use sum_tree::Bias;
  161use sum_tree::TreeMap;
  162use text::{BufferId, OffsetUtf16, Rope};
  163use theme::{
  164    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  165    ThemeColors, ThemeSettings,
  166};
  167use ui::{
  168    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  169    PopoverMenuHandle, Tooltip,
  170};
  171use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  172use workspace::item::{ItemHandle, PreviewTabsSettings};
  173use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  174use workspace::{
  175    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  176};
  177use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  178
  179use crate::hover_links::{find_url, find_url_from_range};
  180use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  181
  182pub const FILE_HEADER_HEIGHT: u32 = 2;
  183pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  184pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  185pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  186const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  187const MAX_LINE_LEN: usize = 1024;
  188const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  189const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  190pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  191#[doc(hidden)]
  192pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  193
  194pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  195pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  196
  197pub fn render_parsed_markdown(
  198    element_id: impl Into<ElementId>,
  199    parsed: &language::ParsedMarkdown,
  200    editor_style: &EditorStyle,
  201    workspace: Option<WeakView<Workspace>>,
  202    cx: &mut WindowContext,
  203) -> InteractiveText {
  204    let code_span_background_color = cx
  205        .theme()
  206        .colors()
  207        .editor_document_highlight_read_background;
  208
  209    let highlights = gpui::combine_highlights(
  210        parsed.highlights.iter().filter_map(|(range, highlight)| {
  211            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  212            Some((range.clone(), highlight))
  213        }),
  214        parsed
  215            .regions
  216            .iter()
  217            .zip(&parsed.region_ranges)
  218            .filter_map(|(region, range)| {
  219                if region.code {
  220                    Some((
  221                        range.clone(),
  222                        HighlightStyle {
  223                            background_color: Some(code_span_background_color),
  224                            ..Default::default()
  225                        },
  226                    ))
  227                } else {
  228                    None
  229                }
  230            }),
  231    );
  232
  233    let mut links = Vec::new();
  234    let mut link_ranges = Vec::new();
  235    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  236        if let Some(link) = region.link.clone() {
  237            links.push(link);
  238            link_ranges.push(range.clone());
  239        }
  240    }
  241
  242    InteractiveText::new(
  243        element_id,
  244        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  245    )
  246    .on_click(link_ranges, move |clicked_range_ix, cx| {
  247        match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace.open_abs_path(path.clone(), false, cx).detach();
  253                    });
  254                }
  255            }
  256        }
  257    })
  258}
  259
  260#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  261pub enum InlayId {
  262    InlineCompletion(usize),
  263    Hint(usize),
  264}
  265
  266impl InlayId {
  267    fn id(&self) -> usize {
  268        match self {
  269            Self::InlineCompletion(id) => *id,
  270            Self::Hint(id) => *id,
  271        }
  272    }
  273}
  274
  275enum DiffRowHighlight {}
  276enum DocumentHighlightRead {}
  277enum DocumentHighlightWrite {}
  278enum InputComposition {}
  279
  280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  281pub enum Navigated {
  282    Yes,
  283    No,
  284}
  285
  286impl Navigated {
  287    pub fn from_bool(yes: bool) -> Navigated {
  288        if yes {
  289            Navigated::Yes
  290        } else {
  291            Navigated::No
  292        }
  293    }
  294}
  295
  296pub fn init_settings(cx: &mut AppContext) {
  297    EditorSettings::register(cx);
  298}
  299
  300pub fn init(cx: &mut AppContext) {
  301    init_settings(cx);
  302
  303    workspace::register_project_item::<Editor>(cx);
  304    workspace::FollowableViewRegistry::register::<Editor>(cx);
  305    workspace::register_serializable_item::<Editor>(cx);
  306
  307    cx.observe_new_views(
  308        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  309            workspace.register_action(Editor::new_file);
  310            workspace.register_action(Editor::new_file_vertical);
  311            workspace.register_action(Editor::new_file_horizontal);
  312        },
  313    )
  314    .detach();
  315
  316    cx.on_action(move |_: &workspace::NewFile, cx| {
  317        let app_state = workspace::AppState::global(cx);
  318        if let Some(app_state) = app_state.upgrade() {
  319            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  320                Editor::new_file(workspace, &Default::default(), cx)
  321            })
  322            .detach();
  323        }
  324    });
  325    cx.on_action(move |_: &workspace::NewWindow, cx| {
  326        let app_state = workspace::AppState::global(cx);
  327        if let Some(app_state) = app_state.upgrade() {
  328            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  329                Editor::new_file(workspace, &Default::default(), cx)
  330            })
  331            .detach();
  332        }
  333    });
  334    git::project_diff::init(cx);
  335}
  336
  337pub struct SearchWithinRange;
  338
  339trait InvalidationRegion {
  340    fn ranges(&self) -> &[Range<Anchor>];
  341}
  342
  343#[derive(Clone, Debug, PartialEq)]
  344pub enum SelectPhase {
  345    Begin {
  346        position: DisplayPoint,
  347        add: bool,
  348        click_count: usize,
  349    },
  350    BeginColumnar {
  351        position: DisplayPoint,
  352        reset: bool,
  353        goal_column: u32,
  354    },
  355    Extend {
  356        position: DisplayPoint,
  357        click_count: usize,
  358    },
  359    Update {
  360        position: DisplayPoint,
  361        goal_column: u32,
  362        scroll_delta: gpui::Point<f32>,
  363    },
  364    End,
  365}
  366
  367#[derive(Clone, Debug)]
  368pub enum SelectMode {
  369    Character,
  370    Word(Range<Anchor>),
  371    Line(Range<Anchor>),
  372    All,
  373}
  374
  375#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  376pub enum EditorMode {
  377    SingleLine { auto_width: bool },
  378    AutoHeight { max_lines: usize },
  379    Full,
  380}
  381
  382#[derive(Copy, Clone, Debug)]
  383pub enum SoftWrap {
  384    /// Prefer not to wrap at all.
  385    ///
  386    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  387    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  388    GitDiff,
  389    /// Prefer a single line generally, unless an overly long line is encountered.
  390    None,
  391    /// Soft wrap lines that exceed the editor width.
  392    EditorWidth,
  393    /// Soft wrap lines at the preferred line length.
  394    Column(u32),
  395    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  396    Bounded(u32),
  397}
  398
  399#[derive(Clone)]
  400pub struct EditorStyle {
  401    pub background: Hsla,
  402    pub local_player: PlayerColor,
  403    pub text: TextStyle,
  404    pub scrollbar_width: Pixels,
  405    pub syntax: Arc<SyntaxTheme>,
  406    pub status: StatusColors,
  407    pub inlay_hints_style: HighlightStyle,
  408    pub inline_completion_styles: InlineCompletionStyles,
  409    pub unnecessary_code_fade: f32,
  410}
  411
  412impl Default for EditorStyle {
  413    fn default() -> Self {
  414        Self {
  415            background: Hsla::default(),
  416            local_player: PlayerColor::default(),
  417            text: TextStyle::default(),
  418            scrollbar_width: Pixels::default(),
  419            syntax: Default::default(),
  420            // HACK: Status colors don't have a real default.
  421            // We should look into removing the status colors from the editor
  422            // style and retrieve them directly from the theme.
  423            status: StatusColors::dark(),
  424            inlay_hints_style: HighlightStyle::default(),
  425            inline_completion_styles: InlineCompletionStyles {
  426                insertion: HighlightStyle::default(),
  427                whitespace: HighlightStyle::default(),
  428            },
  429            unnecessary_code_fade: Default::default(),
  430        }
  431    }
  432}
  433
  434pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  435    let show_background = language_settings::language_settings(None, None, cx)
  436        .inlay_hints
  437        .show_background;
  438
  439    HighlightStyle {
  440        color: Some(cx.theme().status().hint),
  441        background_color: show_background.then(|| cx.theme().status().hint_background),
  442        ..HighlightStyle::default()
  443    }
  444}
  445
  446pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  447    InlineCompletionStyles {
  448        insertion: HighlightStyle {
  449            color: Some(cx.theme().status().predictive),
  450            ..HighlightStyle::default()
  451        },
  452        whitespace: HighlightStyle {
  453            background_color: Some(cx.theme().status().created_background),
  454            ..HighlightStyle::default()
  455        },
  456    }
  457}
  458
  459type CompletionId = usize;
  460
  461#[derive(Debug, Clone)]
  462struct InlineCompletionMenuHint {
  463    provider_name: &'static str,
  464    text: InlineCompletionText,
  465}
  466
  467#[derive(Clone, Debug)]
  468enum InlineCompletionText {
  469    Move(SharedString),
  470    Edit {
  471        text: SharedString,
  472        highlights: Vec<(Range<usize>, HighlightStyle)>,
  473    },
  474}
  475
  476enum InlineCompletion {
  477    Edit(Vec<(Range<Anchor>, String)>),
  478    Move(Anchor),
  479}
  480
  481struct InlineCompletionState {
  482    inlay_ids: Vec<InlayId>,
  483    completion: InlineCompletion,
  484    invalidation_range: Range<Anchor>,
  485}
  486
  487enum InlineCompletionHighlight {}
  488
  489#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  490struct EditorActionId(usize);
  491
  492impl EditorActionId {
  493    pub fn post_inc(&mut self) -> Self {
  494        let answer = self.0;
  495
  496        *self = Self(answer + 1);
  497
  498        Self(answer)
  499    }
  500}
  501
  502// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  503// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  504
  505type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  506type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  507
  508#[derive(Default)]
  509struct ScrollbarMarkerState {
  510    scrollbar_size: Size<Pixels>,
  511    dirty: bool,
  512    markers: Arc<[PaintQuad]>,
  513    pending_refresh: Option<Task<Result<()>>>,
  514}
  515
  516impl ScrollbarMarkerState {
  517    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  518        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  519    }
  520}
  521
  522#[derive(Clone, Debug)]
  523struct RunnableTasks {
  524    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  525    offset: MultiBufferOffset,
  526    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  527    column: u32,
  528    // Values of all named captures, including those starting with '_'
  529    extra_variables: HashMap<String, String>,
  530    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  531    context_range: Range<BufferOffset>,
  532}
  533
  534impl RunnableTasks {
  535    fn resolve<'a>(
  536        &'a self,
  537        cx: &'a task::TaskContext,
  538    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  539        self.templates.iter().filter_map(|(kind, template)| {
  540            template
  541                .resolve_task(&kind.to_id_base(), cx)
  542                .map(|task| (kind.clone(), task))
  543        })
  544    }
  545}
  546
  547#[derive(Clone)]
  548struct ResolvedTasks {
  549    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  550    position: Anchor,
  551}
  552#[derive(Copy, Clone, Debug)]
  553struct MultiBufferOffset(usize);
  554#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  555struct BufferOffset(usize);
  556
  557// Addons allow storing per-editor state in other crates (e.g. Vim)
  558pub trait Addon: 'static {
  559    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  560
  561    fn to_any(&self) -> &dyn std::any::Any;
  562}
  563
  564#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  565pub enum IsVimMode {
  566    Yes,
  567    No,
  568}
  569
  570/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  571///
  572/// See the [module level documentation](self) for more information.
  573pub struct Editor {
  574    focus_handle: FocusHandle,
  575    last_focused_descendant: Option<WeakFocusHandle>,
  576    /// The text buffer being edited
  577    buffer: Model<MultiBuffer>,
  578    /// Map of how text in the buffer should be displayed.
  579    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  580    pub display_map: Model<DisplayMap>,
  581    pub selections: SelectionsCollection,
  582    pub scroll_manager: ScrollManager,
  583    /// When inline assist editors are linked, they all render cursors because
  584    /// typing enters text into each of them, even the ones that aren't focused.
  585    pub(crate) show_cursor_when_unfocused: bool,
  586    columnar_selection_tail: Option<Anchor>,
  587    add_selections_state: Option<AddSelectionsState>,
  588    select_next_state: Option<SelectNextState>,
  589    select_prev_state: Option<SelectNextState>,
  590    selection_history: SelectionHistory,
  591    autoclose_regions: Vec<AutocloseRegion>,
  592    snippet_stack: InvalidationStack<SnippetState>,
  593    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  594    ime_transaction: Option<TransactionId>,
  595    active_diagnostics: Option<ActiveDiagnosticGroup>,
  596    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  597
  598    project: Option<Model<Project>>,
  599    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  600    completion_provider: Option<Box<dyn CompletionProvider>>,
  601    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  602    blink_manager: Model<BlinkManager>,
  603    show_cursor_names: bool,
  604    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  605    pub show_local_selections: bool,
  606    mode: EditorMode,
  607    show_breadcrumbs: bool,
  608    show_gutter: bool,
  609    show_scrollbars: bool,
  610    show_line_numbers: Option<bool>,
  611    use_relative_line_numbers: Option<bool>,
  612    show_git_diff_gutter: Option<bool>,
  613    show_code_actions: Option<bool>,
  614    show_runnables: Option<bool>,
  615    show_wrap_guides: Option<bool>,
  616    show_indent_guides: Option<bool>,
  617    placeholder_text: Option<Arc<str>>,
  618    highlight_order: usize,
  619    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  620    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  621    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  622    scrollbar_marker_state: ScrollbarMarkerState,
  623    active_indent_guides_state: ActiveIndentGuidesState,
  624    nav_history: Option<ItemNavHistory>,
  625    context_menu: RefCell<Option<CodeContextMenu>>,
  626    mouse_context_menu: Option<MouseContextMenu>,
  627    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  628    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  629    signature_help_state: SignatureHelpState,
  630    auto_signature_help: Option<bool>,
  631    find_all_references_task_sources: Vec<Anchor>,
  632    next_completion_id: CompletionId,
  633    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  634    code_actions_task: Option<Task<Result<()>>>,
  635    document_highlights_task: Option<Task<()>>,
  636    linked_editing_range_task: Option<Task<Option<()>>>,
  637    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  638    pending_rename: Option<RenameState>,
  639    searchable: bool,
  640    cursor_shape: CursorShape,
  641    current_line_highlight: Option<CurrentLineHighlight>,
  642    collapse_matches: bool,
  643    autoindent_mode: Option<AutoindentMode>,
  644    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  645    input_enabled: bool,
  646    use_modal_editing: bool,
  647    read_only: bool,
  648    leader_peer_id: Option<PeerId>,
  649    remote_id: Option<ViewId>,
  650    hover_state: HoverState,
  651    gutter_hovered: bool,
  652    hovered_link_state: Option<HoveredLinkState>,
  653    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  654    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  655    active_inline_completion: Option<InlineCompletionState>,
  656    // enable_inline_completions is a switch that Vim can use to disable
  657    // inline completions based on its mode.
  658    enable_inline_completions: bool,
  659    show_inline_completions_override: Option<bool>,
  660    inlay_hint_cache: InlayHintCache,
  661    diff_map: DiffMap,
  662    next_inlay_id: usize,
  663    _subscriptions: Vec<Subscription>,
  664    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  665    gutter_dimensions: GutterDimensions,
  666    style: Option<EditorStyle>,
  667    text_style_refinement: Option<TextStyleRefinement>,
  668    next_editor_action_id: EditorActionId,
  669    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  670    use_autoclose: bool,
  671    use_auto_surround: bool,
  672    auto_replace_emoji_shortcode: bool,
  673    show_git_blame_gutter: bool,
  674    show_git_blame_inline: bool,
  675    show_git_blame_inline_delay_task: Option<Task<()>>,
  676    git_blame_inline_enabled: bool,
  677    serialize_dirty_buffers: bool,
  678    show_selection_menu: Option<bool>,
  679    blame: Option<Model<GitBlame>>,
  680    blame_subscription: Option<Subscription>,
  681    custom_context_menu: Option<
  682        Box<
  683            dyn 'static
  684                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  685        >,
  686    >,
  687    last_bounds: Option<Bounds<Pixels>>,
  688    expect_bounds_change: Option<Bounds<Pixels>>,
  689    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  690    tasks_update_task: Option<Task<()>>,
  691    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  692    breadcrumb_header: Option<String>,
  693    focused_block: Option<FocusedBlock>,
  694    next_scroll_position: NextScrollCursorCenterTopBottom,
  695    addons: HashMap<TypeId, Box<dyn Addon>>,
  696    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  697    toggle_fold_multiple_buffers: Task<()>,
  698    _scroll_cursor_center_top_bottom_task: Task<()>,
  699}
  700
  701#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  702enum NextScrollCursorCenterTopBottom {
  703    #[default]
  704    Center,
  705    Top,
  706    Bottom,
  707}
  708
  709impl NextScrollCursorCenterTopBottom {
  710    fn next(&self) -> Self {
  711        match self {
  712            Self::Center => Self::Top,
  713            Self::Top => Self::Bottom,
  714            Self::Bottom => Self::Center,
  715        }
  716    }
  717}
  718
  719#[derive(Clone)]
  720pub struct EditorSnapshot {
  721    pub mode: EditorMode,
  722    show_gutter: bool,
  723    show_line_numbers: Option<bool>,
  724    show_git_diff_gutter: Option<bool>,
  725    show_code_actions: Option<bool>,
  726    show_runnables: Option<bool>,
  727    git_blame_gutter_max_author_length: Option<usize>,
  728    pub display_snapshot: DisplaySnapshot,
  729    pub placeholder_text: Option<Arc<str>>,
  730    diff_map: DiffMapSnapshot,
  731    is_focused: bool,
  732    scroll_anchor: ScrollAnchor,
  733    ongoing_scroll: OngoingScroll,
  734    current_line_highlight: CurrentLineHighlight,
  735    gutter_hovered: bool,
  736}
  737
  738const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  739
  740#[derive(Default, Debug, Clone, Copy)]
  741pub struct GutterDimensions {
  742    pub left_padding: Pixels,
  743    pub right_padding: Pixels,
  744    pub width: Pixels,
  745    pub margin: Pixels,
  746    pub git_blame_entries_width: Option<Pixels>,
  747}
  748
  749impl GutterDimensions {
  750    /// The full width of the space taken up by the gutter.
  751    pub fn full_width(&self) -> Pixels {
  752        self.margin + self.width
  753    }
  754
  755    /// The width of the space reserved for the fold indicators,
  756    /// use alongside 'justify_end' and `gutter_width` to
  757    /// right align content with the line numbers
  758    pub fn fold_area_width(&self) -> Pixels {
  759        self.margin + self.right_padding
  760    }
  761}
  762
  763#[derive(Debug)]
  764pub struct RemoteSelection {
  765    pub replica_id: ReplicaId,
  766    pub selection: Selection<Anchor>,
  767    pub cursor_shape: CursorShape,
  768    pub peer_id: PeerId,
  769    pub line_mode: bool,
  770    pub participant_index: Option<ParticipantIndex>,
  771    pub user_name: Option<SharedString>,
  772}
  773
  774#[derive(Clone, Debug)]
  775struct SelectionHistoryEntry {
  776    selections: Arc<[Selection<Anchor>]>,
  777    select_next_state: Option<SelectNextState>,
  778    select_prev_state: Option<SelectNextState>,
  779    add_selections_state: Option<AddSelectionsState>,
  780}
  781
  782enum SelectionHistoryMode {
  783    Normal,
  784    Undoing,
  785    Redoing,
  786}
  787
  788#[derive(Clone, PartialEq, Eq, Hash)]
  789struct HoveredCursor {
  790    replica_id: u16,
  791    selection_id: usize,
  792}
  793
  794impl Default for SelectionHistoryMode {
  795    fn default() -> Self {
  796        Self::Normal
  797    }
  798}
  799
  800#[derive(Default)]
  801struct SelectionHistory {
  802    #[allow(clippy::type_complexity)]
  803    selections_by_transaction:
  804        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  805    mode: SelectionHistoryMode,
  806    undo_stack: VecDeque<SelectionHistoryEntry>,
  807    redo_stack: VecDeque<SelectionHistoryEntry>,
  808}
  809
  810impl SelectionHistory {
  811    fn insert_transaction(
  812        &mut self,
  813        transaction_id: TransactionId,
  814        selections: Arc<[Selection<Anchor>]>,
  815    ) {
  816        self.selections_by_transaction
  817            .insert(transaction_id, (selections, None));
  818    }
  819
  820    #[allow(clippy::type_complexity)]
  821    fn transaction(
  822        &self,
  823        transaction_id: TransactionId,
  824    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  825        self.selections_by_transaction.get(&transaction_id)
  826    }
  827
  828    #[allow(clippy::type_complexity)]
  829    fn transaction_mut(
  830        &mut self,
  831        transaction_id: TransactionId,
  832    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  833        self.selections_by_transaction.get_mut(&transaction_id)
  834    }
  835
  836    fn push(&mut self, entry: SelectionHistoryEntry) {
  837        if !entry.selections.is_empty() {
  838            match self.mode {
  839                SelectionHistoryMode::Normal => {
  840                    self.push_undo(entry);
  841                    self.redo_stack.clear();
  842                }
  843                SelectionHistoryMode::Undoing => self.push_redo(entry),
  844                SelectionHistoryMode::Redoing => self.push_undo(entry),
  845            }
  846        }
  847    }
  848
  849    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  850        if self
  851            .undo_stack
  852            .back()
  853            .map_or(true, |e| e.selections != entry.selections)
  854        {
  855            self.undo_stack.push_back(entry);
  856            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  857                self.undo_stack.pop_front();
  858            }
  859        }
  860    }
  861
  862    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  863        if self
  864            .redo_stack
  865            .back()
  866            .map_or(true, |e| e.selections != entry.selections)
  867        {
  868            self.redo_stack.push_back(entry);
  869            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  870                self.redo_stack.pop_front();
  871            }
  872        }
  873    }
  874}
  875
  876struct RowHighlight {
  877    index: usize,
  878    range: Range<Anchor>,
  879    color: Hsla,
  880    should_autoscroll: bool,
  881}
  882
  883#[derive(Clone, Debug)]
  884struct AddSelectionsState {
  885    above: bool,
  886    stack: Vec<usize>,
  887}
  888
  889#[derive(Clone)]
  890struct SelectNextState {
  891    query: AhoCorasick,
  892    wordwise: bool,
  893    done: bool,
  894}
  895
  896impl std::fmt::Debug for SelectNextState {
  897    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  898        f.debug_struct(std::any::type_name::<Self>())
  899            .field("wordwise", &self.wordwise)
  900            .field("done", &self.done)
  901            .finish()
  902    }
  903}
  904
  905#[derive(Debug)]
  906struct AutocloseRegion {
  907    selection_id: usize,
  908    range: Range<Anchor>,
  909    pair: BracketPair,
  910}
  911
  912#[derive(Debug)]
  913struct SnippetState {
  914    ranges: Vec<Vec<Range<Anchor>>>,
  915    active_index: usize,
  916    choices: Vec<Option<Vec<String>>>,
  917}
  918
  919#[doc(hidden)]
  920pub struct RenameState {
  921    pub range: Range<Anchor>,
  922    pub old_name: Arc<str>,
  923    pub editor: View<Editor>,
  924    block_id: CustomBlockId,
  925}
  926
  927struct InvalidationStack<T>(Vec<T>);
  928
  929struct RegisteredInlineCompletionProvider {
  930    provider: Arc<dyn InlineCompletionProviderHandle>,
  931    _subscription: Subscription,
  932}
  933
  934#[derive(Debug)]
  935struct ActiveDiagnosticGroup {
  936    primary_range: Range<Anchor>,
  937    primary_message: String,
  938    group_id: usize,
  939    blocks: HashMap<CustomBlockId, Diagnostic>,
  940    is_valid: bool,
  941}
  942
  943#[derive(Serialize, Deserialize, Clone, Debug)]
  944pub struct ClipboardSelection {
  945    pub len: usize,
  946    pub is_entire_line: bool,
  947    pub first_line_indent: u32,
  948}
  949
  950#[derive(Debug)]
  951pub(crate) struct NavigationData {
  952    cursor_anchor: Anchor,
  953    cursor_position: Point,
  954    scroll_anchor: ScrollAnchor,
  955    scroll_top_row: u32,
  956}
  957
  958#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  959pub enum GotoDefinitionKind {
  960    Symbol,
  961    Declaration,
  962    Type,
  963    Implementation,
  964}
  965
  966#[derive(Debug, Clone)]
  967enum InlayHintRefreshReason {
  968    Toggle(bool),
  969    SettingsChange(InlayHintSettings),
  970    NewLinesShown,
  971    BufferEdited(HashSet<Arc<Language>>),
  972    RefreshRequested,
  973    ExcerptsRemoved(Vec<ExcerptId>),
  974}
  975
  976impl InlayHintRefreshReason {
  977    fn description(&self) -> &'static str {
  978        match self {
  979            Self::Toggle(_) => "toggle",
  980            Self::SettingsChange(_) => "settings change",
  981            Self::NewLinesShown => "new lines shown",
  982            Self::BufferEdited(_) => "buffer edited",
  983            Self::RefreshRequested => "refresh requested",
  984            Self::ExcerptsRemoved(_) => "excerpts removed",
  985        }
  986    }
  987}
  988
  989pub(crate) struct FocusedBlock {
  990    id: BlockId,
  991    focus_handle: WeakFocusHandle,
  992}
  993
  994#[derive(Clone)]
  995enum JumpData {
  996    MultiBufferRow {
  997        row: MultiBufferRow,
  998        line_offset_from_top: u32,
  999    },
 1000    MultiBufferPoint {
 1001        excerpt_id: ExcerptId,
 1002        position: Point,
 1003        anchor: text::Anchor,
 1004        line_offset_from_top: u32,
 1005    },
 1006}
 1007
 1008impl Editor {
 1009    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1010        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1011        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1012        Self::new(
 1013            EditorMode::SingleLine { auto_width: false },
 1014            buffer,
 1015            None,
 1016            false,
 1017            cx,
 1018        )
 1019    }
 1020
 1021    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1022        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1023        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1024        Self::new(EditorMode::Full, buffer, None, false, cx)
 1025    }
 1026
 1027    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1028        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1029        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1030        Self::new(
 1031            EditorMode::SingleLine { auto_width: true },
 1032            buffer,
 1033            None,
 1034            false,
 1035            cx,
 1036        )
 1037    }
 1038
 1039    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1040        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1041        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1042        Self::new(
 1043            EditorMode::AutoHeight { max_lines },
 1044            buffer,
 1045            None,
 1046            false,
 1047            cx,
 1048        )
 1049    }
 1050
 1051    pub fn for_buffer(
 1052        buffer: Model<Buffer>,
 1053        project: Option<Model<Project>>,
 1054        cx: &mut ViewContext<Self>,
 1055    ) -> Self {
 1056        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1057        Self::new(EditorMode::Full, buffer, project, false, cx)
 1058    }
 1059
 1060    pub fn for_multibuffer(
 1061        buffer: Model<MultiBuffer>,
 1062        project: Option<Model<Project>>,
 1063        show_excerpt_controls: bool,
 1064        cx: &mut ViewContext<Self>,
 1065    ) -> Self {
 1066        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1067    }
 1068
 1069    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1070        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1071        let mut clone = Self::new(
 1072            self.mode,
 1073            self.buffer.clone(),
 1074            self.project.clone(),
 1075            show_excerpt_controls,
 1076            cx,
 1077        );
 1078        self.display_map.update(cx, |display_map, cx| {
 1079            let snapshot = display_map.snapshot(cx);
 1080            clone.display_map.update(cx, |display_map, cx| {
 1081                display_map.set_state(&snapshot, cx);
 1082            });
 1083        });
 1084        clone.selections.clone_state(&self.selections);
 1085        clone.scroll_manager.clone_state(&self.scroll_manager);
 1086        clone.searchable = self.searchable;
 1087        clone
 1088    }
 1089
 1090    pub fn new(
 1091        mode: EditorMode,
 1092        buffer: Model<MultiBuffer>,
 1093        project: Option<Model<Project>>,
 1094        show_excerpt_controls: bool,
 1095        cx: &mut ViewContext<Self>,
 1096    ) -> Self {
 1097        let style = cx.text_style();
 1098        let font_size = style.font_size.to_pixels(cx.rem_size());
 1099        let editor = cx.view().downgrade();
 1100        let fold_placeholder = FoldPlaceholder {
 1101            constrain_width: true,
 1102            render: Arc::new(move |fold_id, fold_range, cx| {
 1103                let editor = editor.clone();
 1104                div()
 1105                    .id(fold_id)
 1106                    .bg(cx.theme().colors().ghost_element_background)
 1107                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1108                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1109                    .rounded_sm()
 1110                    .size_full()
 1111                    .cursor_pointer()
 1112                    .child("")
 1113                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1114                    .on_click(move |_, cx| {
 1115                        editor
 1116                            .update(cx, |editor, cx| {
 1117                                editor.unfold_ranges(
 1118                                    &[fold_range.start..fold_range.end],
 1119                                    true,
 1120                                    false,
 1121                                    cx,
 1122                                );
 1123                                cx.stop_propagation();
 1124                            })
 1125                            .ok();
 1126                    })
 1127                    .into_any()
 1128            }),
 1129            merge_adjacent: true,
 1130            ..Default::default()
 1131        };
 1132        let display_map = cx.new_model(|cx| {
 1133            DisplayMap::new(
 1134                buffer.clone(),
 1135                style.font(),
 1136                font_size,
 1137                None,
 1138                show_excerpt_controls,
 1139                FILE_HEADER_HEIGHT,
 1140                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1141                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1142                fold_placeholder,
 1143                cx,
 1144            )
 1145        });
 1146
 1147        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1148
 1149        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1150
 1151        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1152            .then(|| language_settings::SoftWrap::None);
 1153
 1154        let mut project_subscriptions = Vec::new();
 1155        if mode == EditorMode::Full {
 1156            if let Some(project) = project.as_ref() {
 1157                if buffer.read(cx).is_singleton() {
 1158                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1159                        cx.emit(EditorEvent::TitleChanged);
 1160                    }));
 1161                }
 1162                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1163                    if let project::Event::RefreshInlayHints = event {
 1164                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1165                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1166                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1167                            let focus_handle = editor.focus_handle(cx);
 1168                            if focus_handle.is_focused(cx) {
 1169                                let snapshot = buffer.read(cx).snapshot();
 1170                                for (range, snippet) in snippet_edits {
 1171                                    let editor_range =
 1172                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1173                                    editor
 1174                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1175                                        .ok();
 1176                                }
 1177                            }
 1178                        }
 1179                    }
 1180                }));
 1181                if let Some(task_inventory) = project
 1182                    .read(cx)
 1183                    .task_store()
 1184                    .read(cx)
 1185                    .task_inventory()
 1186                    .cloned()
 1187                {
 1188                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1189                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1190                    }));
 1191                }
 1192            }
 1193        }
 1194
 1195        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1196
 1197        let inlay_hint_settings =
 1198            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1199        let focus_handle = cx.focus_handle();
 1200        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1201        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1202            .detach();
 1203        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1204            .detach();
 1205        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1206
 1207        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1208            Some(false)
 1209        } else {
 1210            None
 1211        };
 1212
 1213        let mut code_action_providers = Vec::new();
 1214        if let Some(project) = project.clone() {
 1215            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1216            code_action_providers.push(Rc::new(project) as Rc<_>);
 1217        }
 1218
 1219        let mut this = Self {
 1220            focus_handle,
 1221            show_cursor_when_unfocused: false,
 1222            last_focused_descendant: None,
 1223            buffer: buffer.clone(),
 1224            display_map: display_map.clone(),
 1225            selections,
 1226            scroll_manager: ScrollManager::new(cx),
 1227            columnar_selection_tail: None,
 1228            add_selections_state: None,
 1229            select_next_state: None,
 1230            select_prev_state: None,
 1231            selection_history: Default::default(),
 1232            autoclose_regions: Default::default(),
 1233            snippet_stack: Default::default(),
 1234            select_larger_syntax_node_stack: Vec::new(),
 1235            ime_transaction: Default::default(),
 1236            active_diagnostics: None,
 1237            soft_wrap_mode_override,
 1238            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1239            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1240            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1241            project,
 1242            blink_manager: blink_manager.clone(),
 1243            show_local_selections: true,
 1244            show_scrollbars: true,
 1245            mode,
 1246            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1247            show_gutter: mode == EditorMode::Full,
 1248            show_line_numbers: None,
 1249            use_relative_line_numbers: None,
 1250            show_git_diff_gutter: None,
 1251            show_code_actions: None,
 1252            show_runnables: None,
 1253            show_wrap_guides: None,
 1254            show_indent_guides,
 1255            placeholder_text: None,
 1256            highlight_order: 0,
 1257            highlighted_rows: HashMap::default(),
 1258            background_highlights: Default::default(),
 1259            gutter_highlights: TreeMap::default(),
 1260            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1261            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1262            nav_history: None,
 1263            context_menu: RefCell::new(None),
 1264            mouse_context_menu: None,
 1265            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1266            completion_tasks: Default::default(),
 1267            signature_help_state: SignatureHelpState::default(),
 1268            auto_signature_help: None,
 1269            find_all_references_task_sources: Vec::new(),
 1270            next_completion_id: 0,
 1271            next_inlay_id: 0,
 1272            code_action_providers,
 1273            available_code_actions: Default::default(),
 1274            code_actions_task: Default::default(),
 1275            document_highlights_task: Default::default(),
 1276            linked_editing_range_task: Default::default(),
 1277            pending_rename: Default::default(),
 1278            searchable: true,
 1279            cursor_shape: EditorSettings::get_global(cx)
 1280                .cursor_shape
 1281                .unwrap_or_default(),
 1282            current_line_highlight: None,
 1283            autoindent_mode: Some(AutoindentMode::EachLine),
 1284            collapse_matches: false,
 1285            workspace: None,
 1286            input_enabled: true,
 1287            use_modal_editing: mode == EditorMode::Full,
 1288            read_only: false,
 1289            use_autoclose: true,
 1290            use_auto_surround: true,
 1291            auto_replace_emoji_shortcode: false,
 1292            leader_peer_id: None,
 1293            remote_id: None,
 1294            hover_state: Default::default(),
 1295            hovered_link_state: Default::default(),
 1296            inline_completion_provider: None,
 1297            active_inline_completion: None,
 1298            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1299            diff_map: DiffMap::default(),
 1300            gutter_hovered: false,
 1301            pixel_position_of_newest_cursor: None,
 1302            last_bounds: None,
 1303            expect_bounds_change: None,
 1304            gutter_dimensions: GutterDimensions::default(),
 1305            style: None,
 1306            show_cursor_names: false,
 1307            hovered_cursors: Default::default(),
 1308            next_editor_action_id: EditorActionId::default(),
 1309            editor_actions: Rc::default(),
 1310            show_inline_completions_override: None,
 1311            enable_inline_completions: true,
 1312            custom_context_menu: None,
 1313            show_git_blame_gutter: false,
 1314            show_git_blame_inline: false,
 1315            show_selection_menu: None,
 1316            show_git_blame_inline_delay_task: None,
 1317            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1318            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1319                .session
 1320                .restore_unsaved_buffers,
 1321            blame: None,
 1322            blame_subscription: None,
 1323            tasks: Default::default(),
 1324            _subscriptions: vec![
 1325                cx.observe(&buffer, Self::on_buffer_changed),
 1326                cx.subscribe(&buffer, Self::on_buffer_event),
 1327                cx.observe(&display_map, Self::on_display_map_changed),
 1328                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1329                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1330                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1331                cx.observe_window_activation(|editor, cx| {
 1332                    let active = cx.is_window_active();
 1333                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1334                        if active {
 1335                            blink_manager.enable(cx);
 1336                        } else {
 1337                            blink_manager.disable(cx);
 1338                        }
 1339                    });
 1340                }),
 1341            ],
 1342            tasks_update_task: None,
 1343            linked_edit_ranges: Default::default(),
 1344            previous_search_ranges: None,
 1345            breadcrumb_header: None,
 1346            focused_block: None,
 1347            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1348            addons: HashMap::default(),
 1349            registered_buffers: HashMap::default(),
 1350            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1351            toggle_fold_multiple_buffers: Task::ready(()),
 1352            text_style_refinement: None,
 1353        };
 1354        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1355        this._subscriptions.extend(project_subscriptions);
 1356
 1357        this.end_selection(cx);
 1358        this.scroll_manager.show_scrollbar(cx);
 1359
 1360        if mode == EditorMode::Full {
 1361            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1362            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1363
 1364            if this.git_blame_inline_enabled {
 1365                this.git_blame_inline_enabled = true;
 1366                this.start_git_blame_inline(false, cx);
 1367            }
 1368
 1369            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1370                if let Some(project) = this.project.as_ref() {
 1371                    let lsp_store = project.read(cx).lsp_store();
 1372                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1373                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1374                    });
 1375                    this.registered_buffers
 1376                        .insert(buffer.read(cx).remote_id(), handle);
 1377                }
 1378            }
 1379        }
 1380
 1381        this.report_editor_event("Editor Opened", None, cx);
 1382        this
 1383    }
 1384
 1385    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1386        self.mouse_context_menu
 1387            .as_ref()
 1388            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1389    }
 1390
 1391    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1392        let mut key_context = KeyContext::new_with_defaults();
 1393        key_context.add("Editor");
 1394        let mode = match self.mode {
 1395            EditorMode::SingleLine { .. } => "single_line",
 1396            EditorMode::AutoHeight { .. } => "auto_height",
 1397            EditorMode::Full => "full",
 1398        };
 1399
 1400        if EditorSettings::jupyter_enabled(cx) {
 1401            key_context.add("jupyter");
 1402        }
 1403
 1404        key_context.set("mode", mode);
 1405        if self.pending_rename.is_some() {
 1406            key_context.add("renaming");
 1407        }
 1408        match self.context_menu.borrow().as_ref() {
 1409            Some(CodeContextMenu::Completions(_)) => {
 1410                key_context.add("menu");
 1411                key_context.add("showing_completions")
 1412            }
 1413            Some(CodeContextMenu::CodeActions(_)) => {
 1414                key_context.add("menu");
 1415                key_context.add("showing_code_actions")
 1416            }
 1417            None => {}
 1418        }
 1419
 1420        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1421        if !self.focus_handle(cx).contains_focused(cx)
 1422            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1423        {
 1424            for addon in self.addons.values() {
 1425                addon.extend_key_context(&mut key_context, cx)
 1426            }
 1427        }
 1428
 1429        if let Some(extension) = self
 1430            .buffer
 1431            .read(cx)
 1432            .as_singleton()
 1433            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1434        {
 1435            key_context.set("extension", extension.to_string());
 1436        }
 1437
 1438        if self.has_active_inline_completion() {
 1439            key_context.add("copilot_suggestion");
 1440            key_context.add("inline_completion");
 1441        }
 1442
 1443        if !self
 1444            .selections
 1445            .disjoint
 1446            .iter()
 1447            .all(|selection| selection.start == selection.end)
 1448        {
 1449            key_context.add("selection");
 1450        }
 1451
 1452        key_context
 1453    }
 1454
 1455    pub fn new_file(
 1456        workspace: &mut Workspace,
 1457        _: &workspace::NewFile,
 1458        cx: &mut ViewContext<Workspace>,
 1459    ) {
 1460        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1461            "Failed to create buffer",
 1462            cx,
 1463            |e, _| match e.error_code() {
 1464                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1465                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1466                e.error_tag("required").unwrap_or("the latest version")
 1467            )),
 1468                _ => None,
 1469            },
 1470        );
 1471    }
 1472
 1473    pub fn new_in_workspace(
 1474        workspace: &mut Workspace,
 1475        cx: &mut ViewContext<Workspace>,
 1476    ) -> Task<Result<View<Editor>>> {
 1477        let project = workspace.project().clone();
 1478        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1479
 1480        cx.spawn(|workspace, mut cx| async move {
 1481            let buffer = create.await?;
 1482            workspace.update(&mut cx, |workspace, cx| {
 1483                let editor =
 1484                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1485                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1486                editor
 1487            })
 1488        })
 1489    }
 1490
 1491    fn new_file_vertical(
 1492        workspace: &mut Workspace,
 1493        _: &workspace::NewFileSplitVertical,
 1494        cx: &mut ViewContext<Workspace>,
 1495    ) {
 1496        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1497    }
 1498
 1499    fn new_file_horizontal(
 1500        workspace: &mut Workspace,
 1501        _: &workspace::NewFileSplitHorizontal,
 1502        cx: &mut ViewContext<Workspace>,
 1503    ) {
 1504        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1505    }
 1506
 1507    fn new_file_in_direction(
 1508        workspace: &mut Workspace,
 1509        direction: SplitDirection,
 1510        cx: &mut ViewContext<Workspace>,
 1511    ) {
 1512        let project = workspace.project().clone();
 1513        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1514
 1515        cx.spawn(|workspace, mut cx| async move {
 1516            let buffer = create.await?;
 1517            workspace.update(&mut cx, move |workspace, cx| {
 1518                workspace.split_item(
 1519                    direction,
 1520                    Box::new(
 1521                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1522                    ),
 1523                    cx,
 1524                )
 1525            })?;
 1526            anyhow::Ok(())
 1527        })
 1528        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1529            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1530                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1531                e.error_tag("required").unwrap_or("the latest version")
 1532            )),
 1533            _ => None,
 1534        });
 1535    }
 1536
 1537    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1538        self.leader_peer_id
 1539    }
 1540
 1541    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1542        &self.buffer
 1543    }
 1544
 1545    pub fn workspace(&self) -> Option<View<Workspace>> {
 1546        self.workspace.as_ref()?.0.upgrade()
 1547    }
 1548
 1549    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1550        self.buffer().read(cx).title(cx)
 1551    }
 1552
 1553    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1554        let git_blame_gutter_max_author_length = self
 1555            .render_git_blame_gutter(cx)
 1556            .then(|| {
 1557                if let Some(blame) = self.blame.as_ref() {
 1558                    let max_author_length =
 1559                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1560                    Some(max_author_length)
 1561                } else {
 1562                    None
 1563                }
 1564            })
 1565            .flatten();
 1566
 1567        EditorSnapshot {
 1568            mode: self.mode,
 1569            show_gutter: self.show_gutter,
 1570            show_line_numbers: self.show_line_numbers,
 1571            show_git_diff_gutter: self.show_git_diff_gutter,
 1572            show_code_actions: self.show_code_actions,
 1573            show_runnables: self.show_runnables,
 1574            git_blame_gutter_max_author_length,
 1575            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1576            scroll_anchor: self.scroll_manager.anchor(),
 1577            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1578            placeholder_text: self.placeholder_text.clone(),
 1579            diff_map: self.diff_map.snapshot(),
 1580            is_focused: self.focus_handle.is_focused(cx),
 1581            current_line_highlight: self
 1582                .current_line_highlight
 1583                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1584            gutter_hovered: self.gutter_hovered,
 1585        }
 1586    }
 1587
 1588    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1589        self.buffer.read(cx).language_at(point, cx)
 1590    }
 1591
 1592    pub fn file_at<T: ToOffset>(
 1593        &self,
 1594        point: T,
 1595        cx: &AppContext,
 1596    ) -> Option<Arc<dyn language::File>> {
 1597        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1598    }
 1599
 1600    pub fn active_excerpt(
 1601        &self,
 1602        cx: &AppContext,
 1603    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1604        self.buffer
 1605            .read(cx)
 1606            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1607    }
 1608
 1609    pub fn mode(&self) -> EditorMode {
 1610        self.mode
 1611    }
 1612
 1613    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1614        self.collaboration_hub.as_deref()
 1615    }
 1616
 1617    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1618        self.collaboration_hub = Some(hub);
 1619    }
 1620
 1621    pub fn set_custom_context_menu(
 1622        &mut self,
 1623        f: impl 'static
 1624            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1625    ) {
 1626        self.custom_context_menu = Some(Box::new(f))
 1627    }
 1628
 1629    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1630        self.completion_provider = provider;
 1631    }
 1632
 1633    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1634        self.semantics_provider.clone()
 1635    }
 1636
 1637    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1638        self.semantics_provider = provider;
 1639    }
 1640
 1641    pub fn set_inline_completion_provider<T>(
 1642        &mut self,
 1643        provider: Option<Model<T>>,
 1644        cx: &mut ViewContext<Self>,
 1645    ) where
 1646        T: InlineCompletionProvider,
 1647    {
 1648        self.inline_completion_provider =
 1649            provider.map(|provider| RegisteredInlineCompletionProvider {
 1650                _subscription: cx.observe(&provider, |this, _, cx| {
 1651                    if this.focus_handle.is_focused(cx) {
 1652                        this.update_visible_inline_completion(cx);
 1653                    }
 1654                }),
 1655                provider: Arc::new(provider),
 1656            });
 1657        self.refresh_inline_completion(false, false, cx);
 1658    }
 1659
 1660    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1661        self.placeholder_text.as_deref()
 1662    }
 1663
 1664    pub fn set_placeholder_text(
 1665        &mut self,
 1666        placeholder_text: impl Into<Arc<str>>,
 1667        cx: &mut ViewContext<Self>,
 1668    ) {
 1669        let placeholder_text = Some(placeholder_text.into());
 1670        if self.placeholder_text != placeholder_text {
 1671            self.placeholder_text = placeholder_text;
 1672            cx.notify();
 1673        }
 1674    }
 1675
 1676    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1677        self.cursor_shape = cursor_shape;
 1678
 1679        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1680        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1681
 1682        cx.notify();
 1683    }
 1684
 1685    pub fn set_current_line_highlight(
 1686        &mut self,
 1687        current_line_highlight: Option<CurrentLineHighlight>,
 1688    ) {
 1689        self.current_line_highlight = current_line_highlight;
 1690    }
 1691
 1692    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1693        self.collapse_matches = collapse_matches;
 1694    }
 1695
 1696    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1697        let buffers = self.buffer.read(cx).all_buffers();
 1698        let Some(lsp_store) = self.lsp_store(cx) else {
 1699            return;
 1700        };
 1701        lsp_store.update(cx, |lsp_store, cx| {
 1702            for buffer in buffers {
 1703                self.registered_buffers
 1704                    .entry(buffer.read(cx).remote_id())
 1705                    .or_insert_with(|| {
 1706                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1707                    });
 1708            }
 1709        })
 1710    }
 1711
 1712    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1713        if self.collapse_matches {
 1714            return range.start..range.start;
 1715        }
 1716        range.clone()
 1717    }
 1718
 1719    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1720        if self.display_map.read(cx).clip_at_line_ends != clip {
 1721            self.display_map
 1722                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1723        }
 1724    }
 1725
 1726    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1727        self.input_enabled = input_enabled;
 1728    }
 1729
 1730    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1731        self.enable_inline_completions = enabled;
 1732    }
 1733
 1734    pub fn set_autoindent(&mut self, autoindent: bool) {
 1735        if autoindent {
 1736            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1737        } else {
 1738            self.autoindent_mode = None;
 1739        }
 1740    }
 1741
 1742    pub fn read_only(&self, cx: &AppContext) -> bool {
 1743        self.read_only || self.buffer.read(cx).read_only()
 1744    }
 1745
 1746    pub fn set_read_only(&mut self, read_only: bool) {
 1747        self.read_only = read_only;
 1748    }
 1749
 1750    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1751        self.use_autoclose = autoclose;
 1752    }
 1753
 1754    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1755        self.use_auto_surround = auto_surround;
 1756    }
 1757
 1758    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1759        self.auto_replace_emoji_shortcode = auto_replace;
 1760    }
 1761
 1762    pub fn toggle_inline_completions(
 1763        &mut self,
 1764        _: &ToggleInlineCompletions,
 1765        cx: &mut ViewContext<Self>,
 1766    ) {
 1767        if self.show_inline_completions_override.is_some() {
 1768            self.set_show_inline_completions(None, cx);
 1769        } else {
 1770            let cursor = self.selections.newest_anchor().head();
 1771            if let Some((buffer, cursor_buffer_position)) =
 1772                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1773            {
 1774                let show_inline_completions =
 1775                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1776                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1777            }
 1778        }
 1779    }
 1780
 1781    pub fn set_show_inline_completions(
 1782        &mut self,
 1783        show_inline_completions: Option<bool>,
 1784        cx: &mut ViewContext<Self>,
 1785    ) {
 1786        self.show_inline_completions_override = show_inline_completions;
 1787        self.refresh_inline_completion(false, true, cx);
 1788    }
 1789
 1790    pub fn inline_completions_enabled(&self, cx: &AppContext) -> bool {
 1791        let cursor = self.selections.newest_anchor().head();
 1792        if let Some((buffer, buffer_position)) =
 1793            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1794        {
 1795            self.should_show_inline_completions(&buffer, buffer_position, cx)
 1796        } else {
 1797            false
 1798        }
 1799    }
 1800
 1801    fn should_show_inline_completions(
 1802        &self,
 1803        buffer: &Model<Buffer>,
 1804        buffer_position: language::Anchor,
 1805        cx: &AppContext,
 1806    ) -> bool {
 1807        if !self.snippet_stack.is_empty() {
 1808            return false;
 1809        }
 1810
 1811        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1812            return false;
 1813        }
 1814
 1815        if let Some(provider) = self.inline_completion_provider() {
 1816            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1817                show_inline_completions
 1818            } else {
 1819                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1820            }
 1821        } else {
 1822            false
 1823        }
 1824    }
 1825
 1826    fn inline_completions_disabled_in_scope(
 1827        &self,
 1828        buffer: &Model<Buffer>,
 1829        buffer_position: language::Anchor,
 1830        cx: &AppContext,
 1831    ) -> bool {
 1832        let snapshot = buffer.read(cx).snapshot();
 1833        let settings = snapshot.settings_at(buffer_position, cx);
 1834
 1835        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1836            return false;
 1837        };
 1838
 1839        scope.override_name().map_or(false, |scope_name| {
 1840            settings
 1841                .inline_completions_disabled_in
 1842                .iter()
 1843                .any(|s| s == scope_name)
 1844        })
 1845    }
 1846
 1847    pub fn set_use_modal_editing(&mut self, to: bool) {
 1848        self.use_modal_editing = to;
 1849    }
 1850
 1851    pub fn use_modal_editing(&self) -> bool {
 1852        self.use_modal_editing
 1853    }
 1854
 1855    fn selections_did_change(
 1856        &mut self,
 1857        local: bool,
 1858        old_cursor_position: &Anchor,
 1859        show_completions: bool,
 1860        cx: &mut ViewContext<Self>,
 1861    ) {
 1862        cx.invalidate_character_coordinates();
 1863
 1864        // Copy selections to primary selection buffer
 1865        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1866        if local {
 1867            let selections = self.selections.all::<usize>(cx);
 1868            let buffer_handle = self.buffer.read(cx).read(cx);
 1869
 1870            let mut text = String::new();
 1871            for (index, selection) in selections.iter().enumerate() {
 1872                let text_for_selection = buffer_handle
 1873                    .text_for_range(selection.start..selection.end)
 1874                    .collect::<String>();
 1875
 1876                text.push_str(&text_for_selection);
 1877                if index != selections.len() - 1 {
 1878                    text.push('\n');
 1879                }
 1880            }
 1881
 1882            if !text.is_empty() {
 1883                cx.write_to_primary(ClipboardItem::new_string(text));
 1884            }
 1885        }
 1886
 1887        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1888            self.buffer.update(cx, |buffer, cx| {
 1889                buffer.set_active_selections(
 1890                    &self.selections.disjoint_anchors(),
 1891                    self.selections.line_mode,
 1892                    self.cursor_shape,
 1893                    cx,
 1894                )
 1895            });
 1896        }
 1897        let display_map = self
 1898            .display_map
 1899            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1900        let buffer = &display_map.buffer_snapshot;
 1901        self.add_selections_state = None;
 1902        self.select_next_state = None;
 1903        self.select_prev_state = None;
 1904        self.select_larger_syntax_node_stack.clear();
 1905        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1906        self.snippet_stack
 1907            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1908        self.take_rename(false, cx);
 1909
 1910        let new_cursor_position = self.selections.newest_anchor().head();
 1911
 1912        self.push_to_nav_history(
 1913            *old_cursor_position,
 1914            Some(new_cursor_position.to_point(buffer)),
 1915            cx,
 1916        );
 1917
 1918        if local {
 1919            let new_cursor_position = self.selections.newest_anchor().head();
 1920            let mut context_menu = self.context_menu.borrow_mut();
 1921            let completion_menu = match context_menu.as_ref() {
 1922                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1923                _ => {
 1924                    *context_menu = None;
 1925                    None
 1926                }
 1927            };
 1928
 1929            if let Some(completion_menu) = completion_menu {
 1930                let cursor_position = new_cursor_position.to_offset(buffer);
 1931                let (word_range, kind) =
 1932                    buffer.surrounding_word(completion_menu.initial_position, true);
 1933                if kind == Some(CharKind::Word)
 1934                    && word_range.to_inclusive().contains(&cursor_position)
 1935                {
 1936                    let mut completion_menu = completion_menu.clone();
 1937                    drop(context_menu);
 1938
 1939                    let query = Self::completion_query(buffer, cursor_position);
 1940                    cx.spawn(move |this, mut cx| async move {
 1941                        completion_menu
 1942                            .filter(query.as_deref(), cx.background_executor().clone())
 1943                            .await;
 1944
 1945                        this.update(&mut cx, |this, cx| {
 1946                            let mut context_menu = this.context_menu.borrow_mut();
 1947                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1948                            else {
 1949                                return;
 1950                            };
 1951
 1952                            if menu.id > completion_menu.id {
 1953                                return;
 1954                            }
 1955
 1956                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1957                            drop(context_menu);
 1958                            cx.notify();
 1959                        })
 1960                    })
 1961                    .detach();
 1962
 1963                    if show_completions {
 1964                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1965                    }
 1966                } else {
 1967                    drop(context_menu);
 1968                    self.hide_context_menu(cx);
 1969                }
 1970            } else {
 1971                drop(context_menu);
 1972            }
 1973
 1974            hide_hover(self, cx);
 1975
 1976            if old_cursor_position.to_display_point(&display_map).row()
 1977                != new_cursor_position.to_display_point(&display_map).row()
 1978            {
 1979                self.available_code_actions.take();
 1980            }
 1981            self.refresh_code_actions(cx);
 1982            self.refresh_document_highlights(cx);
 1983            refresh_matching_bracket_highlights(self, cx);
 1984            self.update_visible_inline_completion(cx);
 1985            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1986            if self.git_blame_inline_enabled {
 1987                self.start_inline_blame_timer(cx);
 1988            }
 1989        }
 1990
 1991        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1992        cx.emit(EditorEvent::SelectionsChanged { local });
 1993
 1994        if self.selections.disjoint_anchors().len() == 1 {
 1995            cx.emit(SearchEvent::ActiveMatchChanged)
 1996        }
 1997        cx.notify();
 1998    }
 1999
 2000    pub fn change_selections<R>(
 2001        &mut self,
 2002        autoscroll: Option<Autoscroll>,
 2003        cx: &mut ViewContext<Self>,
 2004        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2005    ) -> R {
 2006        self.change_selections_inner(autoscroll, true, cx, change)
 2007    }
 2008
 2009    pub fn change_selections_inner<R>(
 2010        &mut self,
 2011        autoscroll: Option<Autoscroll>,
 2012        request_completions: bool,
 2013        cx: &mut ViewContext<Self>,
 2014        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2015    ) -> R {
 2016        let old_cursor_position = self.selections.newest_anchor().head();
 2017        self.push_to_selection_history();
 2018
 2019        let (changed, result) = self.selections.change_with(cx, change);
 2020
 2021        if changed {
 2022            if let Some(autoscroll) = autoscroll {
 2023                self.request_autoscroll(autoscroll, cx);
 2024            }
 2025            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2026
 2027            if self.should_open_signature_help_automatically(
 2028                &old_cursor_position,
 2029                self.signature_help_state.backspace_pressed(),
 2030                cx,
 2031            ) {
 2032                self.show_signature_help(&ShowSignatureHelp, cx);
 2033            }
 2034            self.signature_help_state.set_backspace_pressed(false);
 2035        }
 2036
 2037        result
 2038    }
 2039
 2040    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2041    where
 2042        I: IntoIterator<Item = (Range<S>, T)>,
 2043        S: ToOffset,
 2044        T: Into<Arc<str>>,
 2045    {
 2046        if self.read_only(cx) {
 2047            return;
 2048        }
 2049
 2050        self.buffer
 2051            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2052    }
 2053
 2054    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2055    where
 2056        I: IntoIterator<Item = (Range<S>, T)>,
 2057        S: ToOffset,
 2058        T: Into<Arc<str>>,
 2059    {
 2060        if self.read_only(cx) {
 2061            return;
 2062        }
 2063
 2064        self.buffer.update(cx, |buffer, cx| {
 2065            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2066        });
 2067    }
 2068
 2069    pub fn edit_with_block_indent<I, S, T>(
 2070        &mut self,
 2071        edits: I,
 2072        original_indent_columns: Vec<u32>,
 2073        cx: &mut ViewContext<Self>,
 2074    ) where
 2075        I: IntoIterator<Item = (Range<S>, T)>,
 2076        S: ToOffset,
 2077        T: Into<Arc<str>>,
 2078    {
 2079        if self.read_only(cx) {
 2080            return;
 2081        }
 2082
 2083        self.buffer.update(cx, |buffer, cx| {
 2084            buffer.edit(
 2085                edits,
 2086                Some(AutoindentMode::Block {
 2087                    original_indent_columns,
 2088                }),
 2089                cx,
 2090            )
 2091        });
 2092    }
 2093
 2094    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2095        self.hide_context_menu(cx);
 2096
 2097        match phase {
 2098            SelectPhase::Begin {
 2099                position,
 2100                add,
 2101                click_count,
 2102            } => self.begin_selection(position, add, click_count, cx),
 2103            SelectPhase::BeginColumnar {
 2104                position,
 2105                goal_column,
 2106                reset,
 2107            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2108            SelectPhase::Extend {
 2109                position,
 2110                click_count,
 2111            } => self.extend_selection(position, click_count, cx),
 2112            SelectPhase::Update {
 2113                position,
 2114                goal_column,
 2115                scroll_delta,
 2116            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2117            SelectPhase::End => self.end_selection(cx),
 2118        }
 2119    }
 2120
 2121    fn extend_selection(
 2122        &mut self,
 2123        position: DisplayPoint,
 2124        click_count: usize,
 2125        cx: &mut ViewContext<Self>,
 2126    ) {
 2127        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2128        let tail = self.selections.newest::<usize>(cx).tail();
 2129        self.begin_selection(position, false, click_count, cx);
 2130
 2131        let position = position.to_offset(&display_map, Bias::Left);
 2132        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2133
 2134        let mut pending_selection = self
 2135            .selections
 2136            .pending_anchor()
 2137            .expect("extend_selection not called with pending selection");
 2138        if position >= tail {
 2139            pending_selection.start = tail_anchor;
 2140        } else {
 2141            pending_selection.end = tail_anchor;
 2142            pending_selection.reversed = true;
 2143        }
 2144
 2145        let mut pending_mode = self.selections.pending_mode().unwrap();
 2146        match &mut pending_mode {
 2147            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2148            _ => {}
 2149        }
 2150
 2151        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2152            s.set_pending(pending_selection, pending_mode)
 2153        });
 2154    }
 2155
 2156    fn begin_selection(
 2157        &mut self,
 2158        position: DisplayPoint,
 2159        add: bool,
 2160        click_count: usize,
 2161        cx: &mut ViewContext<Self>,
 2162    ) {
 2163        if !self.focus_handle.is_focused(cx) {
 2164            self.last_focused_descendant = None;
 2165            cx.focus(&self.focus_handle);
 2166        }
 2167
 2168        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2169        let buffer = &display_map.buffer_snapshot;
 2170        let newest_selection = self.selections.newest_anchor().clone();
 2171        let position = display_map.clip_point(position, Bias::Left);
 2172
 2173        let start;
 2174        let end;
 2175        let mode;
 2176        let mut auto_scroll;
 2177        match click_count {
 2178            1 => {
 2179                start = buffer.anchor_before(position.to_point(&display_map));
 2180                end = start;
 2181                mode = SelectMode::Character;
 2182                auto_scroll = true;
 2183            }
 2184            2 => {
 2185                let range = movement::surrounding_word(&display_map, position);
 2186                start = buffer.anchor_before(range.start.to_point(&display_map));
 2187                end = buffer.anchor_before(range.end.to_point(&display_map));
 2188                mode = SelectMode::Word(start..end);
 2189                auto_scroll = true;
 2190            }
 2191            3 => {
 2192                let position = display_map
 2193                    .clip_point(position, Bias::Left)
 2194                    .to_point(&display_map);
 2195                let line_start = display_map.prev_line_boundary(position).0;
 2196                let next_line_start = buffer.clip_point(
 2197                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2198                    Bias::Left,
 2199                );
 2200                start = buffer.anchor_before(line_start);
 2201                end = buffer.anchor_before(next_line_start);
 2202                mode = SelectMode::Line(start..end);
 2203                auto_scroll = true;
 2204            }
 2205            _ => {
 2206                start = buffer.anchor_before(0);
 2207                end = buffer.anchor_before(buffer.len());
 2208                mode = SelectMode::All;
 2209                auto_scroll = false;
 2210            }
 2211        }
 2212        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2213
 2214        let point_to_delete: Option<usize> = {
 2215            let selected_points: Vec<Selection<Point>> =
 2216                self.selections.disjoint_in_range(start..end, cx);
 2217
 2218            if !add || click_count > 1 {
 2219                None
 2220            } else if !selected_points.is_empty() {
 2221                Some(selected_points[0].id)
 2222            } else {
 2223                let clicked_point_already_selected =
 2224                    self.selections.disjoint.iter().find(|selection| {
 2225                        selection.start.to_point(buffer) == start.to_point(buffer)
 2226                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2227                    });
 2228
 2229                clicked_point_already_selected.map(|selection| selection.id)
 2230            }
 2231        };
 2232
 2233        let selections_count = self.selections.count();
 2234
 2235        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2236            if let Some(point_to_delete) = point_to_delete {
 2237                s.delete(point_to_delete);
 2238
 2239                if selections_count == 1 {
 2240                    s.set_pending_anchor_range(start..end, mode);
 2241                }
 2242            } else {
 2243                if !add {
 2244                    s.clear_disjoint();
 2245                } else if click_count > 1 {
 2246                    s.delete(newest_selection.id)
 2247                }
 2248
 2249                s.set_pending_anchor_range(start..end, mode);
 2250            }
 2251        });
 2252    }
 2253
 2254    fn begin_columnar_selection(
 2255        &mut self,
 2256        position: DisplayPoint,
 2257        goal_column: u32,
 2258        reset: bool,
 2259        cx: &mut ViewContext<Self>,
 2260    ) {
 2261        if !self.focus_handle.is_focused(cx) {
 2262            self.last_focused_descendant = None;
 2263            cx.focus(&self.focus_handle);
 2264        }
 2265
 2266        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2267
 2268        if reset {
 2269            let pointer_position = display_map
 2270                .buffer_snapshot
 2271                .anchor_before(position.to_point(&display_map));
 2272
 2273            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2274                s.clear_disjoint();
 2275                s.set_pending_anchor_range(
 2276                    pointer_position..pointer_position,
 2277                    SelectMode::Character,
 2278                );
 2279            });
 2280        }
 2281
 2282        let tail = self.selections.newest::<Point>(cx).tail();
 2283        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2284
 2285        if !reset {
 2286            self.select_columns(
 2287                tail.to_display_point(&display_map),
 2288                position,
 2289                goal_column,
 2290                &display_map,
 2291                cx,
 2292            );
 2293        }
 2294    }
 2295
 2296    fn update_selection(
 2297        &mut self,
 2298        position: DisplayPoint,
 2299        goal_column: u32,
 2300        scroll_delta: gpui::Point<f32>,
 2301        cx: &mut ViewContext<Self>,
 2302    ) {
 2303        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2304
 2305        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2306            let tail = tail.to_display_point(&display_map);
 2307            self.select_columns(tail, position, goal_column, &display_map, cx);
 2308        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2309            let buffer = self.buffer.read(cx).snapshot(cx);
 2310            let head;
 2311            let tail;
 2312            let mode = self.selections.pending_mode().unwrap();
 2313            match &mode {
 2314                SelectMode::Character => {
 2315                    head = position.to_point(&display_map);
 2316                    tail = pending.tail().to_point(&buffer);
 2317                }
 2318                SelectMode::Word(original_range) => {
 2319                    let original_display_range = original_range.start.to_display_point(&display_map)
 2320                        ..original_range.end.to_display_point(&display_map);
 2321                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2322                        ..original_display_range.end.to_point(&display_map);
 2323                    if movement::is_inside_word(&display_map, position)
 2324                        || original_display_range.contains(&position)
 2325                    {
 2326                        let word_range = movement::surrounding_word(&display_map, position);
 2327                        if word_range.start < original_display_range.start {
 2328                            head = word_range.start.to_point(&display_map);
 2329                        } else {
 2330                            head = word_range.end.to_point(&display_map);
 2331                        }
 2332                    } else {
 2333                        head = position.to_point(&display_map);
 2334                    }
 2335
 2336                    if head <= original_buffer_range.start {
 2337                        tail = original_buffer_range.end;
 2338                    } else {
 2339                        tail = original_buffer_range.start;
 2340                    }
 2341                }
 2342                SelectMode::Line(original_range) => {
 2343                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2344
 2345                    let position = display_map
 2346                        .clip_point(position, Bias::Left)
 2347                        .to_point(&display_map);
 2348                    let line_start = display_map.prev_line_boundary(position).0;
 2349                    let next_line_start = buffer.clip_point(
 2350                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2351                        Bias::Left,
 2352                    );
 2353
 2354                    if line_start < original_range.start {
 2355                        head = line_start
 2356                    } else {
 2357                        head = next_line_start
 2358                    }
 2359
 2360                    if head <= original_range.start {
 2361                        tail = original_range.end;
 2362                    } else {
 2363                        tail = original_range.start;
 2364                    }
 2365                }
 2366                SelectMode::All => {
 2367                    return;
 2368                }
 2369            };
 2370
 2371            if head < tail {
 2372                pending.start = buffer.anchor_before(head);
 2373                pending.end = buffer.anchor_before(tail);
 2374                pending.reversed = true;
 2375            } else {
 2376                pending.start = buffer.anchor_before(tail);
 2377                pending.end = buffer.anchor_before(head);
 2378                pending.reversed = false;
 2379            }
 2380
 2381            self.change_selections(None, cx, |s| {
 2382                s.set_pending(pending, mode);
 2383            });
 2384        } else {
 2385            log::error!("update_selection dispatched with no pending selection");
 2386            return;
 2387        }
 2388
 2389        self.apply_scroll_delta(scroll_delta, cx);
 2390        cx.notify();
 2391    }
 2392
 2393    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2394        self.columnar_selection_tail.take();
 2395        if self.selections.pending_anchor().is_some() {
 2396            let selections = self.selections.all::<usize>(cx);
 2397            self.change_selections(None, cx, |s| {
 2398                s.select(selections);
 2399                s.clear_pending();
 2400            });
 2401        }
 2402    }
 2403
 2404    fn select_columns(
 2405        &mut self,
 2406        tail: DisplayPoint,
 2407        head: DisplayPoint,
 2408        goal_column: u32,
 2409        display_map: &DisplaySnapshot,
 2410        cx: &mut ViewContext<Self>,
 2411    ) {
 2412        let start_row = cmp::min(tail.row(), head.row());
 2413        let end_row = cmp::max(tail.row(), head.row());
 2414        let start_column = cmp::min(tail.column(), goal_column);
 2415        let end_column = cmp::max(tail.column(), goal_column);
 2416        let reversed = start_column < tail.column();
 2417
 2418        let selection_ranges = (start_row.0..=end_row.0)
 2419            .map(DisplayRow)
 2420            .filter_map(|row| {
 2421                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2422                    let start = display_map
 2423                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2424                        .to_point(display_map);
 2425                    let end = display_map
 2426                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2427                        .to_point(display_map);
 2428                    if reversed {
 2429                        Some(end..start)
 2430                    } else {
 2431                        Some(start..end)
 2432                    }
 2433                } else {
 2434                    None
 2435                }
 2436            })
 2437            .collect::<Vec<_>>();
 2438
 2439        self.change_selections(None, cx, |s| {
 2440            s.select_ranges(selection_ranges);
 2441        });
 2442        cx.notify();
 2443    }
 2444
 2445    pub fn has_pending_nonempty_selection(&self) -> bool {
 2446        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2447            Some(Selection { start, end, .. }) => start != end,
 2448            None => false,
 2449        };
 2450
 2451        pending_nonempty_selection
 2452            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2453    }
 2454
 2455    pub fn has_pending_selection(&self) -> bool {
 2456        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2457    }
 2458
 2459    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2460        if self.clear_expanded_diff_hunks(cx) {
 2461            cx.notify();
 2462            return;
 2463        }
 2464        if self.dismiss_menus_and_popups(true, cx) {
 2465            return;
 2466        }
 2467
 2468        if self.mode == EditorMode::Full
 2469            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2470        {
 2471            return;
 2472        }
 2473
 2474        cx.propagate();
 2475    }
 2476
 2477    pub fn dismiss_menus_and_popups(
 2478        &mut self,
 2479        should_report_inline_completion_event: bool,
 2480        cx: &mut ViewContext<Self>,
 2481    ) -> bool {
 2482        if self.take_rename(false, cx).is_some() {
 2483            return true;
 2484        }
 2485
 2486        if hide_hover(self, cx) {
 2487            return true;
 2488        }
 2489
 2490        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2491            return true;
 2492        }
 2493
 2494        if self.hide_context_menu(cx).is_some() {
 2495            if self.show_inline_completions_in_menu(cx) && self.has_active_inline_completion() {
 2496                self.update_visible_inline_completion(cx);
 2497            }
 2498            return true;
 2499        }
 2500
 2501        if self.mouse_context_menu.take().is_some() {
 2502            return true;
 2503        }
 2504
 2505        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2506            return true;
 2507        }
 2508
 2509        if self.snippet_stack.pop().is_some() {
 2510            return true;
 2511        }
 2512
 2513        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2514            self.dismiss_diagnostics(cx);
 2515            return true;
 2516        }
 2517
 2518        false
 2519    }
 2520
 2521    fn linked_editing_ranges_for(
 2522        &self,
 2523        selection: Range<text::Anchor>,
 2524        cx: &AppContext,
 2525    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2526        if self.linked_edit_ranges.is_empty() {
 2527            return None;
 2528        }
 2529        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2530            selection.end.buffer_id.and_then(|end_buffer_id| {
 2531                if selection.start.buffer_id != Some(end_buffer_id) {
 2532                    return None;
 2533                }
 2534                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2535                let snapshot = buffer.read(cx).snapshot();
 2536                self.linked_edit_ranges
 2537                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2538                    .map(|ranges| (ranges, snapshot, buffer))
 2539            })?;
 2540        use text::ToOffset as TO;
 2541        // find offset from the start of current range to current cursor position
 2542        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2543
 2544        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2545        let start_difference = start_offset - start_byte_offset;
 2546        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2547        let end_difference = end_offset - start_byte_offset;
 2548        // Current range has associated linked ranges.
 2549        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2550        for range in linked_ranges.iter() {
 2551            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2552            let end_offset = start_offset + end_difference;
 2553            let start_offset = start_offset + start_difference;
 2554            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2555                continue;
 2556            }
 2557            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2558                if s.start.buffer_id != selection.start.buffer_id
 2559                    || s.end.buffer_id != selection.end.buffer_id
 2560                {
 2561                    return false;
 2562                }
 2563                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2564                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2565            }) {
 2566                continue;
 2567            }
 2568            let start = buffer_snapshot.anchor_after(start_offset);
 2569            let end = buffer_snapshot.anchor_after(end_offset);
 2570            linked_edits
 2571                .entry(buffer.clone())
 2572                .or_default()
 2573                .push(start..end);
 2574        }
 2575        Some(linked_edits)
 2576    }
 2577
 2578    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2579        let text: Arc<str> = text.into();
 2580
 2581        if self.read_only(cx) {
 2582            return;
 2583        }
 2584
 2585        let selections = self.selections.all_adjusted(cx);
 2586        let mut bracket_inserted = false;
 2587        let mut edits = Vec::new();
 2588        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2589        let mut new_selections = Vec::with_capacity(selections.len());
 2590        let mut new_autoclose_regions = Vec::new();
 2591        let snapshot = self.buffer.read(cx).read(cx);
 2592
 2593        for (selection, autoclose_region) in
 2594            self.selections_with_autoclose_regions(selections, &snapshot)
 2595        {
 2596            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2597                // Determine if the inserted text matches the opening or closing
 2598                // bracket of any of this language's bracket pairs.
 2599                let mut bracket_pair = None;
 2600                let mut is_bracket_pair_start = false;
 2601                let mut is_bracket_pair_end = false;
 2602                if !text.is_empty() {
 2603                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2604                    //  and they are removing the character that triggered IME popup.
 2605                    for (pair, enabled) in scope.brackets() {
 2606                        if !pair.close && !pair.surround {
 2607                            continue;
 2608                        }
 2609
 2610                        if enabled && pair.start.ends_with(text.as_ref()) {
 2611                            let prefix_len = pair.start.len() - text.len();
 2612                            let preceding_text_matches_prefix = prefix_len == 0
 2613                                || (selection.start.column >= (prefix_len as u32)
 2614                                    && snapshot.contains_str_at(
 2615                                        Point::new(
 2616                                            selection.start.row,
 2617                                            selection.start.column - (prefix_len as u32),
 2618                                        ),
 2619                                        &pair.start[..prefix_len],
 2620                                    ));
 2621                            if preceding_text_matches_prefix {
 2622                                bracket_pair = Some(pair.clone());
 2623                                is_bracket_pair_start = true;
 2624                                break;
 2625                            }
 2626                        }
 2627                        if pair.end.as_str() == text.as_ref() {
 2628                            bracket_pair = Some(pair.clone());
 2629                            is_bracket_pair_end = true;
 2630                            break;
 2631                        }
 2632                    }
 2633                }
 2634
 2635                if let Some(bracket_pair) = bracket_pair {
 2636                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2637                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2638                    let auto_surround =
 2639                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2640                    if selection.is_empty() {
 2641                        if is_bracket_pair_start {
 2642                            // If the inserted text is a suffix of an opening bracket and the
 2643                            // selection is preceded by the rest of the opening bracket, then
 2644                            // insert the closing bracket.
 2645                            let following_text_allows_autoclose = snapshot
 2646                                .chars_at(selection.start)
 2647                                .next()
 2648                                .map_or(true, |c| scope.should_autoclose_before(c));
 2649
 2650                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2651                                && bracket_pair.start.len() == 1
 2652                            {
 2653                                let target = bracket_pair.start.chars().next().unwrap();
 2654                                let current_line_count = snapshot
 2655                                    .reversed_chars_at(selection.start)
 2656                                    .take_while(|&c| c != '\n')
 2657                                    .filter(|&c| c == target)
 2658                                    .count();
 2659                                current_line_count % 2 == 1
 2660                            } else {
 2661                                false
 2662                            };
 2663
 2664                            if autoclose
 2665                                && bracket_pair.close
 2666                                && following_text_allows_autoclose
 2667                                && !is_closing_quote
 2668                            {
 2669                                let anchor = snapshot.anchor_before(selection.end);
 2670                                new_selections.push((selection.map(|_| anchor), text.len()));
 2671                                new_autoclose_regions.push((
 2672                                    anchor,
 2673                                    text.len(),
 2674                                    selection.id,
 2675                                    bracket_pair.clone(),
 2676                                ));
 2677                                edits.push((
 2678                                    selection.range(),
 2679                                    format!("{}{}", text, bracket_pair.end).into(),
 2680                                ));
 2681                                bracket_inserted = true;
 2682                                continue;
 2683                            }
 2684                        }
 2685
 2686                        if let Some(region) = autoclose_region {
 2687                            // If the selection is followed by an auto-inserted closing bracket,
 2688                            // then don't insert that closing bracket again; just move the selection
 2689                            // past the closing bracket.
 2690                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2691                                && text.as_ref() == region.pair.end.as_str();
 2692                            if should_skip {
 2693                                let anchor = snapshot.anchor_after(selection.end);
 2694                                new_selections
 2695                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2696                                continue;
 2697                            }
 2698                        }
 2699
 2700                        let always_treat_brackets_as_autoclosed = snapshot
 2701                            .settings_at(selection.start, cx)
 2702                            .always_treat_brackets_as_autoclosed;
 2703                        if always_treat_brackets_as_autoclosed
 2704                            && is_bracket_pair_end
 2705                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2706                        {
 2707                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2708                            // and the inserted text is a closing bracket and the selection is followed
 2709                            // by the closing bracket then move the selection past the closing bracket.
 2710                            let anchor = snapshot.anchor_after(selection.end);
 2711                            new_selections.push((selection.map(|_| anchor), text.len()));
 2712                            continue;
 2713                        }
 2714                    }
 2715                    // If an opening bracket is 1 character long and is typed while
 2716                    // text is selected, then surround that text with the bracket pair.
 2717                    else if auto_surround
 2718                        && bracket_pair.surround
 2719                        && is_bracket_pair_start
 2720                        && bracket_pair.start.chars().count() == 1
 2721                    {
 2722                        edits.push((selection.start..selection.start, text.clone()));
 2723                        edits.push((
 2724                            selection.end..selection.end,
 2725                            bracket_pair.end.as_str().into(),
 2726                        ));
 2727                        bracket_inserted = true;
 2728                        new_selections.push((
 2729                            Selection {
 2730                                id: selection.id,
 2731                                start: snapshot.anchor_after(selection.start),
 2732                                end: snapshot.anchor_before(selection.end),
 2733                                reversed: selection.reversed,
 2734                                goal: selection.goal,
 2735                            },
 2736                            0,
 2737                        ));
 2738                        continue;
 2739                    }
 2740                }
 2741            }
 2742
 2743            if self.auto_replace_emoji_shortcode
 2744                && selection.is_empty()
 2745                && text.as_ref().ends_with(':')
 2746            {
 2747                if let Some(possible_emoji_short_code) =
 2748                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2749                {
 2750                    if !possible_emoji_short_code.is_empty() {
 2751                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2752                            let emoji_shortcode_start = Point::new(
 2753                                selection.start.row,
 2754                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2755                            );
 2756
 2757                            // Remove shortcode from buffer
 2758                            edits.push((
 2759                                emoji_shortcode_start..selection.start,
 2760                                "".to_string().into(),
 2761                            ));
 2762                            new_selections.push((
 2763                                Selection {
 2764                                    id: selection.id,
 2765                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2766                                    end: snapshot.anchor_before(selection.start),
 2767                                    reversed: selection.reversed,
 2768                                    goal: selection.goal,
 2769                                },
 2770                                0,
 2771                            ));
 2772
 2773                            // Insert emoji
 2774                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2775                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2776                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2777
 2778                            continue;
 2779                        }
 2780                    }
 2781                }
 2782            }
 2783
 2784            // If not handling any auto-close operation, then just replace the selected
 2785            // text with the given input and move the selection to the end of the
 2786            // newly inserted text.
 2787            let anchor = snapshot.anchor_after(selection.end);
 2788            if !self.linked_edit_ranges.is_empty() {
 2789                let start_anchor = snapshot.anchor_before(selection.start);
 2790
 2791                let is_word_char = text.chars().next().map_or(true, |char| {
 2792                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2793                    classifier.is_word(char)
 2794                });
 2795
 2796                if is_word_char {
 2797                    if let Some(ranges) = self
 2798                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2799                    {
 2800                        for (buffer, edits) in ranges {
 2801                            linked_edits
 2802                                .entry(buffer.clone())
 2803                                .or_default()
 2804                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2805                        }
 2806                    }
 2807                }
 2808            }
 2809
 2810            new_selections.push((selection.map(|_| anchor), 0));
 2811            edits.push((selection.start..selection.end, text.clone()));
 2812        }
 2813
 2814        drop(snapshot);
 2815
 2816        self.transact(cx, |this, cx| {
 2817            this.buffer.update(cx, |buffer, cx| {
 2818                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2819            });
 2820            for (buffer, edits) in linked_edits {
 2821                buffer.update(cx, |buffer, cx| {
 2822                    let snapshot = buffer.snapshot();
 2823                    let edits = edits
 2824                        .into_iter()
 2825                        .map(|(range, text)| {
 2826                            use text::ToPoint as TP;
 2827                            let end_point = TP::to_point(&range.end, &snapshot);
 2828                            let start_point = TP::to_point(&range.start, &snapshot);
 2829                            (start_point..end_point, text)
 2830                        })
 2831                        .sorted_by_key(|(range, _)| range.start)
 2832                        .collect::<Vec<_>>();
 2833                    buffer.edit(edits, None, cx);
 2834                })
 2835            }
 2836            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2837            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2838            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2839            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2840                .zip(new_selection_deltas)
 2841                .map(|(selection, delta)| Selection {
 2842                    id: selection.id,
 2843                    start: selection.start + delta,
 2844                    end: selection.end + delta,
 2845                    reversed: selection.reversed,
 2846                    goal: SelectionGoal::None,
 2847                })
 2848                .collect::<Vec<_>>();
 2849
 2850            let mut i = 0;
 2851            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2852                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2853                let start = map.buffer_snapshot.anchor_before(position);
 2854                let end = map.buffer_snapshot.anchor_after(position);
 2855                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2856                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2857                        Ordering::Less => i += 1,
 2858                        Ordering::Greater => break,
 2859                        Ordering::Equal => {
 2860                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2861                                Ordering::Less => i += 1,
 2862                                Ordering::Equal => break,
 2863                                Ordering::Greater => break,
 2864                            }
 2865                        }
 2866                    }
 2867                }
 2868                this.autoclose_regions.insert(
 2869                    i,
 2870                    AutocloseRegion {
 2871                        selection_id,
 2872                        range: start..end,
 2873                        pair,
 2874                    },
 2875                );
 2876            }
 2877
 2878            let had_active_inline_completion = this.has_active_inline_completion();
 2879            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2880                s.select(new_selections)
 2881            });
 2882
 2883            if !bracket_inserted {
 2884                if let Some(on_type_format_task) =
 2885                    this.trigger_on_type_formatting(text.to_string(), cx)
 2886                {
 2887                    on_type_format_task.detach_and_log_err(cx);
 2888                }
 2889            }
 2890
 2891            let editor_settings = EditorSettings::get_global(cx);
 2892            if bracket_inserted
 2893                && (editor_settings.auto_signature_help
 2894                    || editor_settings.show_signature_help_after_edits)
 2895            {
 2896                this.show_signature_help(&ShowSignatureHelp, cx);
 2897            }
 2898
 2899            let trigger_in_words =
 2900                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2901            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 2902            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2903            this.refresh_inline_completion(true, false, cx);
 2904        });
 2905    }
 2906
 2907    fn find_possible_emoji_shortcode_at_position(
 2908        snapshot: &MultiBufferSnapshot,
 2909        position: Point,
 2910    ) -> Option<String> {
 2911        let mut chars = Vec::new();
 2912        let mut found_colon = false;
 2913        for char in snapshot.reversed_chars_at(position).take(100) {
 2914            // Found a possible emoji shortcode in the middle of the buffer
 2915            if found_colon {
 2916                if char.is_whitespace() {
 2917                    chars.reverse();
 2918                    return Some(chars.iter().collect());
 2919                }
 2920                // If the previous character is not a whitespace, we are in the middle of a word
 2921                // and we only want to complete the shortcode if the word is made up of other emojis
 2922                let mut containing_word = String::new();
 2923                for ch in snapshot
 2924                    .reversed_chars_at(position)
 2925                    .skip(chars.len() + 1)
 2926                    .take(100)
 2927                {
 2928                    if ch.is_whitespace() {
 2929                        break;
 2930                    }
 2931                    containing_word.push(ch);
 2932                }
 2933                let containing_word = containing_word.chars().rev().collect::<String>();
 2934                if util::word_consists_of_emojis(containing_word.as_str()) {
 2935                    chars.reverse();
 2936                    return Some(chars.iter().collect());
 2937                }
 2938            }
 2939
 2940            if char.is_whitespace() || !char.is_ascii() {
 2941                return None;
 2942            }
 2943            if char == ':' {
 2944                found_colon = true;
 2945            } else {
 2946                chars.push(char);
 2947            }
 2948        }
 2949        // Found a possible emoji shortcode at the beginning of the buffer
 2950        chars.reverse();
 2951        Some(chars.iter().collect())
 2952    }
 2953
 2954    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2955        self.transact(cx, |this, cx| {
 2956            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2957                let selections = this.selections.all::<usize>(cx);
 2958                let multi_buffer = this.buffer.read(cx);
 2959                let buffer = multi_buffer.snapshot(cx);
 2960                selections
 2961                    .iter()
 2962                    .map(|selection| {
 2963                        let start_point = selection.start.to_point(&buffer);
 2964                        let mut indent =
 2965                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2966                        indent.len = cmp::min(indent.len, start_point.column);
 2967                        let start = selection.start;
 2968                        let end = selection.end;
 2969                        let selection_is_empty = start == end;
 2970                        let language_scope = buffer.language_scope_at(start);
 2971                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2972                            &language_scope
 2973                        {
 2974                            let leading_whitespace_len = buffer
 2975                                .reversed_chars_at(start)
 2976                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2977                                .map(|c| c.len_utf8())
 2978                                .sum::<usize>();
 2979
 2980                            let trailing_whitespace_len = buffer
 2981                                .chars_at(end)
 2982                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2983                                .map(|c| c.len_utf8())
 2984                                .sum::<usize>();
 2985
 2986                            let insert_extra_newline =
 2987                                language.brackets().any(|(pair, enabled)| {
 2988                                    let pair_start = pair.start.trim_end();
 2989                                    let pair_end = pair.end.trim_start();
 2990
 2991                                    enabled
 2992                                        && pair.newline
 2993                                        && buffer.contains_str_at(
 2994                                            end + trailing_whitespace_len,
 2995                                            pair_end,
 2996                                        )
 2997                                        && buffer.contains_str_at(
 2998                                            (start - leading_whitespace_len)
 2999                                                .saturating_sub(pair_start.len()),
 3000                                            pair_start,
 3001                                        )
 3002                                });
 3003
 3004                            // Comment extension on newline is allowed only for cursor selections
 3005                            let comment_delimiter = maybe!({
 3006                                if !selection_is_empty {
 3007                                    return None;
 3008                                }
 3009
 3010                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3011                                    return None;
 3012                                }
 3013
 3014                                let delimiters = language.line_comment_prefixes();
 3015                                let max_len_of_delimiter =
 3016                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3017                                let (snapshot, range) =
 3018                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3019
 3020                                let mut index_of_first_non_whitespace = 0;
 3021                                let comment_candidate = snapshot
 3022                                    .chars_for_range(range)
 3023                                    .skip_while(|c| {
 3024                                        let should_skip = c.is_whitespace();
 3025                                        if should_skip {
 3026                                            index_of_first_non_whitespace += 1;
 3027                                        }
 3028                                        should_skip
 3029                                    })
 3030                                    .take(max_len_of_delimiter)
 3031                                    .collect::<String>();
 3032                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3033                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3034                                })?;
 3035                                let cursor_is_placed_after_comment_marker =
 3036                                    index_of_first_non_whitespace + comment_prefix.len()
 3037                                        <= start_point.column as usize;
 3038                                if cursor_is_placed_after_comment_marker {
 3039                                    Some(comment_prefix.clone())
 3040                                } else {
 3041                                    None
 3042                                }
 3043                            });
 3044                            (comment_delimiter, insert_extra_newline)
 3045                        } else {
 3046                            (None, false)
 3047                        };
 3048
 3049                        let capacity_for_delimiter = comment_delimiter
 3050                            .as_deref()
 3051                            .map(str::len)
 3052                            .unwrap_or_default();
 3053                        let mut new_text =
 3054                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3055                        new_text.push('\n');
 3056                        new_text.extend(indent.chars());
 3057                        if let Some(delimiter) = &comment_delimiter {
 3058                            new_text.push_str(delimiter);
 3059                        }
 3060                        if insert_extra_newline {
 3061                            new_text = new_text.repeat(2);
 3062                        }
 3063
 3064                        let anchor = buffer.anchor_after(end);
 3065                        let new_selection = selection.map(|_| anchor);
 3066                        (
 3067                            (start..end, new_text),
 3068                            (insert_extra_newline, new_selection),
 3069                        )
 3070                    })
 3071                    .unzip()
 3072            };
 3073
 3074            this.edit_with_autoindent(edits, cx);
 3075            let buffer = this.buffer.read(cx).snapshot(cx);
 3076            let new_selections = selection_fixup_info
 3077                .into_iter()
 3078                .map(|(extra_newline_inserted, new_selection)| {
 3079                    let mut cursor = new_selection.end.to_point(&buffer);
 3080                    if extra_newline_inserted {
 3081                        cursor.row -= 1;
 3082                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3083                    }
 3084                    new_selection.map(|_| cursor)
 3085                })
 3086                .collect();
 3087
 3088            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3089            this.refresh_inline_completion(true, false, cx);
 3090        });
 3091    }
 3092
 3093    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3094        let buffer = self.buffer.read(cx);
 3095        let snapshot = buffer.snapshot(cx);
 3096
 3097        let mut edits = Vec::new();
 3098        let mut rows = Vec::new();
 3099
 3100        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3101            let cursor = selection.head();
 3102            let row = cursor.row;
 3103
 3104            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3105
 3106            let newline = "\n".to_string();
 3107            edits.push((start_of_line..start_of_line, newline));
 3108
 3109            rows.push(row + rows_inserted as u32);
 3110        }
 3111
 3112        self.transact(cx, |editor, cx| {
 3113            editor.edit(edits, cx);
 3114
 3115            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3116                let mut index = 0;
 3117                s.move_cursors_with(|map, _, _| {
 3118                    let row = rows[index];
 3119                    index += 1;
 3120
 3121                    let point = Point::new(row, 0);
 3122                    let boundary = map.next_line_boundary(point).1;
 3123                    let clipped = map.clip_point(boundary, Bias::Left);
 3124
 3125                    (clipped, SelectionGoal::None)
 3126                });
 3127            });
 3128
 3129            let mut indent_edits = Vec::new();
 3130            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3131            for row in rows {
 3132                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3133                for (row, indent) in indents {
 3134                    if indent.len == 0 {
 3135                        continue;
 3136                    }
 3137
 3138                    let text = match indent.kind {
 3139                        IndentKind::Space => " ".repeat(indent.len as usize),
 3140                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3141                    };
 3142                    let point = Point::new(row.0, 0);
 3143                    indent_edits.push((point..point, text));
 3144                }
 3145            }
 3146            editor.edit(indent_edits, cx);
 3147        });
 3148    }
 3149
 3150    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3151        let buffer = self.buffer.read(cx);
 3152        let snapshot = buffer.snapshot(cx);
 3153
 3154        let mut edits = Vec::new();
 3155        let mut rows = Vec::new();
 3156        let mut rows_inserted = 0;
 3157
 3158        for selection in self.selections.all_adjusted(cx) {
 3159            let cursor = selection.head();
 3160            let row = cursor.row;
 3161
 3162            let point = Point::new(row + 1, 0);
 3163            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3164
 3165            let newline = "\n".to_string();
 3166            edits.push((start_of_line..start_of_line, newline));
 3167
 3168            rows_inserted += 1;
 3169            rows.push(row + rows_inserted);
 3170        }
 3171
 3172        self.transact(cx, |editor, cx| {
 3173            editor.edit(edits, cx);
 3174
 3175            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3176                let mut index = 0;
 3177                s.move_cursors_with(|map, _, _| {
 3178                    let row = rows[index];
 3179                    index += 1;
 3180
 3181                    let point = Point::new(row, 0);
 3182                    let boundary = map.next_line_boundary(point).1;
 3183                    let clipped = map.clip_point(boundary, Bias::Left);
 3184
 3185                    (clipped, SelectionGoal::None)
 3186                });
 3187            });
 3188
 3189            let mut indent_edits = Vec::new();
 3190            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3191            for row in rows {
 3192                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3193                for (row, indent) in indents {
 3194                    if indent.len == 0 {
 3195                        continue;
 3196                    }
 3197
 3198                    let text = match indent.kind {
 3199                        IndentKind::Space => " ".repeat(indent.len as usize),
 3200                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3201                    };
 3202                    let point = Point::new(row.0, 0);
 3203                    indent_edits.push((point..point, text));
 3204                }
 3205            }
 3206            editor.edit(indent_edits, cx);
 3207        });
 3208    }
 3209
 3210    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3211        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3212            original_indent_columns: Vec::new(),
 3213        });
 3214        self.insert_with_autoindent_mode(text, autoindent, cx);
 3215    }
 3216
 3217    fn insert_with_autoindent_mode(
 3218        &mut self,
 3219        text: &str,
 3220        autoindent_mode: Option<AutoindentMode>,
 3221        cx: &mut ViewContext<Self>,
 3222    ) {
 3223        if self.read_only(cx) {
 3224            return;
 3225        }
 3226
 3227        let text: Arc<str> = text.into();
 3228        self.transact(cx, |this, cx| {
 3229            let old_selections = this.selections.all_adjusted(cx);
 3230            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3231                let anchors = {
 3232                    let snapshot = buffer.read(cx);
 3233                    old_selections
 3234                        .iter()
 3235                        .map(|s| {
 3236                            let anchor = snapshot.anchor_after(s.head());
 3237                            s.map(|_| anchor)
 3238                        })
 3239                        .collect::<Vec<_>>()
 3240                };
 3241                buffer.edit(
 3242                    old_selections
 3243                        .iter()
 3244                        .map(|s| (s.start..s.end, text.clone())),
 3245                    autoindent_mode,
 3246                    cx,
 3247                );
 3248                anchors
 3249            });
 3250
 3251            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3252                s.select_anchors(selection_anchors);
 3253            })
 3254        });
 3255    }
 3256
 3257    fn trigger_completion_on_input(
 3258        &mut self,
 3259        text: &str,
 3260        trigger_in_words: bool,
 3261        cx: &mut ViewContext<Self>,
 3262    ) {
 3263        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3264            self.show_completions(
 3265                &ShowCompletions {
 3266                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3267                },
 3268                cx,
 3269            );
 3270        } else {
 3271            self.hide_context_menu(cx);
 3272        }
 3273    }
 3274
 3275    fn is_completion_trigger(
 3276        &self,
 3277        text: &str,
 3278        trigger_in_words: bool,
 3279        cx: &mut ViewContext<Self>,
 3280    ) -> bool {
 3281        let position = self.selections.newest_anchor().head();
 3282        let multibuffer = self.buffer.read(cx);
 3283        let Some(buffer) = position
 3284            .buffer_id
 3285            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3286        else {
 3287            return false;
 3288        };
 3289
 3290        if let Some(completion_provider) = &self.completion_provider {
 3291            completion_provider.is_completion_trigger(
 3292                &buffer,
 3293                position.text_anchor,
 3294                text,
 3295                trigger_in_words,
 3296                cx,
 3297            )
 3298        } else {
 3299            false
 3300        }
 3301    }
 3302
 3303    /// If any empty selections is touching the start of its innermost containing autoclose
 3304    /// region, expand it to select the brackets.
 3305    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3306        let selections = self.selections.all::<usize>(cx);
 3307        let buffer = self.buffer.read(cx).read(cx);
 3308        let new_selections = self
 3309            .selections_with_autoclose_regions(selections, &buffer)
 3310            .map(|(mut selection, region)| {
 3311                if !selection.is_empty() {
 3312                    return selection;
 3313                }
 3314
 3315                if let Some(region) = region {
 3316                    let mut range = region.range.to_offset(&buffer);
 3317                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3318                        range.start -= region.pair.start.len();
 3319                        if buffer.contains_str_at(range.start, &region.pair.start)
 3320                            && buffer.contains_str_at(range.end, &region.pair.end)
 3321                        {
 3322                            range.end += region.pair.end.len();
 3323                            selection.start = range.start;
 3324                            selection.end = range.end;
 3325
 3326                            return selection;
 3327                        }
 3328                    }
 3329                }
 3330
 3331                let always_treat_brackets_as_autoclosed = buffer
 3332                    .settings_at(selection.start, cx)
 3333                    .always_treat_brackets_as_autoclosed;
 3334
 3335                if !always_treat_brackets_as_autoclosed {
 3336                    return selection;
 3337                }
 3338
 3339                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3340                    for (pair, enabled) in scope.brackets() {
 3341                        if !enabled || !pair.close {
 3342                            continue;
 3343                        }
 3344
 3345                        if buffer.contains_str_at(selection.start, &pair.end) {
 3346                            let pair_start_len = pair.start.len();
 3347                            if buffer.contains_str_at(
 3348                                selection.start.saturating_sub(pair_start_len),
 3349                                &pair.start,
 3350                            ) {
 3351                                selection.start -= pair_start_len;
 3352                                selection.end += pair.end.len();
 3353
 3354                                return selection;
 3355                            }
 3356                        }
 3357                    }
 3358                }
 3359
 3360                selection
 3361            })
 3362            .collect();
 3363
 3364        drop(buffer);
 3365        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3366    }
 3367
 3368    /// Iterate the given selections, and for each one, find the smallest surrounding
 3369    /// autoclose region. This uses the ordering of the selections and the autoclose
 3370    /// regions to avoid repeated comparisons.
 3371    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3372        &'a self,
 3373        selections: impl IntoIterator<Item = Selection<D>>,
 3374        buffer: &'a MultiBufferSnapshot,
 3375    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3376        let mut i = 0;
 3377        let mut regions = self.autoclose_regions.as_slice();
 3378        selections.into_iter().map(move |selection| {
 3379            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3380
 3381            let mut enclosing = None;
 3382            while let Some(pair_state) = regions.get(i) {
 3383                if pair_state.range.end.to_offset(buffer) < range.start {
 3384                    regions = &regions[i + 1..];
 3385                    i = 0;
 3386                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3387                    break;
 3388                } else {
 3389                    if pair_state.selection_id == selection.id {
 3390                        enclosing = Some(pair_state);
 3391                    }
 3392                    i += 1;
 3393                }
 3394            }
 3395
 3396            (selection, enclosing)
 3397        })
 3398    }
 3399
 3400    /// Remove any autoclose regions that no longer contain their selection.
 3401    fn invalidate_autoclose_regions(
 3402        &mut self,
 3403        mut selections: &[Selection<Anchor>],
 3404        buffer: &MultiBufferSnapshot,
 3405    ) {
 3406        self.autoclose_regions.retain(|state| {
 3407            let mut i = 0;
 3408            while let Some(selection) = selections.get(i) {
 3409                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3410                    selections = &selections[1..];
 3411                    continue;
 3412                }
 3413                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3414                    break;
 3415                }
 3416                if selection.id == state.selection_id {
 3417                    return true;
 3418                } else {
 3419                    i += 1;
 3420                }
 3421            }
 3422            false
 3423        });
 3424    }
 3425
 3426    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3427        let offset = position.to_offset(buffer);
 3428        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3429        if offset > word_range.start && kind == Some(CharKind::Word) {
 3430            Some(
 3431                buffer
 3432                    .text_for_range(word_range.start..offset)
 3433                    .collect::<String>(),
 3434            )
 3435        } else {
 3436            None
 3437        }
 3438    }
 3439
 3440    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3441        self.refresh_inlay_hints(
 3442            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3443            cx,
 3444        );
 3445    }
 3446
 3447    pub fn inlay_hints_enabled(&self) -> bool {
 3448        self.inlay_hint_cache.enabled
 3449    }
 3450
 3451    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3452        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3453            return;
 3454        }
 3455
 3456        let reason_description = reason.description();
 3457        let ignore_debounce = matches!(
 3458            reason,
 3459            InlayHintRefreshReason::SettingsChange(_)
 3460                | InlayHintRefreshReason::Toggle(_)
 3461                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3462        );
 3463        let (invalidate_cache, required_languages) = match reason {
 3464            InlayHintRefreshReason::Toggle(enabled) => {
 3465                self.inlay_hint_cache.enabled = enabled;
 3466                if enabled {
 3467                    (InvalidationStrategy::RefreshRequested, None)
 3468                } else {
 3469                    self.inlay_hint_cache.clear();
 3470                    self.splice_inlays(
 3471                        self.visible_inlay_hints(cx)
 3472                            .iter()
 3473                            .map(|inlay| inlay.id)
 3474                            .collect(),
 3475                        Vec::new(),
 3476                        cx,
 3477                    );
 3478                    return;
 3479                }
 3480            }
 3481            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3482                match self.inlay_hint_cache.update_settings(
 3483                    &self.buffer,
 3484                    new_settings,
 3485                    self.visible_inlay_hints(cx),
 3486                    cx,
 3487                ) {
 3488                    ControlFlow::Break(Some(InlaySplice {
 3489                        to_remove,
 3490                        to_insert,
 3491                    })) => {
 3492                        self.splice_inlays(to_remove, to_insert, cx);
 3493                        return;
 3494                    }
 3495                    ControlFlow::Break(None) => return,
 3496                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3497                }
 3498            }
 3499            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3500                if let Some(InlaySplice {
 3501                    to_remove,
 3502                    to_insert,
 3503                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3504                {
 3505                    self.splice_inlays(to_remove, to_insert, cx);
 3506                }
 3507                return;
 3508            }
 3509            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3510            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3511                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3512            }
 3513            InlayHintRefreshReason::RefreshRequested => {
 3514                (InvalidationStrategy::RefreshRequested, None)
 3515            }
 3516        };
 3517
 3518        if let Some(InlaySplice {
 3519            to_remove,
 3520            to_insert,
 3521        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3522            reason_description,
 3523            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3524            invalidate_cache,
 3525            ignore_debounce,
 3526            cx,
 3527        ) {
 3528            self.splice_inlays(to_remove, to_insert, cx);
 3529        }
 3530    }
 3531
 3532    fn visible_inlay_hints(&self, cx: &ViewContext<Editor>) -> Vec<Inlay> {
 3533        self.display_map
 3534            .read(cx)
 3535            .current_inlays()
 3536            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3537            .cloned()
 3538            .collect()
 3539    }
 3540
 3541    pub fn excerpts_for_inlay_hints_query(
 3542        &self,
 3543        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3544        cx: &mut ViewContext<Editor>,
 3545    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3546        let Some(project) = self.project.as_ref() else {
 3547            return HashMap::default();
 3548        };
 3549        let project = project.read(cx);
 3550        let multi_buffer = self.buffer().read(cx);
 3551        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3552        let multi_buffer_visible_start = self
 3553            .scroll_manager
 3554            .anchor()
 3555            .anchor
 3556            .to_point(&multi_buffer_snapshot);
 3557        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3558            multi_buffer_visible_start
 3559                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3560            Bias::Left,
 3561        );
 3562        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3563        multi_buffer_snapshot
 3564            .range_to_buffer_ranges(multi_buffer_visible_range)
 3565            .into_iter()
 3566            .filter(|(_, excerpt_visible_range)| !excerpt_visible_range.is_empty())
 3567            .filter_map(|(excerpt, excerpt_visible_range)| {
 3568                let buffer_file = project::File::from_dyn(excerpt.buffer().file())?;
 3569                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3570                let worktree_entry = buffer_worktree
 3571                    .read(cx)
 3572                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3573                if worktree_entry.is_ignored {
 3574                    return None;
 3575                }
 3576
 3577                let language = excerpt.buffer().language()?;
 3578                if let Some(restrict_to_languages) = restrict_to_languages {
 3579                    if !restrict_to_languages.contains(language) {
 3580                        return None;
 3581                    }
 3582                }
 3583                Some((
 3584                    excerpt.id(),
 3585                    (
 3586                        multi_buffer.buffer(excerpt.buffer_id()).unwrap(),
 3587                        excerpt.buffer().version().clone(),
 3588                        excerpt_visible_range,
 3589                    ),
 3590                ))
 3591            })
 3592            .collect()
 3593    }
 3594
 3595    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3596        TextLayoutDetails {
 3597            text_system: cx.text_system().clone(),
 3598            editor_style: self.style.clone().unwrap(),
 3599            rem_size: cx.rem_size(),
 3600            scroll_anchor: self.scroll_manager.anchor(),
 3601            visible_rows: self.visible_line_count(),
 3602            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3603        }
 3604    }
 3605
 3606    pub fn splice_inlays(
 3607        &self,
 3608        to_remove: Vec<InlayId>,
 3609        to_insert: Vec<Inlay>,
 3610        cx: &mut ViewContext<Self>,
 3611    ) {
 3612        self.display_map.update(cx, |display_map, cx| {
 3613            display_map.splice_inlays(to_remove, to_insert, cx)
 3614        });
 3615        cx.notify();
 3616    }
 3617
 3618    fn trigger_on_type_formatting(
 3619        &self,
 3620        input: String,
 3621        cx: &mut ViewContext<Self>,
 3622    ) -> Option<Task<Result<()>>> {
 3623        if input.len() != 1 {
 3624            return None;
 3625        }
 3626
 3627        let project = self.project.as_ref()?;
 3628        let position = self.selections.newest_anchor().head();
 3629        let (buffer, buffer_position) = self
 3630            .buffer
 3631            .read(cx)
 3632            .text_anchor_for_position(position, cx)?;
 3633
 3634        let settings = language_settings::language_settings(
 3635            buffer
 3636                .read(cx)
 3637                .language_at(buffer_position)
 3638                .map(|l| l.name()),
 3639            buffer.read(cx).file(),
 3640            cx,
 3641        );
 3642        if !settings.use_on_type_format {
 3643            return None;
 3644        }
 3645
 3646        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3647        // hence we do LSP request & edit on host side only — add formats to host's history.
 3648        let push_to_lsp_host_history = true;
 3649        // If this is not the host, append its history with new edits.
 3650        let push_to_client_history = project.read(cx).is_via_collab();
 3651
 3652        let on_type_formatting = project.update(cx, |project, cx| {
 3653            project.on_type_format(
 3654                buffer.clone(),
 3655                buffer_position,
 3656                input,
 3657                push_to_lsp_host_history,
 3658                cx,
 3659            )
 3660        });
 3661        Some(cx.spawn(|editor, mut cx| async move {
 3662            if let Some(transaction) = on_type_formatting.await? {
 3663                if push_to_client_history {
 3664                    buffer
 3665                        .update(&mut cx, |buffer, _| {
 3666                            buffer.push_transaction(transaction, Instant::now());
 3667                        })
 3668                        .ok();
 3669                }
 3670                editor.update(&mut cx, |editor, cx| {
 3671                    editor.refresh_document_highlights(cx);
 3672                })?;
 3673            }
 3674            Ok(())
 3675        }))
 3676    }
 3677
 3678    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3679        if self.pending_rename.is_some() {
 3680            return;
 3681        }
 3682
 3683        let Some(provider) = self.completion_provider.as_ref() else {
 3684            return;
 3685        };
 3686
 3687        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3688            return;
 3689        }
 3690
 3691        let position = self.selections.newest_anchor().head();
 3692        let (buffer, buffer_position) =
 3693            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3694                output
 3695            } else {
 3696                return;
 3697            };
 3698        let show_completion_documentation = buffer
 3699            .read(cx)
 3700            .snapshot()
 3701            .settings_at(buffer_position, cx)
 3702            .show_completion_documentation;
 3703
 3704        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3705
 3706        let trigger_kind = match &options.trigger {
 3707            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3708                CompletionTriggerKind::TRIGGER_CHARACTER
 3709            }
 3710            _ => CompletionTriggerKind::INVOKED,
 3711        };
 3712        let completion_context = CompletionContext {
 3713            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3714                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3715                    Some(String::from(trigger))
 3716                } else {
 3717                    None
 3718                }
 3719            }),
 3720            trigger_kind,
 3721        };
 3722        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3723        let sort_completions = provider.sort_completions();
 3724
 3725        let id = post_inc(&mut self.next_completion_id);
 3726        let task = cx.spawn(|editor, mut cx| {
 3727            async move {
 3728                editor.update(&mut cx, |this, _| {
 3729                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3730                })?;
 3731                let completions = completions.await.log_err();
 3732                let menu = if let Some(completions) = completions {
 3733                    let mut menu = CompletionsMenu::new(
 3734                        id,
 3735                        sort_completions,
 3736                        show_completion_documentation,
 3737                        position,
 3738                        buffer.clone(),
 3739                        completions.into(),
 3740                    );
 3741
 3742                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3743                        .await;
 3744
 3745                    menu.visible().then_some(menu)
 3746                } else {
 3747                    None
 3748                };
 3749
 3750                editor.update(&mut cx, |editor, cx| {
 3751                    match editor.context_menu.borrow().as_ref() {
 3752                        None => {}
 3753                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3754                            if prev_menu.id > id {
 3755                                return;
 3756                            }
 3757                        }
 3758                        _ => return,
 3759                    }
 3760
 3761                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3762                        let mut menu = menu.unwrap();
 3763                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3764
 3765                        if editor.show_inline_completions_in_menu(cx) {
 3766                            if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3767                                menu.show_inline_completion_hint(hint);
 3768                            }
 3769                        } else {
 3770                            editor.discard_inline_completion(false, cx);
 3771                        }
 3772
 3773                        *editor.context_menu.borrow_mut() =
 3774                            Some(CodeContextMenu::Completions(menu));
 3775
 3776                        cx.notify();
 3777                    } else if editor.completion_tasks.len() <= 1 {
 3778                        // If there are no more completion tasks and the last menu was
 3779                        // empty, we should hide it.
 3780                        let was_hidden = editor.hide_context_menu(cx).is_none();
 3781                        // If it was already hidden and we don't show inline
 3782                        // completions in the menu, we should also show the
 3783                        // inline-completion when available.
 3784                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3785                            editor.update_visible_inline_completion(cx);
 3786                        }
 3787                    }
 3788                })?;
 3789
 3790                Ok::<_, anyhow::Error>(())
 3791            }
 3792            .log_err()
 3793        });
 3794
 3795        self.completion_tasks.push((id, task));
 3796    }
 3797
 3798    pub fn confirm_completion(
 3799        &mut self,
 3800        action: &ConfirmCompletion,
 3801        cx: &mut ViewContext<Self>,
 3802    ) -> Option<Task<Result<()>>> {
 3803        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3804    }
 3805
 3806    pub fn compose_completion(
 3807        &mut self,
 3808        action: &ComposeCompletion,
 3809        cx: &mut ViewContext<Self>,
 3810    ) -> Option<Task<Result<()>>> {
 3811        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3812    }
 3813
 3814    fn do_completion(
 3815        &mut self,
 3816        item_ix: Option<usize>,
 3817        intent: CompletionIntent,
 3818        cx: &mut ViewContext<Editor>,
 3819    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3820        use language::ToOffset as _;
 3821
 3822        let completions_menu =
 3823            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3824                menu
 3825            } else {
 3826                return None;
 3827            };
 3828
 3829        let mat = completions_menu
 3830            .entries
 3831            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3832
 3833        let mat = match mat {
 3834            CompletionEntry::InlineCompletionHint { .. } => {
 3835                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3836                cx.stop_propagation();
 3837                return Some(Task::ready(Ok(())));
 3838            }
 3839            CompletionEntry::Match(mat) => {
 3840                if self.show_inline_completions_in_menu(cx) {
 3841                    self.discard_inline_completion(true, cx);
 3842                }
 3843                mat
 3844            }
 3845        };
 3846
 3847        let buffer_handle = completions_menu.buffer;
 3848        let completion = completions_menu
 3849            .completions
 3850            .borrow()
 3851            .get(mat.candidate_id)?
 3852            .clone();
 3853        cx.stop_propagation();
 3854
 3855        let snippet;
 3856        let text;
 3857
 3858        if completion.is_snippet() {
 3859            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3860            text = snippet.as_ref().unwrap().text.clone();
 3861        } else {
 3862            snippet = None;
 3863            text = completion.new_text.clone();
 3864        };
 3865        let selections = self.selections.all::<usize>(cx);
 3866        let buffer = buffer_handle.read(cx);
 3867        let old_range = completion.old_range.to_offset(buffer);
 3868        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3869
 3870        let newest_selection = self.selections.newest_anchor();
 3871        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3872            return None;
 3873        }
 3874
 3875        let lookbehind = newest_selection
 3876            .start
 3877            .text_anchor
 3878            .to_offset(buffer)
 3879            .saturating_sub(old_range.start);
 3880        let lookahead = old_range
 3881            .end
 3882            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3883        let mut common_prefix_len = old_text
 3884            .bytes()
 3885            .zip(text.bytes())
 3886            .take_while(|(a, b)| a == b)
 3887            .count();
 3888
 3889        let snapshot = self.buffer.read(cx).snapshot(cx);
 3890        let mut range_to_replace: Option<Range<isize>> = None;
 3891        let mut ranges = Vec::new();
 3892        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3893        for selection in &selections {
 3894            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3895                let start = selection.start.saturating_sub(lookbehind);
 3896                let end = selection.end + lookahead;
 3897                if selection.id == newest_selection.id {
 3898                    range_to_replace = Some(
 3899                        ((start + common_prefix_len) as isize - selection.start as isize)
 3900                            ..(end as isize - selection.start as isize),
 3901                    );
 3902                }
 3903                ranges.push(start + common_prefix_len..end);
 3904            } else {
 3905                common_prefix_len = 0;
 3906                ranges.clear();
 3907                ranges.extend(selections.iter().map(|s| {
 3908                    if s.id == newest_selection.id {
 3909                        range_to_replace = Some(
 3910                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3911                                - selection.start as isize
 3912                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3913                                    - selection.start as isize,
 3914                        );
 3915                        old_range.clone()
 3916                    } else {
 3917                        s.start..s.end
 3918                    }
 3919                }));
 3920                break;
 3921            }
 3922            if !self.linked_edit_ranges.is_empty() {
 3923                let start_anchor = snapshot.anchor_before(selection.head());
 3924                let end_anchor = snapshot.anchor_after(selection.tail());
 3925                if let Some(ranges) = self
 3926                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3927                {
 3928                    for (buffer, edits) in ranges {
 3929                        linked_edits.entry(buffer.clone()).or_default().extend(
 3930                            edits
 3931                                .into_iter()
 3932                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3933                        );
 3934                    }
 3935                }
 3936            }
 3937        }
 3938        let text = &text[common_prefix_len..];
 3939
 3940        cx.emit(EditorEvent::InputHandled {
 3941            utf16_range_to_replace: range_to_replace,
 3942            text: text.into(),
 3943        });
 3944
 3945        self.transact(cx, |this, cx| {
 3946            if let Some(mut snippet) = snippet {
 3947                snippet.text = text.to_string();
 3948                for tabstop in snippet
 3949                    .tabstops
 3950                    .iter_mut()
 3951                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3952                {
 3953                    tabstop.start -= common_prefix_len as isize;
 3954                    tabstop.end -= common_prefix_len as isize;
 3955                }
 3956
 3957                this.insert_snippet(&ranges, snippet, cx).log_err();
 3958            } else {
 3959                this.buffer.update(cx, |buffer, cx| {
 3960                    buffer.edit(
 3961                        ranges.iter().map(|range| (range.clone(), text)),
 3962                        this.autoindent_mode.clone(),
 3963                        cx,
 3964                    );
 3965                });
 3966            }
 3967            for (buffer, edits) in linked_edits {
 3968                buffer.update(cx, |buffer, cx| {
 3969                    let snapshot = buffer.snapshot();
 3970                    let edits = edits
 3971                        .into_iter()
 3972                        .map(|(range, text)| {
 3973                            use text::ToPoint as TP;
 3974                            let end_point = TP::to_point(&range.end, &snapshot);
 3975                            let start_point = TP::to_point(&range.start, &snapshot);
 3976                            (start_point..end_point, text)
 3977                        })
 3978                        .sorted_by_key(|(range, _)| range.start)
 3979                        .collect::<Vec<_>>();
 3980                    buffer.edit(edits, None, cx);
 3981                })
 3982            }
 3983
 3984            this.refresh_inline_completion(true, false, cx);
 3985        });
 3986
 3987        let show_new_completions_on_confirm = completion
 3988            .confirm
 3989            .as_ref()
 3990            .map_or(false, |confirm| confirm(intent, cx));
 3991        if show_new_completions_on_confirm {
 3992            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3993        }
 3994
 3995        let provider = self.completion_provider.as_ref()?;
 3996        drop(completion);
 3997        let apply_edits = provider.apply_additional_edits_for_completion(
 3998            buffer_handle,
 3999            completions_menu.completions.clone(),
 4000            mat.candidate_id,
 4001            true,
 4002            cx,
 4003        );
 4004
 4005        let editor_settings = EditorSettings::get_global(cx);
 4006        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4007            // After the code completion is finished, users often want to know what signatures are needed.
 4008            // so we should automatically call signature_help
 4009            self.show_signature_help(&ShowSignatureHelp, cx);
 4010        }
 4011
 4012        Some(cx.foreground_executor().spawn(async move {
 4013            apply_edits.await?;
 4014            Ok(())
 4015        }))
 4016    }
 4017
 4018    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4019        let mut context_menu = self.context_menu.borrow_mut();
 4020        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4021            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4022                // Toggle if we're selecting the same one
 4023                *context_menu = None;
 4024                cx.notify();
 4025                return;
 4026            } else {
 4027                // Otherwise, clear it and start a new one
 4028                *context_menu = None;
 4029                cx.notify();
 4030            }
 4031        }
 4032        drop(context_menu);
 4033        let snapshot = self.snapshot(cx);
 4034        let deployed_from_indicator = action.deployed_from_indicator;
 4035        let mut task = self.code_actions_task.take();
 4036        let action = action.clone();
 4037        cx.spawn(|editor, mut cx| async move {
 4038            while let Some(prev_task) = task {
 4039                prev_task.await.log_err();
 4040                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4041            }
 4042
 4043            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4044                if editor.focus_handle.is_focused(cx) {
 4045                    let multibuffer_point = action
 4046                        .deployed_from_indicator
 4047                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4048                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4049                    let (buffer, buffer_row) = snapshot
 4050                        .buffer_snapshot
 4051                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4052                        .and_then(|(buffer_snapshot, range)| {
 4053                            editor
 4054                                .buffer
 4055                                .read(cx)
 4056                                .buffer(buffer_snapshot.remote_id())
 4057                                .map(|buffer| (buffer, range.start.row))
 4058                        })?;
 4059                    let (_, code_actions) = editor
 4060                        .available_code_actions
 4061                        .clone()
 4062                        .and_then(|(location, code_actions)| {
 4063                            let snapshot = location.buffer.read(cx).snapshot();
 4064                            let point_range = location.range.to_point(&snapshot);
 4065                            let point_range = point_range.start.row..=point_range.end.row;
 4066                            if point_range.contains(&buffer_row) {
 4067                                Some((location, code_actions))
 4068                            } else {
 4069                                None
 4070                            }
 4071                        })
 4072                        .unzip();
 4073                    let buffer_id = buffer.read(cx).remote_id();
 4074                    let tasks = editor
 4075                        .tasks
 4076                        .get(&(buffer_id, buffer_row))
 4077                        .map(|t| Arc::new(t.to_owned()));
 4078                    if tasks.is_none() && code_actions.is_none() {
 4079                        return None;
 4080                    }
 4081
 4082                    editor.completion_tasks.clear();
 4083                    editor.discard_inline_completion(false, cx);
 4084                    let task_context =
 4085                        tasks
 4086                            .as_ref()
 4087                            .zip(editor.project.clone())
 4088                            .map(|(tasks, project)| {
 4089                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4090                            });
 4091
 4092                    Some(cx.spawn(|editor, mut cx| async move {
 4093                        let task_context = match task_context {
 4094                            Some(task_context) => task_context.await,
 4095                            None => None,
 4096                        };
 4097                        let resolved_tasks =
 4098                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4099                                Rc::new(ResolvedTasks {
 4100                                    templates: tasks.resolve(&task_context).collect(),
 4101                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4102                                        multibuffer_point.row,
 4103                                        tasks.column,
 4104                                    )),
 4105                                })
 4106                            });
 4107                        let spawn_straight_away = resolved_tasks
 4108                            .as_ref()
 4109                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4110                            && code_actions
 4111                                .as_ref()
 4112                                .map_or(true, |actions| actions.is_empty());
 4113                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4114                            *editor.context_menu.borrow_mut() =
 4115                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4116                                    buffer,
 4117                                    actions: CodeActionContents {
 4118                                        tasks: resolved_tasks,
 4119                                        actions: code_actions,
 4120                                    },
 4121                                    selected_item: Default::default(),
 4122                                    scroll_handle: UniformListScrollHandle::default(),
 4123                                    deployed_from_indicator,
 4124                                }));
 4125                            if spawn_straight_away {
 4126                                if let Some(task) = editor.confirm_code_action(
 4127                                    &ConfirmCodeAction { item_ix: Some(0) },
 4128                                    cx,
 4129                                ) {
 4130                                    cx.notify();
 4131                                    return task;
 4132                                }
 4133                            }
 4134                            cx.notify();
 4135                            Task::ready(Ok(()))
 4136                        }) {
 4137                            task.await
 4138                        } else {
 4139                            Ok(())
 4140                        }
 4141                    }))
 4142                } else {
 4143                    Some(Task::ready(Ok(())))
 4144                }
 4145            })?;
 4146            if let Some(task) = spawned_test_task {
 4147                task.await?;
 4148            }
 4149
 4150            Ok::<_, anyhow::Error>(())
 4151        })
 4152        .detach_and_log_err(cx);
 4153    }
 4154
 4155    pub fn confirm_code_action(
 4156        &mut self,
 4157        action: &ConfirmCodeAction,
 4158        cx: &mut ViewContext<Self>,
 4159    ) -> Option<Task<Result<()>>> {
 4160        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4161            menu
 4162        } else {
 4163            return None;
 4164        };
 4165        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4166        let action = actions_menu.actions.get(action_ix)?;
 4167        let title = action.label();
 4168        let buffer = actions_menu.buffer;
 4169        let workspace = self.workspace()?;
 4170
 4171        match action {
 4172            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4173                workspace.update(cx, |workspace, cx| {
 4174                    workspace::tasks::schedule_resolved_task(
 4175                        workspace,
 4176                        task_source_kind,
 4177                        resolved_task,
 4178                        false,
 4179                        cx,
 4180                    );
 4181
 4182                    Some(Task::ready(Ok(())))
 4183                })
 4184            }
 4185            CodeActionsItem::CodeAction {
 4186                excerpt_id,
 4187                action,
 4188                provider,
 4189            } => {
 4190                let apply_code_action =
 4191                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4192                let workspace = workspace.downgrade();
 4193                Some(cx.spawn(|editor, cx| async move {
 4194                    let project_transaction = apply_code_action.await?;
 4195                    Self::open_project_transaction(
 4196                        &editor,
 4197                        workspace,
 4198                        project_transaction,
 4199                        title,
 4200                        cx,
 4201                    )
 4202                    .await
 4203                }))
 4204            }
 4205        }
 4206    }
 4207
 4208    pub async fn open_project_transaction(
 4209        this: &WeakView<Editor>,
 4210        workspace: WeakView<Workspace>,
 4211        transaction: ProjectTransaction,
 4212        title: String,
 4213        mut cx: AsyncWindowContext,
 4214    ) -> Result<()> {
 4215        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4216        cx.update(|cx| {
 4217            entries.sort_unstable_by_key(|(buffer, _)| {
 4218                buffer.read(cx).file().map(|f| f.path().clone())
 4219            });
 4220        })?;
 4221
 4222        // If the project transaction's edits are all contained within this editor, then
 4223        // avoid opening a new editor to display them.
 4224
 4225        if let Some((buffer, transaction)) = entries.first() {
 4226            if entries.len() == 1 {
 4227                let excerpt = this.update(&mut cx, |editor, cx| {
 4228                    editor
 4229                        .buffer()
 4230                        .read(cx)
 4231                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4232                })?;
 4233                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4234                    if excerpted_buffer == *buffer {
 4235                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4236                            let excerpt_range = excerpt_range.to_offset(buffer);
 4237                            buffer
 4238                                .edited_ranges_for_transaction::<usize>(transaction)
 4239                                .all(|range| {
 4240                                    excerpt_range.start <= range.start
 4241                                        && excerpt_range.end >= range.end
 4242                                })
 4243                        })?;
 4244
 4245                        if all_edits_within_excerpt {
 4246                            return Ok(());
 4247                        }
 4248                    }
 4249                }
 4250            }
 4251        } else {
 4252            return Ok(());
 4253        }
 4254
 4255        let mut ranges_to_highlight = Vec::new();
 4256        let excerpt_buffer = cx.new_model(|cx| {
 4257            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4258            for (buffer_handle, transaction) in &entries {
 4259                let buffer = buffer_handle.read(cx);
 4260                ranges_to_highlight.extend(
 4261                    multibuffer.push_excerpts_with_context_lines(
 4262                        buffer_handle.clone(),
 4263                        buffer
 4264                            .edited_ranges_for_transaction::<usize>(transaction)
 4265                            .collect(),
 4266                        DEFAULT_MULTIBUFFER_CONTEXT,
 4267                        cx,
 4268                    ),
 4269                );
 4270            }
 4271            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4272            multibuffer
 4273        })?;
 4274
 4275        workspace.update(&mut cx, |workspace, cx| {
 4276            let project = workspace.project().clone();
 4277            let editor =
 4278                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4279            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4280            editor.update(cx, |editor, cx| {
 4281                editor.highlight_background::<Self>(
 4282                    &ranges_to_highlight,
 4283                    |theme| theme.editor_highlighted_line_background,
 4284                    cx,
 4285                );
 4286            });
 4287        })?;
 4288
 4289        Ok(())
 4290    }
 4291
 4292    pub fn clear_code_action_providers(&mut self) {
 4293        self.code_action_providers.clear();
 4294        self.available_code_actions.take();
 4295    }
 4296
 4297    pub fn add_code_action_provider(
 4298        &mut self,
 4299        provider: Rc<dyn CodeActionProvider>,
 4300        cx: &mut ViewContext<Self>,
 4301    ) {
 4302        if self
 4303            .code_action_providers
 4304            .iter()
 4305            .any(|existing_provider| existing_provider.id() == provider.id())
 4306        {
 4307            return;
 4308        }
 4309
 4310        self.code_action_providers.push(provider);
 4311        self.refresh_code_actions(cx);
 4312    }
 4313
 4314    pub fn remove_code_action_provider(&mut self, id: Arc<str>, cx: &mut ViewContext<Self>) {
 4315        self.code_action_providers
 4316            .retain(|provider| provider.id() != id);
 4317        self.refresh_code_actions(cx);
 4318    }
 4319
 4320    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4321        let buffer = self.buffer.read(cx);
 4322        let newest_selection = self.selections.newest_anchor().clone();
 4323        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4324        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4325        if start_buffer != end_buffer {
 4326            return None;
 4327        }
 4328
 4329        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4330            cx.background_executor()
 4331                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4332                .await;
 4333
 4334            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4335                let providers = this.code_action_providers.clone();
 4336                let tasks = this
 4337                    .code_action_providers
 4338                    .iter()
 4339                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4340                    .collect::<Vec<_>>();
 4341                (providers, tasks)
 4342            })?;
 4343
 4344            let mut actions = Vec::new();
 4345            for (provider, provider_actions) in
 4346                providers.into_iter().zip(future::join_all(tasks).await)
 4347            {
 4348                if let Some(provider_actions) = provider_actions.log_err() {
 4349                    actions.extend(provider_actions.into_iter().map(|action| {
 4350                        AvailableCodeAction {
 4351                            excerpt_id: newest_selection.start.excerpt_id,
 4352                            action,
 4353                            provider: provider.clone(),
 4354                        }
 4355                    }));
 4356                }
 4357            }
 4358
 4359            this.update(&mut cx, |this, cx| {
 4360                this.available_code_actions = if actions.is_empty() {
 4361                    None
 4362                } else {
 4363                    Some((
 4364                        Location {
 4365                            buffer: start_buffer,
 4366                            range: start..end,
 4367                        },
 4368                        actions.into(),
 4369                    ))
 4370                };
 4371                cx.notify();
 4372            })
 4373        }));
 4374        None
 4375    }
 4376
 4377    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4378        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4379            self.show_git_blame_inline = false;
 4380
 4381            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4382                cx.background_executor().timer(delay).await;
 4383
 4384                this.update(&mut cx, |this, cx| {
 4385                    this.show_git_blame_inline = true;
 4386                    cx.notify();
 4387                })
 4388                .log_err();
 4389            }));
 4390        }
 4391    }
 4392
 4393    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4394        if self.pending_rename.is_some() {
 4395            return None;
 4396        }
 4397
 4398        let provider = self.semantics_provider.clone()?;
 4399        let buffer = self.buffer.read(cx);
 4400        let newest_selection = self.selections.newest_anchor().clone();
 4401        let cursor_position = newest_selection.head();
 4402        let (cursor_buffer, cursor_buffer_position) =
 4403            buffer.text_anchor_for_position(cursor_position, cx)?;
 4404        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4405        if cursor_buffer != tail_buffer {
 4406            return None;
 4407        }
 4408        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4409        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4410            cx.background_executor()
 4411                .timer(Duration::from_millis(debounce))
 4412                .await;
 4413
 4414            let highlights = if let Some(highlights) = cx
 4415                .update(|cx| {
 4416                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4417                })
 4418                .ok()
 4419                .flatten()
 4420            {
 4421                highlights.await.log_err()
 4422            } else {
 4423                None
 4424            };
 4425
 4426            if let Some(highlights) = highlights {
 4427                this.update(&mut cx, |this, cx| {
 4428                    if this.pending_rename.is_some() {
 4429                        return;
 4430                    }
 4431
 4432                    let buffer_id = cursor_position.buffer_id;
 4433                    let buffer = this.buffer.read(cx);
 4434                    if !buffer
 4435                        .text_anchor_for_position(cursor_position, cx)
 4436                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4437                    {
 4438                        return;
 4439                    }
 4440
 4441                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4442                    let mut write_ranges = Vec::new();
 4443                    let mut read_ranges = Vec::new();
 4444                    for highlight in highlights {
 4445                        for (excerpt_id, excerpt_range) in
 4446                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4447                        {
 4448                            let start = highlight
 4449                                .range
 4450                                .start
 4451                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4452                            let end = highlight
 4453                                .range
 4454                                .end
 4455                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4456                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4457                                continue;
 4458                            }
 4459
 4460                            let range = Anchor {
 4461                                buffer_id,
 4462                                excerpt_id,
 4463                                text_anchor: start,
 4464                            }..Anchor {
 4465                                buffer_id,
 4466                                excerpt_id,
 4467                                text_anchor: end,
 4468                            };
 4469                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4470                                write_ranges.push(range);
 4471                            } else {
 4472                                read_ranges.push(range);
 4473                            }
 4474                        }
 4475                    }
 4476
 4477                    this.highlight_background::<DocumentHighlightRead>(
 4478                        &read_ranges,
 4479                        |theme| theme.editor_document_highlight_read_background,
 4480                        cx,
 4481                    );
 4482                    this.highlight_background::<DocumentHighlightWrite>(
 4483                        &write_ranges,
 4484                        |theme| theme.editor_document_highlight_write_background,
 4485                        cx,
 4486                    );
 4487                    cx.notify();
 4488                })
 4489                .log_err();
 4490            }
 4491        }));
 4492        None
 4493    }
 4494
 4495    pub fn refresh_inline_completion(
 4496        &mut self,
 4497        debounce: bool,
 4498        user_requested: bool,
 4499        cx: &mut ViewContext<Self>,
 4500    ) -> Option<()> {
 4501        let provider = self.inline_completion_provider()?;
 4502        let cursor = self.selections.newest_anchor().head();
 4503        let (buffer, cursor_buffer_position) =
 4504            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4505
 4506        if !user_requested
 4507            && (!self.enable_inline_completions
 4508                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4509                || !self.is_focused(cx)
 4510                || buffer.read(cx).is_empty())
 4511        {
 4512            self.discard_inline_completion(false, cx);
 4513            return None;
 4514        }
 4515
 4516        self.update_visible_inline_completion(cx);
 4517        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4518        Some(())
 4519    }
 4520
 4521    fn cycle_inline_completion(
 4522        &mut self,
 4523        direction: Direction,
 4524        cx: &mut ViewContext<Self>,
 4525    ) -> Option<()> {
 4526        let provider = self.inline_completion_provider()?;
 4527        let cursor = self.selections.newest_anchor().head();
 4528        let (buffer, cursor_buffer_position) =
 4529            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4530        if !self.enable_inline_completions
 4531            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4532        {
 4533            return None;
 4534        }
 4535
 4536        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4537        self.update_visible_inline_completion(cx);
 4538
 4539        Some(())
 4540    }
 4541
 4542    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4543        if !self.has_active_inline_completion() {
 4544            self.refresh_inline_completion(false, true, cx);
 4545            return;
 4546        }
 4547
 4548        self.update_visible_inline_completion(cx);
 4549    }
 4550
 4551    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4552        self.show_cursor_names(cx);
 4553    }
 4554
 4555    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4556        self.show_cursor_names = true;
 4557        cx.notify();
 4558        cx.spawn(|this, mut cx| async move {
 4559            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4560            this.update(&mut cx, |this, cx| {
 4561                this.show_cursor_names = false;
 4562                cx.notify()
 4563            })
 4564            .ok()
 4565        })
 4566        .detach();
 4567    }
 4568
 4569    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4570        if self.has_active_inline_completion() {
 4571            self.cycle_inline_completion(Direction::Next, cx);
 4572        } else {
 4573            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4574            if is_copilot_disabled {
 4575                cx.propagate();
 4576            }
 4577        }
 4578    }
 4579
 4580    pub fn previous_inline_completion(
 4581        &mut self,
 4582        _: &PreviousInlineCompletion,
 4583        cx: &mut ViewContext<Self>,
 4584    ) {
 4585        if self.has_active_inline_completion() {
 4586            self.cycle_inline_completion(Direction::Prev, cx);
 4587        } else {
 4588            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4589            if is_copilot_disabled {
 4590                cx.propagate();
 4591            }
 4592        }
 4593    }
 4594
 4595    pub fn accept_inline_completion(
 4596        &mut self,
 4597        _: &AcceptInlineCompletion,
 4598        cx: &mut ViewContext<Self>,
 4599    ) {
 4600        let buffer = self.buffer.read(cx);
 4601        let snapshot = buffer.snapshot(cx);
 4602        let selection = self.selections.newest_adjusted(cx);
 4603        let cursor = selection.head();
 4604        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4605        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4606        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4607        {
 4608            if cursor.column < suggested_indent.len
 4609                && cursor.column <= current_indent.len
 4610                && current_indent.len <= suggested_indent.len
 4611            {
 4612                self.tab(&Default::default(), cx);
 4613                return;
 4614            }
 4615        }
 4616
 4617        if self.show_inline_completions_in_menu(cx) {
 4618            self.hide_context_menu(cx);
 4619        }
 4620
 4621        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4622            return;
 4623        };
 4624
 4625        self.report_inline_completion_event(true, cx);
 4626
 4627        match &active_inline_completion.completion {
 4628            InlineCompletion::Move(position) => {
 4629                let position = *position;
 4630                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4631                    selections.select_anchor_ranges([position..position]);
 4632                });
 4633            }
 4634            InlineCompletion::Edit(edits) => {
 4635                if let Some(provider) = self.inline_completion_provider() {
 4636                    provider.accept(cx);
 4637                }
 4638
 4639                let snapshot = self.buffer.read(cx).snapshot(cx);
 4640                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4641
 4642                self.buffer.update(cx, |buffer, cx| {
 4643                    buffer.edit(edits.iter().cloned(), None, cx)
 4644                });
 4645
 4646                self.change_selections(None, cx, |s| {
 4647                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4648                });
 4649
 4650                self.update_visible_inline_completion(cx);
 4651                if self.active_inline_completion.is_none() {
 4652                    self.refresh_inline_completion(true, true, cx);
 4653                }
 4654
 4655                cx.notify();
 4656            }
 4657        }
 4658    }
 4659
 4660    pub fn accept_partial_inline_completion(
 4661        &mut self,
 4662        _: &AcceptPartialInlineCompletion,
 4663        cx: &mut ViewContext<Self>,
 4664    ) {
 4665        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4666            return;
 4667        };
 4668        if self.selections.count() != 1 {
 4669            return;
 4670        }
 4671
 4672        self.report_inline_completion_event(true, cx);
 4673
 4674        match &active_inline_completion.completion {
 4675            InlineCompletion::Move(position) => {
 4676                let position = *position;
 4677                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4678                    selections.select_anchor_ranges([position..position]);
 4679                });
 4680            }
 4681            InlineCompletion::Edit(edits) => {
 4682                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4683                    let text = edits[0].1.as_str();
 4684                    let mut partial_completion = text
 4685                        .chars()
 4686                        .by_ref()
 4687                        .take_while(|c| c.is_alphabetic())
 4688                        .collect::<String>();
 4689                    if partial_completion.is_empty() {
 4690                        partial_completion = text
 4691                            .chars()
 4692                            .by_ref()
 4693                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4694                            .collect::<String>();
 4695                    }
 4696
 4697                    cx.emit(EditorEvent::InputHandled {
 4698                        utf16_range_to_replace: None,
 4699                        text: partial_completion.clone().into(),
 4700                    });
 4701
 4702                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4703
 4704                    self.refresh_inline_completion(true, true, cx);
 4705                    cx.notify();
 4706                }
 4707            }
 4708        }
 4709    }
 4710
 4711    fn discard_inline_completion(
 4712        &mut self,
 4713        should_report_inline_completion_event: bool,
 4714        cx: &mut ViewContext<Self>,
 4715    ) -> bool {
 4716        if should_report_inline_completion_event {
 4717            self.report_inline_completion_event(false, cx);
 4718        }
 4719
 4720        if let Some(provider) = self.inline_completion_provider() {
 4721            provider.discard(cx);
 4722        }
 4723
 4724        self.take_active_inline_completion(cx).is_some()
 4725    }
 4726
 4727    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4728        let Some(provider) = self.inline_completion_provider() else {
 4729            return;
 4730        };
 4731        let Some(project) = self.project.as_ref() else {
 4732            return;
 4733        };
 4734        let Some((_, buffer, _)) = self
 4735            .buffer
 4736            .read(cx)
 4737            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4738        else {
 4739            return;
 4740        };
 4741
 4742        let project = project.read(cx);
 4743        let extension = buffer
 4744            .read(cx)
 4745            .file()
 4746            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4747        project.client().telemetry().report_inline_completion_event(
 4748            provider.name().into(),
 4749            accepted,
 4750            extension,
 4751        );
 4752    }
 4753
 4754    pub fn has_active_inline_completion(&self) -> bool {
 4755        self.active_inline_completion.is_some()
 4756    }
 4757
 4758    fn take_active_inline_completion(
 4759        &mut self,
 4760        cx: &mut ViewContext<Self>,
 4761    ) -> Option<InlineCompletion> {
 4762        let active_inline_completion = self.active_inline_completion.take()?;
 4763        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4764        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4765        Some(active_inline_completion.completion)
 4766    }
 4767
 4768    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4769        let selection = self.selections.newest_anchor();
 4770        let cursor = selection.head();
 4771        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4772        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4773        let excerpt_id = cursor.excerpt_id;
 4774
 4775        let completions_menu_has_precedence = !self.show_inline_completions_in_menu(cx)
 4776            && (self.context_menu.borrow().is_some()
 4777                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 4778        if completions_menu_has_precedence
 4779            || !offset_selection.is_empty()
 4780            || self
 4781                .active_inline_completion
 4782                .as_ref()
 4783                .map_or(false, |completion| {
 4784                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4785                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4786                    !invalidation_range.contains(&offset_selection.head())
 4787                })
 4788        {
 4789            self.discard_inline_completion(false, cx);
 4790            return None;
 4791        }
 4792
 4793        self.take_active_inline_completion(cx);
 4794        let provider = self.inline_completion_provider()?;
 4795
 4796        let (buffer, cursor_buffer_position) =
 4797            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4798
 4799        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4800        let edits = completion
 4801            .edits
 4802            .into_iter()
 4803            .flat_map(|(range, new_text)| {
 4804                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4805                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4806                Some((start..end, new_text))
 4807            })
 4808            .collect::<Vec<_>>();
 4809        if edits.is_empty() {
 4810            return None;
 4811        }
 4812
 4813        let first_edit_start = edits.first().unwrap().0.start;
 4814        let edit_start_row = first_edit_start
 4815            .to_point(&multibuffer)
 4816            .row
 4817            .saturating_sub(2);
 4818
 4819        let last_edit_end = edits.last().unwrap().0.end;
 4820        let edit_end_row = cmp::min(
 4821            multibuffer.max_point().row,
 4822            last_edit_end.to_point(&multibuffer).row + 2,
 4823        );
 4824
 4825        let cursor_row = cursor.to_point(&multibuffer).row;
 4826
 4827        let mut inlay_ids = Vec::new();
 4828        let invalidation_row_range;
 4829        let completion;
 4830        if cursor_row < edit_start_row {
 4831            invalidation_row_range = cursor_row..edit_end_row;
 4832            completion = InlineCompletion::Move(first_edit_start);
 4833        } else if cursor_row > edit_end_row {
 4834            invalidation_row_range = edit_start_row..cursor_row;
 4835            completion = InlineCompletion::Move(first_edit_start);
 4836        } else {
 4837            if edits
 4838                .iter()
 4839                .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4840            {
 4841                let mut inlays = Vec::new();
 4842                for (range, new_text) in &edits {
 4843                    let inlay = Inlay::inline_completion(
 4844                        post_inc(&mut self.next_inlay_id),
 4845                        range.start,
 4846                        new_text.as_str(),
 4847                    );
 4848                    inlay_ids.push(inlay.id);
 4849                    inlays.push(inlay);
 4850                }
 4851
 4852                self.splice_inlays(vec![], inlays, cx);
 4853            } else {
 4854                let background_color = cx.theme().status().deleted_background;
 4855                self.highlight_text::<InlineCompletionHighlight>(
 4856                    edits.iter().map(|(range, _)| range.clone()).collect(),
 4857                    HighlightStyle {
 4858                        background_color: Some(background_color),
 4859                        ..Default::default()
 4860                    },
 4861                    cx,
 4862                );
 4863            }
 4864
 4865            invalidation_row_range = edit_start_row..edit_end_row;
 4866            completion = InlineCompletion::Edit(edits);
 4867        };
 4868
 4869        let invalidation_range = multibuffer
 4870            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4871            ..multibuffer.anchor_after(Point::new(
 4872                invalidation_row_range.end,
 4873                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4874            ));
 4875
 4876        self.active_inline_completion = Some(InlineCompletionState {
 4877            inlay_ids,
 4878            completion,
 4879            invalidation_range,
 4880        });
 4881
 4882        if self.show_inline_completions_in_menu(cx) && self.has_active_completions_menu() {
 4883            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4884                match self.context_menu.borrow_mut().as_mut() {
 4885                    Some(CodeContextMenu::Completions(menu)) => {
 4886                        menu.show_inline_completion_hint(hint);
 4887                    }
 4888                    _ => {}
 4889                }
 4890            }
 4891        }
 4892
 4893        cx.notify();
 4894
 4895        Some(())
 4896    }
 4897
 4898    fn inline_completion_menu_hint(
 4899        &mut self,
 4900        cx: &mut ViewContext<Self>,
 4901    ) -> Option<InlineCompletionMenuHint> {
 4902        if self.has_active_inline_completion() {
 4903            let provider_name = self.inline_completion_provider()?.display_name();
 4904            let editor_snapshot = self.snapshot(cx);
 4905
 4906            let text = match &self.active_inline_completion.as_ref()?.completion {
 4907                InlineCompletion::Edit(edits) => {
 4908                    inline_completion_edit_text(&editor_snapshot, edits, true, cx)
 4909                }
 4910                InlineCompletion::Move(target) => {
 4911                    let target_point =
 4912                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4913                    let target_line = target_point.row + 1;
 4914                    InlineCompletionText::Move(
 4915                        format!("Jump to edit in line {}", target_line).into(),
 4916                    )
 4917                }
 4918            };
 4919
 4920            Some(InlineCompletionMenuHint {
 4921                provider_name,
 4922                text,
 4923            })
 4924        } else {
 4925            None
 4926        }
 4927    }
 4928
 4929    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4930        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4931    }
 4932
 4933    fn show_inline_completions_in_menu(&self, cx: &AppContext) -> bool {
 4934        EditorSettings::get_global(cx).show_inline_completions_in_menu
 4935            && self
 4936                .inline_completion_provider()
 4937                .map_or(false, |provider| provider.show_completions_in_menu())
 4938    }
 4939
 4940    fn render_code_actions_indicator(
 4941        &self,
 4942        _style: &EditorStyle,
 4943        row: DisplayRow,
 4944        is_active: bool,
 4945        cx: &mut ViewContext<Self>,
 4946    ) -> Option<IconButton> {
 4947        if self.available_code_actions.is_some() {
 4948            Some(
 4949                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4950                    .shape(ui::IconButtonShape::Square)
 4951                    .icon_size(IconSize::XSmall)
 4952                    .icon_color(Color::Muted)
 4953                    .toggle_state(is_active)
 4954                    .tooltip({
 4955                        let focus_handle = self.focus_handle.clone();
 4956                        move |cx| {
 4957                            Tooltip::for_action_in(
 4958                                "Toggle Code Actions",
 4959                                &ToggleCodeActions {
 4960                                    deployed_from_indicator: None,
 4961                                },
 4962                                &focus_handle,
 4963                                cx,
 4964                            )
 4965                        }
 4966                    })
 4967                    .on_click(cx.listener(move |editor, _e, cx| {
 4968                        editor.focus(cx);
 4969                        editor.toggle_code_actions(
 4970                            &ToggleCodeActions {
 4971                                deployed_from_indicator: Some(row),
 4972                            },
 4973                            cx,
 4974                        );
 4975                    })),
 4976            )
 4977        } else {
 4978            None
 4979        }
 4980    }
 4981
 4982    fn clear_tasks(&mut self) {
 4983        self.tasks.clear()
 4984    }
 4985
 4986    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4987        if self.tasks.insert(key, value).is_some() {
 4988            // This case should hopefully be rare, but just in case...
 4989            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4990        }
 4991    }
 4992
 4993    fn build_tasks_context(
 4994        project: &Model<Project>,
 4995        buffer: &Model<Buffer>,
 4996        buffer_row: u32,
 4997        tasks: &Arc<RunnableTasks>,
 4998        cx: &mut ViewContext<Self>,
 4999    ) -> Task<Option<task::TaskContext>> {
 5000        let position = Point::new(buffer_row, tasks.column);
 5001        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5002        let location = Location {
 5003            buffer: buffer.clone(),
 5004            range: range_start..range_start,
 5005        };
 5006        // Fill in the environmental variables from the tree-sitter captures
 5007        let mut captured_task_variables = TaskVariables::default();
 5008        for (capture_name, value) in tasks.extra_variables.clone() {
 5009            captured_task_variables.insert(
 5010                task::VariableName::Custom(capture_name.into()),
 5011                value.clone(),
 5012            );
 5013        }
 5014        project.update(cx, |project, cx| {
 5015            project.task_store().update(cx, |task_store, cx| {
 5016                task_store.task_context_for_location(captured_task_variables, location, cx)
 5017            })
 5018        })
 5019    }
 5020
 5021    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 5022        let Some((workspace, _)) = self.workspace.clone() else {
 5023            return;
 5024        };
 5025        let Some(project) = self.project.clone() else {
 5026            return;
 5027        };
 5028
 5029        // Try to find a closest, enclosing node using tree-sitter that has a
 5030        // task
 5031        let Some((buffer, buffer_row, tasks)) = self
 5032            .find_enclosing_node_task(cx)
 5033            // Or find the task that's closest in row-distance.
 5034            .or_else(|| self.find_closest_task(cx))
 5035        else {
 5036            return;
 5037        };
 5038
 5039        let reveal_strategy = action.reveal;
 5040        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5041        cx.spawn(|_, mut cx| async move {
 5042            let context = task_context.await?;
 5043            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5044
 5045            let resolved = resolved_task.resolved.as_mut()?;
 5046            resolved.reveal = reveal_strategy;
 5047
 5048            workspace
 5049                .update(&mut cx, |workspace, cx| {
 5050                    workspace::tasks::schedule_resolved_task(
 5051                        workspace,
 5052                        task_source_kind,
 5053                        resolved_task,
 5054                        false,
 5055                        cx,
 5056                    );
 5057                })
 5058                .ok()
 5059        })
 5060        .detach();
 5061    }
 5062
 5063    fn find_closest_task(
 5064        &mut self,
 5065        cx: &mut ViewContext<Self>,
 5066    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5067        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5068
 5069        let ((buffer_id, row), tasks) = self
 5070            .tasks
 5071            .iter()
 5072            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5073
 5074        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5075        let tasks = Arc::new(tasks.to_owned());
 5076        Some((buffer, *row, tasks))
 5077    }
 5078
 5079    fn find_enclosing_node_task(
 5080        &mut self,
 5081        cx: &mut ViewContext<Self>,
 5082    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5083        let snapshot = self.buffer.read(cx).snapshot(cx);
 5084        let offset = self.selections.newest::<usize>(cx).head();
 5085        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5086        let buffer_id = excerpt.buffer().remote_id();
 5087
 5088        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5089        let mut cursor = layer.node().walk();
 5090
 5091        while cursor.goto_first_child_for_byte(offset).is_some() {
 5092            if cursor.node().end_byte() == offset {
 5093                cursor.goto_next_sibling();
 5094            }
 5095        }
 5096
 5097        // Ascend to the smallest ancestor that contains the range and has a task.
 5098        loop {
 5099            let node = cursor.node();
 5100            let node_range = node.byte_range();
 5101            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5102
 5103            // Check if this node contains our offset
 5104            if node_range.start <= offset && node_range.end >= offset {
 5105                // If it contains offset, check for task
 5106                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5107                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5108                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5109                }
 5110            }
 5111
 5112            if !cursor.goto_parent() {
 5113                break;
 5114            }
 5115        }
 5116        None
 5117    }
 5118
 5119    fn render_run_indicator(
 5120        &self,
 5121        _style: &EditorStyle,
 5122        is_active: bool,
 5123        row: DisplayRow,
 5124        cx: &mut ViewContext<Self>,
 5125    ) -> IconButton {
 5126        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5127            .shape(ui::IconButtonShape::Square)
 5128            .icon_size(IconSize::XSmall)
 5129            .icon_color(Color::Muted)
 5130            .toggle_state(is_active)
 5131            .on_click(cx.listener(move |editor, _e, cx| {
 5132                editor.focus(cx);
 5133                editor.toggle_code_actions(
 5134                    &ToggleCodeActions {
 5135                        deployed_from_indicator: Some(row),
 5136                    },
 5137                    cx,
 5138                );
 5139            }))
 5140    }
 5141
 5142    #[cfg(any(feature = "test-support", test))]
 5143    pub fn context_menu_visible(&self) -> bool {
 5144        self.context_menu
 5145            .borrow()
 5146            .as_ref()
 5147            .map_or(false, |menu| menu.visible())
 5148    }
 5149
 5150    #[cfg(feature = "test-support")]
 5151    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5152        self.context_menu
 5153            .borrow()
 5154            .as_ref()
 5155            .map_or(false, |menu| match menu {
 5156                CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
 5157                    matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5158                }),
 5159                CodeContextMenu::CodeActions(_) => false,
 5160            })
 5161    }
 5162
 5163    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5164        self.context_menu
 5165            .borrow()
 5166            .as_ref()
 5167            .map(|menu| menu.origin(cursor_position))
 5168    }
 5169
 5170    fn render_context_menu(
 5171        &self,
 5172        style: &EditorStyle,
 5173        max_height_in_lines: u32,
 5174        cx: &mut ViewContext<Editor>,
 5175    ) -> Option<AnyElement> {
 5176        self.context_menu.borrow().as_ref().and_then(|menu| {
 5177            if menu.visible() {
 5178                Some(menu.render(style, max_height_in_lines, cx))
 5179            } else {
 5180                None
 5181            }
 5182        })
 5183    }
 5184
 5185    fn render_context_menu_aside(
 5186        &self,
 5187        style: &EditorStyle,
 5188        max_size: Size<Pixels>,
 5189        cx: &mut ViewContext<Editor>,
 5190    ) -> Option<AnyElement> {
 5191        self.context_menu.borrow().as_ref().and_then(|menu| {
 5192            if menu.visible() {
 5193                menu.render_aside(
 5194                    style,
 5195                    max_size,
 5196                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5197                    cx,
 5198                )
 5199            } else {
 5200                None
 5201            }
 5202        })
 5203    }
 5204
 5205    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5206        cx.notify();
 5207        self.completion_tasks.clear();
 5208        let context_menu = self.context_menu.borrow_mut().take();
 5209        if context_menu.is_some() && !self.show_inline_completions_in_menu(cx) {
 5210            self.update_visible_inline_completion(cx);
 5211        }
 5212        context_menu
 5213    }
 5214
 5215    fn show_snippet_choices(
 5216        &mut self,
 5217        choices: &Vec<String>,
 5218        selection: Range<Anchor>,
 5219        cx: &mut ViewContext<Self>,
 5220    ) {
 5221        if selection.start.buffer_id.is_none() {
 5222            return;
 5223        }
 5224        let buffer_id = selection.start.buffer_id.unwrap();
 5225        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5226        let id = post_inc(&mut self.next_completion_id);
 5227
 5228        if let Some(buffer) = buffer {
 5229            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5230                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5231            ));
 5232        }
 5233    }
 5234
 5235    pub fn insert_snippet(
 5236        &mut self,
 5237        insertion_ranges: &[Range<usize>],
 5238        snippet: Snippet,
 5239        cx: &mut ViewContext<Self>,
 5240    ) -> Result<()> {
 5241        struct Tabstop<T> {
 5242            is_end_tabstop: bool,
 5243            ranges: Vec<Range<T>>,
 5244            choices: Option<Vec<String>>,
 5245        }
 5246
 5247        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5248            let snippet_text: Arc<str> = snippet.text.clone().into();
 5249            buffer.edit(
 5250                insertion_ranges
 5251                    .iter()
 5252                    .cloned()
 5253                    .map(|range| (range, snippet_text.clone())),
 5254                Some(AutoindentMode::EachLine),
 5255                cx,
 5256            );
 5257
 5258            let snapshot = &*buffer.read(cx);
 5259            let snippet = &snippet;
 5260            snippet
 5261                .tabstops
 5262                .iter()
 5263                .map(|tabstop| {
 5264                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5265                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5266                    });
 5267                    let mut tabstop_ranges = tabstop
 5268                        .ranges
 5269                        .iter()
 5270                        .flat_map(|tabstop_range| {
 5271                            let mut delta = 0_isize;
 5272                            insertion_ranges.iter().map(move |insertion_range| {
 5273                                let insertion_start = insertion_range.start as isize + delta;
 5274                                delta +=
 5275                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5276
 5277                                let start = ((insertion_start + tabstop_range.start) as usize)
 5278                                    .min(snapshot.len());
 5279                                let end = ((insertion_start + tabstop_range.end) as usize)
 5280                                    .min(snapshot.len());
 5281                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5282                            })
 5283                        })
 5284                        .collect::<Vec<_>>();
 5285                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5286
 5287                    Tabstop {
 5288                        is_end_tabstop,
 5289                        ranges: tabstop_ranges,
 5290                        choices: tabstop.choices.clone(),
 5291                    }
 5292                })
 5293                .collect::<Vec<_>>()
 5294        });
 5295        if let Some(tabstop) = tabstops.first() {
 5296            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5297                s.select_ranges(tabstop.ranges.iter().cloned());
 5298            });
 5299
 5300            if let Some(choices) = &tabstop.choices {
 5301                if let Some(selection) = tabstop.ranges.first() {
 5302                    self.show_snippet_choices(choices, selection.clone(), cx)
 5303                }
 5304            }
 5305
 5306            // If we're already at the last tabstop and it's at the end of the snippet,
 5307            // we're done, we don't need to keep the state around.
 5308            if !tabstop.is_end_tabstop {
 5309                let choices = tabstops
 5310                    .iter()
 5311                    .map(|tabstop| tabstop.choices.clone())
 5312                    .collect();
 5313
 5314                let ranges = tabstops
 5315                    .into_iter()
 5316                    .map(|tabstop| tabstop.ranges)
 5317                    .collect::<Vec<_>>();
 5318
 5319                self.snippet_stack.push(SnippetState {
 5320                    active_index: 0,
 5321                    ranges,
 5322                    choices,
 5323                });
 5324            }
 5325
 5326            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5327            if self.autoclose_regions.is_empty() {
 5328                let snapshot = self.buffer.read(cx).snapshot(cx);
 5329                for selection in &mut self.selections.all::<Point>(cx) {
 5330                    let selection_head = selection.head();
 5331                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5332                        continue;
 5333                    };
 5334
 5335                    let mut bracket_pair = None;
 5336                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5337                    let prev_chars = snapshot
 5338                        .reversed_chars_at(selection_head)
 5339                        .collect::<String>();
 5340                    for (pair, enabled) in scope.brackets() {
 5341                        if enabled
 5342                            && pair.close
 5343                            && prev_chars.starts_with(pair.start.as_str())
 5344                            && next_chars.starts_with(pair.end.as_str())
 5345                        {
 5346                            bracket_pair = Some(pair.clone());
 5347                            break;
 5348                        }
 5349                    }
 5350                    if let Some(pair) = bracket_pair {
 5351                        let start = snapshot.anchor_after(selection_head);
 5352                        let end = snapshot.anchor_after(selection_head);
 5353                        self.autoclose_regions.push(AutocloseRegion {
 5354                            selection_id: selection.id,
 5355                            range: start..end,
 5356                            pair,
 5357                        });
 5358                    }
 5359                }
 5360            }
 5361        }
 5362        Ok(())
 5363    }
 5364
 5365    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5366        self.move_to_snippet_tabstop(Bias::Right, cx)
 5367    }
 5368
 5369    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5370        self.move_to_snippet_tabstop(Bias::Left, cx)
 5371    }
 5372
 5373    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5374        if let Some(mut snippet) = self.snippet_stack.pop() {
 5375            match bias {
 5376                Bias::Left => {
 5377                    if snippet.active_index > 0 {
 5378                        snippet.active_index -= 1;
 5379                    } else {
 5380                        self.snippet_stack.push(snippet);
 5381                        return false;
 5382                    }
 5383                }
 5384                Bias::Right => {
 5385                    if snippet.active_index + 1 < snippet.ranges.len() {
 5386                        snippet.active_index += 1;
 5387                    } else {
 5388                        self.snippet_stack.push(snippet);
 5389                        return false;
 5390                    }
 5391                }
 5392            }
 5393            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5394                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5395                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5396                });
 5397
 5398                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5399                    if let Some(selection) = current_ranges.first() {
 5400                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5401                    }
 5402                }
 5403
 5404                // If snippet state is not at the last tabstop, push it back on the stack
 5405                if snippet.active_index + 1 < snippet.ranges.len() {
 5406                    self.snippet_stack.push(snippet);
 5407                }
 5408                return true;
 5409            }
 5410        }
 5411
 5412        false
 5413    }
 5414
 5415    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5416        self.transact(cx, |this, cx| {
 5417            this.select_all(&SelectAll, cx);
 5418            this.insert("", cx);
 5419        });
 5420    }
 5421
 5422    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5423        self.transact(cx, |this, cx| {
 5424            this.select_autoclose_pair(cx);
 5425            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5426            if !this.linked_edit_ranges.is_empty() {
 5427                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5428                let snapshot = this.buffer.read(cx).snapshot(cx);
 5429
 5430                for selection in selections.iter() {
 5431                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5432                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5433                    if selection_start.buffer_id != selection_end.buffer_id {
 5434                        continue;
 5435                    }
 5436                    if let Some(ranges) =
 5437                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5438                    {
 5439                        for (buffer, entries) in ranges {
 5440                            linked_ranges.entry(buffer).or_default().extend(entries);
 5441                        }
 5442                    }
 5443                }
 5444            }
 5445
 5446            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5447            if !this.selections.line_mode {
 5448                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5449                for selection in &mut selections {
 5450                    if selection.is_empty() {
 5451                        let old_head = selection.head();
 5452                        let mut new_head =
 5453                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5454                                .to_point(&display_map);
 5455                        if let Some((buffer, line_buffer_range)) = display_map
 5456                            .buffer_snapshot
 5457                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5458                        {
 5459                            let indent_size =
 5460                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5461                            let indent_len = match indent_size.kind {
 5462                                IndentKind::Space => {
 5463                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5464                                }
 5465                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5466                            };
 5467                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5468                                let indent_len = indent_len.get();
 5469                                new_head = cmp::min(
 5470                                    new_head,
 5471                                    MultiBufferPoint::new(
 5472                                        old_head.row,
 5473                                        ((old_head.column - 1) / indent_len) * indent_len,
 5474                                    ),
 5475                                );
 5476                            }
 5477                        }
 5478
 5479                        selection.set_head(new_head, SelectionGoal::None);
 5480                    }
 5481                }
 5482            }
 5483
 5484            this.signature_help_state.set_backspace_pressed(true);
 5485            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5486            this.insert("", cx);
 5487            let empty_str: Arc<str> = Arc::from("");
 5488            for (buffer, edits) in linked_ranges {
 5489                let snapshot = buffer.read(cx).snapshot();
 5490                use text::ToPoint as TP;
 5491
 5492                let edits = edits
 5493                    .into_iter()
 5494                    .map(|range| {
 5495                        let end_point = TP::to_point(&range.end, &snapshot);
 5496                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5497
 5498                        if end_point == start_point {
 5499                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5500                                .saturating_sub(1);
 5501                            start_point =
 5502                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5503                        };
 5504
 5505                        (start_point..end_point, empty_str.clone())
 5506                    })
 5507                    .sorted_by_key(|(range, _)| range.start)
 5508                    .collect::<Vec<_>>();
 5509                buffer.update(cx, |this, cx| {
 5510                    this.edit(edits, None, cx);
 5511                })
 5512            }
 5513            this.refresh_inline_completion(true, false, cx);
 5514            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5515        });
 5516    }
 5517
 5518    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5519        self.transact(cx, |this, cx| {
 5520            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5521                let line_mode = s.line_mode;
 5522                s.move_with(|map, selection| {
 5523                    if selection.is_empty() && !line_mode {
 5524                        let cursor = movement::right(map, selection.head());
 5525                        selection.end = cursor;
 5526                        selection.reversed = true;
 5527                        selection.goal = SelectionGoal::None;
 5528                    }
 5529                })
 5530            });
 5531            this.insert("", cx);
 5532            this.refresh_inline_completion(true, false, cx);
 5533        });
 5534    }
 5535
 5536    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5537        if self.move_to_prev_snippet_tabstop(cx) {
 5538            return;
 5539        }
 5540
 5541        self.outdent(&Outdent, cx);
 5542    }
 5543
 5544    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5545        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5546            return;
 5547        }
 5548
 5549        let mut selections = self.selections.all_adjusted(cx);
 5550        let buffer = self.buffer.read(cx);
 5551        let snapshot = buffer.snapshot(cx);
 5552        let rows_iter = selections.iter().map(|s| s.head().row);
 5553        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5554
 5555        let mut edits = Vec::new();
 5556        let mut prev_edited_row = 0;
 5557        let mut row_delta = 0;
 5558        for selection in &mut selections {
 5559            if selection.start.row != prev_edited_row {
 5560                row_delta = 0;
 5561            }
 5562            prev_edited_row = selection.end.row;
 5563
 5564            // If the selection is non-empty, then increase the indentation of the selected lines.
 5565            if !selection.is_empty() {
 5566                row_delta =
 5567                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5568                continue;
 5569            }
 5570
 5571            // If the selection is empty and the cursor is in the leading whitespace before the
 5572            // suggested indentation, then auto-indent the line.
 5573            let cursor = selection.head();
 5574            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5575            if let Some(suggested_indent) =
 5576                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5577            {
 5578                if cursor.column < suggested_indent.len
 5579                    && cursor.column <= current_indent.len
 5580                    && current_indent.len <= suggested_indent.len
 5581                {
 5582                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5583                    selection.end = selection.start;
 5584                    if row_delta == 0 {
 5585                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5586                            cursor.row,
 5587                            current_indent,
 5588                            suggested_indent,
 5589                        ));
 5590                        row_delta = suggested_indent.len - current_indent.len;
 5591                    }
 5592                    continue;
 5593                }
 5594            }
 5595
 5596            // Otherwise, insert a hard or soft tab.
 5597            let settings = buffer.settings_at(cursor, cx);
 5598            let tab_size = if settings.hard_tabs {
 5599                IndentSize::tab()
 5600            } else {
 5601                let tab_size = settings.tab_size.get();
 5602                let char_column = snapshot
 5603                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5604                    .flat_map(str::chars)
 5605                    .count()
 5606                    + row_delta as usize;
 5607                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5608                IndentSize::spaces(chars_to_next_tab_stop)
 5609            };
 5610            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5611            selection.end = selection.start;
 5612            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5613            row_delta += tab_size.len;
 5614        }
 5615
 5616        self.transact(cx, |this, cx| {
 5617            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5618            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5619            this.refresh_inline_completion(true, false, cx);
 5620        });
 5621    }
 5622
 5623    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5624        if self.read_only(cx) {
 5625            return;
 5626        }
 5627        let mut selections = self.selections.all::<Point>(cx);
 5628        let mut prev_edited_row = 0;
 5629        let mut row_delta = 0;
 5630        let mut edits = Vec::new();
 5631        let buffer = self.buffer.read(cx);
 5632        let snapshot = buffer.snapshot(cx);
 5633        for selection in &mut selections {
 5634            if selection.start.row != prev_edited_row {
 5635                row_delta = 0;
 5636            }
 5637            prev_edited_row = selection.end.row;
 5638
 5639            row_delta =
 5640                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5641        }
 5642
 5643        self.transact(cx, |this, cx| {
 5644            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5645            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5646        });
 5647    }
 5648
 5649    fn indent_selection(
 5650        buffer: &MultiBuffer,
 5651        snapshot: &MultiBufferSnapshot,
 5652        selection: &mut Selection<Point>,
 5653        edits: &mut Vec<(Range<Point>, String)>,
 5654        delta_for_start_row: u32,
 5655        cx: &AppContext,
 5656    ) -> u32 {
 5657        let settings = buffer.settings_at(selection.start, cx);
 5658        let tab_size = settings.tab_size.get();
 5659        let indent_kind = if settings.hard_tabs {
 5660            IndentKind::Tab
 5661        } else {
 5662            IndentKind::Space
 5663        };
 5664        let mut start_row = selection.start.row;
 5665        let mut end_row = selection.end.row + 1;
 5666
 5667        // If a selection ends at the beginning of a line, don't indent
 5668        // that last line.
 5669        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5670            end_row -= 1;
 5671        }
 5672
 5673        // Avoid re-indenting a row that has already been indented by a
 5674        // previous selection, but still update this selection's column
 5675        // to reflect that indentation.
 5676        if delta_for_start_row > 0 {
 5677            start_row += 1;
 5678            selection.start.column += delta_for_start_row;
 5679            if selection.end.row == selection.start.row {
 5680                selection.end.column += delta_for_start_row;
 5681            }
 5682        }
 5683
 5684        let mut delta_for_end_row = 0;
 5685        let has_multiple_rows = start_row + 1 != end_row;
 5686        for row in start_row..end_row {
 5687            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5688            let indent_delta = match (current_indent.kind, indent_kind) {
 5689                (IndentKind::Space, IndentKind::Space) => {
 5690                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5691                    IndentSize::spaces(columns_to_next_tab_stop)
 5692                }
 5693                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5694                (_, IndentKind::Tab) => IndentSize::tab(),
 5695            };
 5696
 5697            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5698                0
 5699            } else {
 5700                selection.start.column
 5701            };
 5702            let row_start = Point::new(row, start);
 5703            edits.push((
 5704                row_start..row_start,
 5705                indent_delta.chars().collect::<String>(),
 5706            ));
 5707
 5708            // Update this selection's endpoints to reflect the indentation.
 5709            if row == selection.start.row {
 5710                selection.start.column += indent_delta.len;
 5711            }
 5712            if row == selection.end.row {
 5713                selection.end.column += indent_delta.len;
 5714                delta_for_end_row = indent_delta.len;
 5715            }
 5716        }
 5717
 5718        if selection.start.row == selection.end.row {
 5719            delta_for_start_row + delta_for_end_row
 5720        } else {
 5721            delta_for_end_row
 5722        }
 5723    }
 5724
 5725    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5726        if self.read_only(cx) {
 5727            return;
 5728        }
 5729        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5730        let selections = self.selections.all::<Point>(cx);
 5731        let mut deletion_ranges = Vec::new();
 5732        let mut last_outdent = None;
 5733        {
 5734            let buffer = self.buffer.read(cx);
 5735            let snapshot = buffer.snapshot(cx);
 5736            for selection in &selections {
 5737                let settings = buffer.settings_at(selection.start, cx);
 5738                let tab_size = settings.tab_size.get();
 5739                let mut rows = selection.spanned_rows(false, &display_map);
 5740
 5741                // Avoid re-outdenting a row that has already been outdented by a
 5742                // previous selection.
 5743                if let Some(last_row) = last_outdent {
 5744                    if last_row == rows.start {
 5745                        rows.start = rows.start.next_row();
 5746                    }
 5747                }
 5748                let has_multiple_rows = rows.len() > 1;
 5749                for row in rows.iter_rows() {
 5750                    let indent_size = snapshot.indent_size_for_line(row);
 5751                    if indent_size.len > 0 {
 5752                        let deletion_len = match indent_size.kind {
 5753                            IndentKind::Space => {
 5754                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5755                                if columns_to_prev_tab_stop == 0 {
 5756                                    tab_size
 5757                                } else {
 5758                                    columns_to_prev_tab_stop
 5759                                }
 5760                            }
 5761                            IndentKind::Tab => 1,
 5762                        };
 5763                        let start = if has_multiple_rows
 5764                            || deletion_len > selection.start.column
 5765                            || indent_size.len < selection.start.column
 5766                        {
 5767                            0
 5768                        } else {
 5769                            selection.start.column - deletion_len
 5770                        };
 5771                        deletion_ranges.push(
 5772                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5773                        );
 5774                        last_outdent = Some(row);
 5775                    }
 5776                }
 5777            }
 5778        }
 5779
 5780        self.transact(cx, |this, cx| {
 5781            this.buffer.update(cx, |buffer, cx| {
 5782                let empty_str: Arc<str> = Arc::default();
 5783                buffer.edit(
 5784                    deletion_ranges
 5785                        .into_iter()
 5786                        .map(|range| (range, empty_str.clone())),
 5787                    None,
 5788                    cx,
 5789                );
 5790            });
 5791            let selections = this.selections.all::<usize>(cx);
 5792            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5793        });
 5794    }
 5795
 5796    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5797        if self.read_only(cx) {
 5798            return;
 5799        }
 5800        let selections = self
 5801            .selections
 5802            .all::<usize>(cx)
 5803            .into_iter()
 5804            .map(|s| s.range());
 5805
 5806        self.transact(cx, |this, cx| {
 5807            this.buffer.update(cx, |buffer, cx| {
 5808                buffer.autoindent_ranges(selections, cx);
 5809            });
 5810            let selections = this.selections.all::<usize>(cx);
 5811            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5812        });
 5813    }
 5814
 5815    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5816        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5817        let selections = self.selections.all::<Point>(cx);
 5818
 5819        let mut new_cursors = Vec::new();
 5820        let mut edit_ranges = Vec::new();
 5821        let mut selections = selections.iter().peekable();
 5822        while let Some(selection) = selections.next() {
 5823            let mut rows = selection.spanned_rows(false, &display_map);
 5824            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5825
 5826            // Accumulate contiguous regions of rows that we want to delete.
 5827            while let Some(next_selection) = selections.peek() {
 5828                let next_rows = next_selection.spanned_rows(false, &display_map);
 5829                if next_rows.start <= rows.end {
 5830                    rows.end = next_rows.end;
 5831                    selections.next().unwrap();
 5832                } else {
 5833                    break;
 5834                }
 5835            }
 5836
 5837            let buffer = &display_map.buffer_snapshot;
 5838            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5839            let edit_end;
 5840            let cursor_buffer_row;
 5841            if buffer.max_point().row >= rows.end.0 {
 5842                // If there's a line after the range, delete the \n from the end of the row range
 5843                // and position the cursor on the next line.
 5844                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5845                cursor_buffer_row = rows.end;
 5846            } else {
 5847                // If there isn't a line after the range, delete the \n from the line before the
 5848                // start of the row range and position the cursor there.
 5849                edit_start = edit_start.saturating_sub(1);
 5850                edit_end = buffer.len();
 5851                cursor_buffer_row = rows.start.previous_row();
 5852            }
 5853
 5854            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5855            *cursor.column_mut() =
 5856                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5857
 5858            new_cursors.push((
 5859                selection.id,
 5860                buffer.anchor_after(cursor.to_point(&display_map)),
 5861            ));
 5862            edit_ranges.push(edit_start..edit_end);
 5863        }
 5864
 5865        self.transact(cx, |this, cx| {
 5866            let buffer = this.buffer.update(cx, |buffer, cx| {
 5867                let empty_str: Arc<str> = Arc::default();
 5868                buffer.edit(
 5869                    edit_ranges
 5870                        .into_iter()
 5871                        .map(|range| (range, empty_str.clone())),
 5872                    None,
 5873                    cx,
 5874                );
 5875                buffer.snapshot(cx)
 5876            });
 5877            let new_selections = new_cursors
 5878                .into_iter()
 5879                .map(|(id, cursor)| {
 5880                    let cursor = cursor.to_point(&buffer);
 5881                    Selection {
 5882                        id,
 5883                        start: cursor,
 5884                        end: cursor,
 5885                        reversed: false,
 5886                        goal: SelectionGoal::None,
 5887                    }
 5888                })
 5889                .collect();
 5890
 5891            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5892                s.select(new_selections);
 5893            });
 5894        });
 5895    }
 5896
 5897    pub fn join_lines_impl(&mut self, insert_whitespace: bool, cx: &mut ViewContext<Self>) {
 5898        if self.read_only(cx) {
 5899            return;
 5900        }
 5901        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5902        for selection in self.selections.all::<Point>(cx) {
 5903            let start = MultiBufferRow(selection.start.row);
 5904            // Treat single line selections as if they include the next line. Otherwise this action
 5905            // would do nothing for single line selections individual cursors.
 5906            let end = if selection.start.row == selection.end.row {
 5907                MultiBufferRow(selection.start.row + 1)
 5908            } else {
 5909                MultiBufferRow(selection.end.row)
 5910            };
 5911
 5912            if let Some(last_row_range) = row_ranges.last_mut() {
 5913                if start <= last_row_range.end {
 5914                    last_row_range.end = end;
 5915                    continue;
 5916                }
 5917            }
 5918            row_ranges.push(start..end);
 5919        }
 5920
 5921        let snapshot = self.buffer.read(cx).snapshot(cx);
 5922        let mut cursor_positions = Vec::new();
 5923        for row_range in &row_ranges {
 5924            let anchor = snapshot.anchor_before(Point::new(
 5925                row_range.end.previous_row().0,
 5926                snapshot.line_len(row_range.end.previous_row()),
 5927            ));
 5928            cursor_positions.push(anchor..anchor);
 5929        }
 5930
 5931        self.transact(cx, |this, cx| {
 5932            for row_range in row_ranges.into_iter().rev() {
 5933                for row in row_range.iter_rows().rev() {
 5934                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5935                    let next_line_row = row.next_row();
 5936                    let indent = snapshot.indent_size_for_line(next_line_row);
 5937                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5938
 5939                    let replace =
 5940                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 5941                            " "
 5942                        } else {
 5943                            ""
 5944                        };
 5945
 5946                    this.buffer.update(cx, |buffer, cx| {
 5947                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5948                    });
 5949                }
 5950            }
 5951
 5952            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5953                s.select_anchor_ranges(cursor_positions)
 5954            });
 5955        });
 5956    }
 5957
 5958    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5959        self.join_lines_impl(true, cx);
 5960    }
 5961
 5962    pub fn sort_lines_case_sensitive(
 5963        &mut self,
 5964        _: &SortLinesCaseSensitive,
 5965        cx: &mut ViewContext<Self>,
 5966    ) {
 5967        self.manipulate_lines(cx, |lines| lines.sort())
 5968    }
 5969
 5970    pub fn sort_lines_case_insensitive(
 5971        &mut self,
 5972        _: &SortLinesCaseInsensitive,
 5973        cx: &mut ViewContext<Self>,
 5974    ) {
 5975        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5976    }
 5977
 5978    pub fn unique_lines_case_insensitive(
 5979        &mut self,
 5980        _: &UniqueLinesCaseInsensitive,
 5981        cx: &mut ViewContext<Self>,
 5982    ) {
 5983        self.manipulate_lines(cx, |lines| {
 5984            let mut seen = HashSet::default();
 5985            lines.retain(|line| seen.insert(line.to_lowercase()));
 5986        })
 5987    }
 5988
 5989    pub fn unique_lines_case_sensitive(
 5990        &mut self,
 5991        _: &UniqueLinesCaseSensitive,
 5992        cx: &mut ViewContext<Self>,
 5993    ) {
 5994        self.manipulate_lines(cx, |lines| {
 5995            let mut seen = HashSet::default();
 5996            lines.retain(|line| seen.insert(*line));
 5997        })
 5998    }
 5999
 6000    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6001        let mut revert_changes = HashMap::default();
 6002        let snapshot = self.snapshot(cx);
 6003        for hunk in hunks_for_ranges(
 6004            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 6005            &snapshot,
 6006        ) {
 6007            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6008        }
 6009        if !revert_changes.is_empty() {
 6010            self.transact(cx, |editor, cx| {
 6011                editor.revert(revert_changes, cx);
 6012            });
 6013        }
 6014    }
 6015
 6016    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 6017        let Some(project) = self.project.clone() else {
 6018            return;
 6019        };
 6020        self.reload(project, cx).detach_and_notify_err(cx);
 6021    }
 6022
 6023    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6024        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 6025        if !revert_changes.is_empty() {
 6026            self.transact(cx, |editor, cx| {
 6027                editor.revert(revert_changes, cx);
 6028            });
 6029        }
 6030    }
 6031
 6032    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 6033        let snapshot = self.buffer.read(cx).read(cx);
 6034        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 6035            drop(snapshot);
 6036            let mut revert_changes = HashMap::default();
 6037            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6038            if !revert_changes.is_empty() {
 6039                self.revert(revert_changes, cx)
 6040            }
 6041        }
 6042    }
 6043
 6044    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6045        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6046            let project_path = buffer.read(cx).project_path(cx)?;
 6047            let project = self.project.as_ref()?.read(cx);
 6048            let entry = project.entry_for_path(&project_path, cx)?;
 6049            let parent = match &entry.canonical_path {
 6050                Some(canonical_path) => canonical_path.to_path_buf(),
 6051                None => project.absolute_path(&project_path, cx)?,
 6052            }
 6053            .parent()?
 6054            .to_path_buf();
 6055            Some(parent)
 6056        }) {
 6057            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6058        }
 6059    }
 6060
 6061    fn gather_revert_changes(
 6062        &mut self,
 6063        selections: &[Selection<Point>],
 6064        cx: &mut ViewContext<Editor>,
 6065    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6066        let mut revert_changes = HashMap::default();
 6067        let snapshot = self.snapshot(cx);
 6068        for hunk in hunks_for_selections(&snapshot, selections) {
 6069            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6070        }
 6071        revert_changes
 6072    }
 6073
 6074    pub fn prepare_revert_change(
 6075        &mut self,
 6076        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6077        hunk: &MultiBufferDiffHunk,
 6078        cx: &AppContext,
 6079    ) -> Option<()> {
 6080        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6081        let buffer = buffer.read(cx);
 6082        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6083        let original_text = change_set
 6084            .read(cx)
 6085            .base_text
 6086            .as_ref()?
 6087            .read(cx)
 6088            .as_rope()
 6089            .slice(hunk.diff_base_byte_range.clone());
 6090        let buffer_snapshot = buffer.snapshot();
 6091        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6092        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6093            probe
 6094                .0
 6095                .start
 6096                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6097                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6098        }) {
 6099            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6100            Some(())
 6101        } else {
 6102            None
 6103        }
 6104    }
 6105
 6106    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6107        self.manipulate_lines(cx, |lines| lines.reverse())
 6108    }
 6109
 6110    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6111        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6112    }
 6113
 6114    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6115    where
 6116        Fn: FnMut(&mut Vec<&str>),
 6117    {
 6118        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6119        let buffer = self.buffer.read(cx).snapshot(cx);
 6120
 6121        let mut edits = Vec::new();
 6122
 6123        let selections = self.selections.all::<Point>(cx);
 6124        let mut selections = selections.iter().peekable();
 6125        let mut contiguous_row_selections = Vec::new();
 6126        let mut new_selections = Vec::new();
 6127        let mut added_lines = 0;
 6128        let mut removed_lines = 0;
 6129
 6130        while let Some(selection) = selections.next() {
 6131            let (start_row, end_row) = consume_contiguous_rows(
 6132                &mut contiguous_row_selections,
 6133                selection,
 6134                &display_map,
 6135                &mut selections,
 6136            );
 6137
 6138            let start_point = Point::new(start_row.0, 0);
 6139            let end_point = Point::new(
 6140                end_row.previous_row().0,
 6141                buffer.line_len(end_row.previous_row()),
 6142            );
 6143            let text = buffer
 6144                .text_for_range(start_point..end_point)
 6145                .collect::<String>();
 6146
 6147            let mut lines = text.split('\n').collect_vec();
 6148
 6149            let lines_before = lines.len();
 6150            callback(&mut lines);
 6151            let lines_after = lines.len();
 6152
 6153            edits.push((start_point..end_point, lines.join("\n")));
 6154
 6155            // Selections must change based on added and removed line count
 6156            let start_row =
 6157                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6158            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6159            new_selections.push(Selection {
 6160                id: selection.id,
 6161                start: start_row,
 6162                end: end_row,
 6163                goal: SelectionGoal::None,
 6164                reversed: selection.reversed,
 6165            });
 6166
 6167            if lines_after > lines_before {
 6168                added_lines += lines_after - lines_before;
 6169            } else if lines_before > lines_after {
 6170                removed_lines += lines_before - lines_after;
 6171            }
 6172        }
 6173
 6174        self.transact(cx, |this, cx| {
 6175            let buffer = this.buffer.update(cx, |buffer, cx| {
 6176                buffer.edit(edits, None, cx);
 6177                buffer.snapshot(cx)
 6178            });
 6179
 6180            // Recalculate offsets on newly edited buffer
 6181            let new_selections = new_selections
 6182                .iter()
 6183                .map(|s| {
 6184                    let start_point = Point::new(s.start.0, 0);
 6185                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6186                    Selection {
 6187                        id: s.id,
 6188                        start: buffer.point_to_offset(start_point),
 6189                        end: buffer.point_to_offset(end_point),
 6190                        goal: s.goal,
 6191                        reversed: s.reversed,
 6192                    }
 6193                })
 6194                .collect();
 6195
 6196            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6197                s.select(new_selections);
 6198            });
 6199
 6200            this.request_autoscroll(Autoscroll::fit(), cx);
 6201        });
 6202    }
 6203
 6204    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6205        self.manipulate_text(cx, |text| text.to_uppercase())
 6206    }
 6207
 6208    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6209        self.manipulate_text(cx, |text| text.to_lowercase())
 6210    }
 6211
 6212    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6213        self.manipulate_text(cx, |text| {
 6214            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6215            // https://github.com/rutrum/convert-case/issues/16
 6216            text.split('\n')
 6217                .map(|line| line.to_case(Case::Title))
 6218                .join("\n")
 6219        })
 6220    }
 6221
 6222    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6223        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6224    }
 6225
 6226    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6227        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6228    }
 6229
 6230    pub fn convert_to_upper_camel_case(
 6231        &mut self,
 6232        _: &ConvertToUpperCamelCase,
 6233        cx: &mut ViewContext<Self>,
 6234    ) {
 6235        self.manipulate_text(cx, |text| {
 6236            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6237            // https://github.com/rutrum/convert-case/issues/16
 6238            text.split('\n')
 6239                .map(|line| line.to_case(Case::UpperCamel))
 6240                .join("\n")
 6241        })
 6242    }
 6243
 6244    pub fn convert_to_lower_camel_case(
 6245        &mut self,
 6246        _: &ConvertToLowerCamelCase,
 6247        cx: &mut ViewContext<Self>,
 6248    ) {
 6249        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6250    }
 6251
 6252    pub fn convert_to_opposite_case(
 6253        &mut self,
 6254        _: &ConvertToOppositeCase,
 6255        cx: &mut ViewContext<Self>,
 6256    ) {
 6257        self.manipulate_text(cx, |text| {
 6258            text.chars()
 6259                .fold(String::with_capacity(text.len()), |mut t, c| {
 6260                    if c.is_uppercase() {
 6261                        t.extend(c.to_lowercase());
 6262                    } else {
 6263                        t.extend(c.to_uppercase());
 6264                    }
 6265                    t
 6266                })
 6267        })
 6268    }
 6269
 6270    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6271    where
 6272        Fn: FnMut(&str) -> String,
 6273    {
 6274        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6275        let buffer = self.buffer.read(cx).snapshot(cx);
 6276
 6277        let mut new_selections = Vec::new();
 6278        let mut edits = Vec::new();
 6279        let mut selection_adjustment = 0i32;
 6280
 6281        for selection in self.selections.all::<usize>(cx) {
 6282            let selection_is_empty = selection.is_empty();
 6283
 6284            let (start, end) = if selection_is_empty {
 6285                let word_range = movement::surrounding_word(
 6286                    &display_map,
 6287                    selection.start.to_display_point(&display_map),
 6288                );
 6289                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6290                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6291                (start, end)
 6292            } else {
 6293                (selection.start, selection.end)
 6294            };
 6295
 6296            let text = buffer.text_for_range(start..end).collect::<String>();
 6297            let old_length = text.len() as i32;
 6298            let text = callback(&text);
 6299
 6300            new_selections.push(Selection {
 6301                start: (start as i32 - selection_adjustment) as usize,
 6302                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6303                goal: SelectionGoal::None,
 6304                ..selection
 6305            });
 6306
 6307            selection_adjustment += old_length - text.len() as i32;
 6308
 6309            edits.push((start..end, text));
 6310        }
 6311
 6312        self.transact(cx, |this, cx| {
 6313            this.buffer.update(cx, |buffer, cx| {
 6314                buffer.edit(edits, None, cx);
 6315            });
 6316
 6317            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6318                s.select(new_selections);
 6319            });
 6320
 6321            this.request_autoscroll(Autoscroll::fit(), cx);
 6322        });
 6323    }
 6324
 6325    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6326        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6327        let buffer = &display_map.buffer_snapshot;
 6328        let selections = self.selections.all::<Point>(cx);
 6329
 6330        let mut edits = Vec::new();
 6331        let mut selections_iter = selections.iter().peekable();
 6332        while let Some(selection) = selections_iter.next() {
 6333            let mut rows = selection.spanned_rows(false, &display_map);
 6334            // duplicate line-wise
 6335            if whole_lines || selection.start == selection.end {
 6336                // Avoid duplicating the same lines twice.
 6337                while let Some(next_selection) = selections_iter.peek() {
 6338                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6339                    if next_rows.start < rows.end {
 6340                        rows.end = next_rows.end;
 6341                        selections_iter.next().unwrap();
 6342                    } else {
 6343                        break;
 6344                    }
 6345                }
 6346
 6347                // Copy the text from the selected row region and splice it either at the start
 6348                // or end of the region.
 6349                let start = Point::new(rows.start.0, 0);
 6350                let end = Point::new(
 6351                    rows.end.previous_row().0,
 6352                    buffer.line_len(rows.end.previous_row()),
 6353                );
 6354                let text = buffer
 6355                    .text_for_range(start..end)
 6356                    .chain(Some("\n"))
 6357                    .collect::<String>();
 6358                let insert_location = if upwards {
 6359                    Point::new(rows.end.0, 0)
 6360                } else {
 6361                    start
 6362                };
 6363                edits.push((insert_location..insert_location, text));
 6364            } else {
 6365                // duplicate character-wise
 6366                let start = selection.start;
 6367                let end = selection.end;
 6368                let text = buffer.text_for_range(start..end).collect::<String>();
 6369                edits.push((selection.end..selection.end, text));
 6370            }
 6371        }
 6372
 6373        self.transact(cx, |this, cx| {
 6374            this.buffer.update(cx, |buffer, cx| {
 6375                buffer.edit(edits, None, cx);
 6376            });
 6377
 6378            this.request_autoscroll(Autoscroll::fit(), cx);
 6379        });
 6380    }
 6381
 6382    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6383        self.duplicate(true, true, cx);
 6384    }
 6385
 6386    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6387        self.duplicate(false, true, cx);
 6388    }
 6389
 6390    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6391        self.duplicate(false, false, cx);
 6392    }
 6393
 6394    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6395        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6396        let buffer = self.buffer.read(cx).snapshot(cx);
 6397
 6398        let mut edits = Vec::new();
 6399        let mut unfold_ranges = Vec::new();
 6400        let mut refold_creases = Vec::new();
 6401
 6402        let selections = self.selections.all::<Point>(cx);
 6403        let mut selections = selections.iter().peekable();
 6404        let mut contiguous_row_selections = Vec::new();
 6405        let mut new_selections = Vec::new();
 6406
 6407        while let Some(selection) = selections.next() {
 6408            // Find all the selections that span a contiguous row range
 6409            let (start_row, end_row) = consume_contiguous_rows(
 6410                &mut contiguous_row_selections,
 6411                selection,
 6412                &display_map,
 6413                &mut selections,
 6414            );
 6415
 6416            // Move the text spanned by the row range to be before the line preceding the row range
 6417            if start_row.0 > 0 {
 6418                let range_to_move = Point::new(
 6419                    start_row.previous_row().0,
 6420                    buffer.line_len(start_row.previous_row()),
 6421                )
 6422                    ..Point::new(
 6423                        end_row.previous_row().0,
 6424                        buffer.line_len(end_row.previous_row()),
 6425                    );
 6426                let insertion_point = display_map
 6427                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6428                    .0;
 6429
 6430                // Don't move lines across excerpts
 6431                if buffer
 6432                    .excerpt_boundaries_in_range((
 6433                        Bound::Excluded(insertion_point),
 6434                        Bound::Included(range_to_move.end),
 6435                    ))
 6436                    .next()
 6437                    .is_none()
 6438                {
 6439                    let text = buffer
 6440                        .text_for_range(range_to_move.clone())
 6441                        .flat_map(|s| s.chars())
 6442                        .skip(1)
 6443                        .chain(['\n'])
 6444                        .collect::<String>();
 6445
 6446                    edits.push((
 6447                        buffer.anchor_after(range_to_move.start)
 6448                            ..buffer.anchor_before(range_to_move.end),
 6449                        String::new(),
 6450                    ));
 6451                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6452                    edits.push((insertion_anchor..insertion_anchor, text));
 6453
 6454                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6455
 6456                    // Move selections up
 6457                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6458                        |mut selection| {
 6459                            selection.start.row -= row_delta;
 6460                            selection.end.row -= row_delta;
 6461                            selection
 6462                        },
 6463                    ));
 6464
 6465                    // Move folds up
 6466                    unfold_ranges.push(range_to_move.clone());
 6467                    for fold in display_map.folds_in_range(
 6468                        buffer.anchor_before(range_to_move.start)
 6469                            ..buffer.anchor_after(range_to_move.end),
 6470                    ) {
 6471                        let mut start = fold.range.start.to_point(&buffer);
 6472                        let mut end = fold.range.end.to_point(&buffer);
 6473                        start.row -= row_delta;
 6474                        end.row -= row_delta;
 6475                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6476                    }
 6477                }
 6478            }
 6479
 6480            // If we didn't move line(s), preserve the existing selections
 6481            new_selections.append(&mut contiguous_row_selections);
 6482        }
 6483
 6484        self.transact(cx, |this, cx| {
 6485            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6486            this.buffer.update(cx, |buffer, cx| {
 6487                for (range, text) in edits {
 6488                    buffer.edit([(range, text)], None, cx);
 6489                }
 6490            });
 6491            this.fold_creases(refold_creases, true, cx);
 6492            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6493                s.select(new_selections);
 6494            })
 6495        });
 6496    }
 6497
 6498    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6499        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6500        let buffer = self.buffer.read(cx).snapshot(cx);
 6501
 6502        let mut edits = Vec::new();
 6503        let mut unfold_ranges = Vec::new();
 6504        let mut refold_creases = Vec::new();
 6505
 6506        let selections = self.selections.all::<Point>(cx);
 6507        let mut selections = selections.iter().peekable();
 6508        let mut contiguous_row_selections = Vec::new();
 6509        let mut new_selections = Vec::new();
 6510
 6511        while let Some(selection) = selections.next() {
 6512            // Find all the selections that span a contiguous row range
 6513            let (start_row, end_row) = consume_contiguous_rows(
 6514                &mut contiguous_row_selections,
 6515                selection,
 6516                &display_map,
 6517                &mut selections,
 6518            );
 6519
 6520            // Move the text spanned by the row range to be after the last line of the row range
 6521            if end_row.0 <= buffer.max_point().row {
 6522                let range_to_move =
 6523                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6524                let insertion_point = display_map
 6525                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6526                    .0;
 6527
 6528                // Don't move lines across excerpt boundaries
 6529                if buffer
 6530                    .excerpt_boundaries_in_range((
 6531                        Bound::Excluded(range_to_move.start),
 6532                        Bound::Included(insertion_point),
 6533                    ))
 6534                    .next()
 6535                    .is_none()
 6536                {
 6537                    let mut text = String::from("\n");
 6538                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6539                    text.pop(); // Drop trailing newline
 6540                    edits.push((
 6541                        buffer.anchor_after(range_to_move.start)
 6542                            ..buffer.anchor_before(range_to_move.end),
 6543                        String::new(),
 6544                    ));
 6545                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6546                    edits.push((insertion_anchor..insertion_anchor, text));
 6547
 6548                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6549
 6550                    // Move selections down
 6551                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6552                        |mut selection| {
 6553                            selection.start.row += row_delta;
 6554                            selection.end.row += row_delta;
 6555                            selection
 6556                        },
 6557                    ));
 6558
 6559                    // Move folds down
 6560                    unfold_ranges.push(range_to_move.clone());
 6561                    for fold in display_map.folds_in_range(
 6562                        buffer.anchor_before(range_to_move.start)
 6563                            ..buffer.anchor_after(range_to_move.end),
 6564                    ) {
 6565                        let mut start = fold.range.start.to_point(&buffer);
 6566                        let mut end = fold.range.end.to_point(&buffer);
 6567                        start.row += row_delta;
 6568                        end.row += row_delta;
 6569                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6570                    }
 6571                }
 6572            }
 6573
 6574            // If we didn't move line(s), preserve the existing selections
 6575            new_selections.append(&mut contiguous_row_selections);
 6576        }
 6577
 6578        self.transact(cx, |this, cx| {
 6579            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6580            this.buffer.update(cx, |buffer, cx| {
 6581                for (range, text) in edits {
 6582                    buffer.edit([(range, text)], None, cx);
 6583                }
 6584            });
 6585            this.fold_creases(refold_creases, true, cx);
 6586            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6587        });
 6588    }
 6589
 6590    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6591        let text_layout_details = &self.text_layout_details(cx);
 6592        self.transact(cx, |this, cx| {
 6593            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6594                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6595                let line_mode = s.line_mode;
 6596                s.move_with(|display_map, selection| {
 6597                    if !selection.is_empty() || line_mode {
 6598                        return;
 6599                    }
 6600
 6601                    let mut head = selection.head();
 6602                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6603                    if head.column() == display_map.line_len(head.row()) {
 6604                        transpose_offset = display_map
 6605                            .buffer_snapshot
 6606                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6607                    }
 6608
 6609                    if transpose_offset == 0 {
 6610                        return;
 6611                    }
 6612
 6613                    *head.column_mut() += 1;
 6614                    head = display_map.clip_point(head, Bias::Right);
 6615                    let goal = SelectionGoal::HorizontalPosition(
 6616                        display_map
 6617                            .x_for_display_point(head, text_layout_details)
 6618                            .into(),
 6619                    );
 6620                    selection.collapse_to(head, goal);
 6621
 6622                    let transpose_start = display_map
 6623                        .buffer_snapshot
 6624                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6625                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6626                        let transpose_end = display_map
 6627                            .buffer_snapshot
 6628                            .clip_offset(transpose_offset + 1, Bias::Right);
 6629                        if let Some(ch) =
 6630                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6631                        {
 6632                            edits.push((transpose_start..transpose_offset, String::new()));
 6633                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6634                        }
 6635                    }
 6636                });
 6637                edits
 6638            });
 6639            this.buffer
 6640                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6641            let selections = this.selections.all::<usize>(cx);
 6642            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6643                s.select(selections);
 6644            });
 6645        });
 6646    }
 6647
 6648    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6649        self.rewrap_impl(IsVimMode::No, cx)
 6650    }
 6651
 6652    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6653        let buffer = self.buffer.read(cx).snapshot(cx);
 6654        let selections = self.selections.all::<Point>(cx);
 6655        let mut selections = selections.iter().peekable();
 6656
 6657        let mut edits = Vec::new();
 6658        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6659
 6660        while let Some(selection) = selections.next() {
 6661            let mut start_row = selection.start.row;
 6662            let mut end_row = selection.end.row;
 6663
 6664            // Skip selections that overlap with a range that has already been rewrapped.
 6665            let selection_range = start_row..end_row;
 6666            if rewrapped_row_ranges
 6667                .iter()
 6668                .any(|range| range.overlaps(&selection_range))
 6669            {
 6670                continue;
 6671            }
 6672
 6673            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6674
 6675            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6676                match language_scope.language_name().0.as_ref() {
 6677                    "Markdown" | "Plain Text" => {
 6678                        should_rewrap = true;
 6679                    }
 6680                    _ => {}
 6681                }
 6682            }
 6683
 6684            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6685
 6686            // Since not all lines in the selection may be at the same indent
 6687            // level, choose the indent size that is the most common between all
 6688            // of the lines.
 6689            //
 6690            // If there is a tie, we use the deepest indent.
 6691            let (indent_size, indent_end) = {
 6692                let mut indent_size_occurrences = HashMap::default();
 6693                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6694
 6695                for row in start_row..=end_row {
 6696                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6697                    rows_by_indent_size.entry(indent).or_default().push(row);
 6698                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6699                }
 6700
 6701                let indent_size = indent_size_occurrences
 6702                    .into_iter()
 6703                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6704                    .map(|(indent, _)| indent)
 6705                    .unwrap_or_default();
 6706                let row = rows_by_indent_size[&indent_size][0];
 6707                let indent_end = Point::new(row, indent_size.len);
 6708
 6709                (indent_size, indent_end)
 6710            };
 6711
 6712            let mut line_prefix = indent_size.chars().collect::<String>();
 6713
 6714            if let Some(comment_prefix) =
 6715                buffer
 6716                    .language_scope_at(selection.head())
 6717                    .and_then(|language| {
 6718                        language
 6719                            .line_comment_prefixes()
 6720                            .iter()
 6721                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6722                            .cloned()
 6723                    })
 6724            {
 6725                line_prefix.push_str(&comment_prefix);
 6726                should_rewrap = true;
 6727            }
 6728
 6729            if !should_rewrap {
 6730                continue;
 6731            }
 6732
 6733            if selection.is_empty() {
 6734                'expand_upwards: while start_row > 0 {
 6735                    let prev_row = start_row - 1;
 6736                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6737                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6738                    {
 6739                        start_row = prev_row;
 6740                    } else {
 6741                        break 'expand_upwards;
 6742                    }
 6743                }
 6744
 6745                'expand_downwards: while end_row < buffer.max_point().row {
 6746                    let next_row = end_row + 1;
 6747                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6748                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6749                    {
 6750                        end_row = next_row;
 6751                    } else {
 6752                        break 'expand_downwards;
 6753                    }
 6754                }
 6755            }
 6756
 6757            let start = Point::new(start_row, 0);
 6758            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6759            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6760            let Some(lines_without_prefixes) = selection_text
 6761                .lines()
 6762                .map(|line| {
 6763                    line.strip_prefix(&line_prefix)
 6764                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6765                        .ok_or_else(|| {
 6766                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6767                        })
 6768                })
 6769                .collect::<Result<Vec<_>, _>>()
 6770                .log_err()
 6771            else {
 6772                continue;
 6773            };
 6774
 6775            let wrap_column = buffer
 6776                .settings_at(Point::new(start_row, 0), cx)
 6777                .preferred_line_length as usize;
 6778            let wrapped_text = wrap_with_prefix(
 6779                line_prefix,
 6780                lines_without_prefixes.join(" "),
 6781                wrap_column,
 6782                tab_size,
 6783            );
 6784
 6785            // TODO: should always use char-based diff while still supporting cursor behavior that
 6786            // matches vim.
 6787            let diff = match is_vim_mode {
 6788                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6789                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6790            };
 6791            let mut offset = start.to_offset(&buffer);
 6792            let mut moved_since_edit = true;
 6793
 6794            for change in diff.iter_all_changes() {
 6795                let value = change.value();
 6796                match change.tag() {
 6797                    ChangeTag::Equal => {
 6798                        offset += value.len();
 6799                        moved_since_edit = true;
 6800                    }
 6801                    ChangeTag::Delete => {
 6802                        let start = buffer.anchor_after(offset);
 6803                        let end = buffer.anchor_before(offset + value.len());
 6804
 6805                        if moved_since_edit {
 6806                            edits.push((start..end, String::new()));
 6807                        } else {
 6808                            edits.last_mut().unwrap().0.end = end;
 6809                        }
 6810
 6811                        offset += value.len();
 6812                        moved_since_edit = false;
 6813                    }
 6814                    ChangeTag::Insert => {
 6815                        if moved_since_edit {
 6816                            let anchor = buffer.anchor_after(offset);
 6817                            edits.push((anchor..anchor, value.to_string()));
 6818                        } else {
 6819                            edits.last_mut().unwrap().1.push_str(value);
 6820                        }
 6821
 6822                        moved_since_edit = false;
 6823                    }
 6824                }
 6825            }
 6826
 6827            rewrapped_row_ranges.push(start_row..=end_row);
 6828        }
 6829
 6830        self.buffer
 6831            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6832    }
 6833
 6834    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6835        let mut text = String::new();
 6836        let buffer = self.buffer.read(cx).snapshot(cx);
 6837        let mut selections = self.selections.all::<Point>(cx);
 6838        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6839        {
 6840            let max_point = buffer.max_point();
 6841            let mut is_first = true;
 6842            for selection in &mut selections {
 6843                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6844                if is_entire_line {
 6845                    selection.start = Point::new(selection.start.row, 0);
 6846                    if !selection.is_empty() && selection.end.column == 0 {
 6847                        selection.end = cmp::min(max_point, selection.end);
 6848                    } else {
 6849                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6850                    }
 6851                    selection.goal = SelectionGoal::None;
 6852                }
 6853                if is_first {
 6854                    is_first = false;
 6855                } else {
 6856                    text += "\n";
 6857                }
 6858                let mut len = 0;
 6859                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6860                    text.push_str(chunk);
 6861                    len += chunk.len();
 6862                }
 6863                clipboard_selections.push(ClipboardSelection {
 6864                    len,
 6865                    is_entire_line,
 6866                    first_line_indent: buffer
 6867                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6868                        .len,
 6869                });
 6870            }
 6871        }
 6872
 6873        self.transact(cx, |this, cx| {
 6874            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6875                s.select(selections);
 6876            });
 6877            this.insert("", cx);
 6878        });
 6879        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6880    }
 6881
 6882    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6883        let item = self.cut_common(cx);
 6884        cx.write_to_clipboard(item);
 6885    }
 6886
 6887    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6888        self.change_selections(None, cx, |s| {
 6889            s.move_with(|snapshot, sel| {
 6890                if sel.is_empty() {
 6891                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6892                }
 6893            });
 6894        });
 6895        let item = self.cut_common(cx);
 6896        cx.set_global(KillRing(item))
 6897    }
 6898
 6899    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6900        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6901            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6902                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6903            } else {
 6904                return;
 6905            }
 6906        } else {
 6907            return;
 6908        };
 6909        self.do_paste(&text, metadata, false, cx);
 6910    }
 6911
 6912    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6913        let selections = self.selections.all::<Point>(cx);
 6914        let buffer = self.buffer.read(cx).read(cx);
 6915        let mut text = String::new();
 6916
 6917        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6918        {
 6919            let max_point = buffer.max_point();
 6920            let mut is_first = true;
 6921            for selection in selections.iter() {
 6922                let mut start = selection.start;
 6923                let mut end = selection.end;
 6924                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6925                if is_entire_line {
 6926                    start = Point::new(start.row, 0);
 6927                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6928                }
 6929                if is_first {
 6930                    is_first = false;
 6931                } else {
 6932                    text += "\n";
 6933                }
 6934                let mut len = 0;
 6935                for chunk in buffer.text_for_range(start..end) {
 6936                    text.push_str(chunk);
 6937                    len += chunk.len();
 6938                }
 6939                clipboard_selections.push(ClipboardSelection {
 6940                    len,
 6941                    is_entire_line,
 6942                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6943                });
 6944            }
 6945        }
 6946
 6947        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6948            text,
 6949            clipboard_selections,
 6950        ));
 6951    }
 6952
 6953    pub fn do_paste(
 6954        &mut self,
 6955        text: &String,
 6956        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6957        handle_entire_lines: bool,
 6958        cx: &mut ViewContext<Self>,
 6959    ) {
 6960        if self.read_only(cx) {
 6961            return;
 6962        }
 6963
 6964        let clipboard_text = Cow::Borrowed(text);
 6965
 6966        self.transact(cx, |this, cx| {
 6967            if let Some(mut clipboard_selections) = clipboard_selections {
 6968                let old_selections = this.selections.all::<usize>(cx);
 6969                let all_selections_were_entire_line =
 6970                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6971                let first_selection_indent_column =
 6972                    clipboard_selections.first().map(|s| s.first_line_indent);
 6973                if clipboard_selections.len() != old_selections.len() {
 6974                    clipboard_selections.drain(..);
 6975                }
 6976                let cursor_offset = this.selections.last::<usize>(cx).head();
 6977                let mut auto_indent_on_paste = true;
 6978
 6979                this.buffer.update(cx, |buffer, cx| {
 6980                    let snapshot = buffer.read(cx);
 6981                    auto_indent_on_paste =
 6982                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6983
 6984                    let mut start_offset = 0;
 6985                    let mut edits = Vec::new();
 6986                    let mut original_indent_columns = Vec::new();
 6987                    for (ix, selection) in old_selections.iter().enumerate() {
 6988                        let to_insert;
 6989                        let entire_line;
 6990                        let original_indent_column;
 6991                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6992                            let end_offset = start_offset + clipboard_selection.len;
 6993                            to_insert = &clipboard_text[start_offset..end_offset];
 6994                            entire_line = clipboard_selection.is_entire_line;
 6995                            start_offset = end_offset + 1;
 6996                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6997                        } else {
 6998                            to_insert = clipboard_text.as_str();
 6999                            entire_line = all_selections_were_entire_line;
 7000                            original_indent_column = first_selection_indent_column
 7001                        }
 7002
 7003                        // If the corresponding selection was empty when this slice of the
 7004                        // clipboard text was written, then the entire line containing the
 7005                        // selection was copied. If this selection is also currently empty,
 7006                        // then paste the line before the current line of the buffer.
 7007                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7008                            let column = selection.start.to_point(&snapshot).column as usize;
 7009                            let line_start = selection.start - column;
 7010                            line_start..line_start
 7011                        } else {
 7012                            selection.range()
 7013                        };
 7014
 7015                        edits.push((range, to_insert));
 7016                        original_indent_columns.extend(original_indent_column);
 7017                    }
 7018                    drop(snapshot);
 7019
 7020                    buffer.edit(
 7021                        edits,
 7022                        if auto_indent_on_paste {
 7023                            Some(AutoindentMode::Block {
 7024                                original_indent_columns,
 7025                            })
 7026                        } else {
 7027                            None
 7028                        },
 7029                        cx,
 7030                    );
 7031                });
 7032
 7033                let selections = this.selections.all::<usize>(cx);
 7034                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7035            } else {
 7036                this.insert(&clipboard_text, cx);
 7037            }
 7038        });
 7039    }
 7040
 7041    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7042        if let Some(item) = cx.read_from_clipboard() {
 7043            let entries = item.entries();
 7044
 7045            match entries.first() {
 7046                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7047                // of all the pasted entries.
 7048                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7049                    .do_paste(
 7050                        clipboard_string.text(),
 7051                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7052                        true,
 7053                        cx,
 7054                    ),
 7055                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7056            }
 7057        }
 7058    }
 7059
 7060    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7061        if self.read_only(cx) {
 7062            return;
 7063        }
 7064
 7065        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7066            if let Some((selections, _)) =
 7067                self.selection_history.transaction(transaction_id).cloned()
 7068            {
 7069                self.change_selections(None, cx, |s| {
 7070                    s.select_anchors(selections.to_vec());
 7071                });
 7072            }
 7073            self.request_autoscroll(Autoscroll::fit(), cx);
 7074            self.unmark_text(cx);
 7075            self.refresh_inline_completion(true, false, cx);
 7076            cx.emit(EditorEvent::Edited { transaction_id });
 7077            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7078        }
 7079    }
 7080
 7081    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7082        if self.read_only(cx) {
 7083            return;
 7084        }
 7085
 7086        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7087            if let Some((_, Some(selections))) =
 7088                self.selection_history.transaction(transaction_id).cloned()
 7089            {
 7090                self.change_selections(None, cx, |s| {
 7091                    s.select_anchors(selections.to_vec());
 7092                });
 7093            }
 7094            self.request_autoscroll(Autoscroll::fit(), cx);
 7095            self.unmark_text(cx);
 7096            self.refresh_inline_completion(true, false, cx);
 7097            cx.emit(EditorEvent::Edited { transaction_id });
 7098        }
 7099    }
 7100
 7101    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7102        self.buffer
 7103            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7104    }
 7105
 7106    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7107        self.buffer
 7108            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7109    }
 7110
 7111    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7112        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7113            let line_mode = s.line_mode;
 7114            s.move_with(|map, selection| {
 7115                let cursor = if selection.is_empty() && !line_mode {
 7116                    movement::left(map, selection.start)
 7117                } else {
 7118                    selection.start
 7119                };
 7120                selection.collapse_to(cursor, SelectionGoal::None);
 7121            });
 7122        })
 7123    }
 7124
 7125    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7126        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7127            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7128        })
 7129    }
 7130
 7131    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7132        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7133            let line_mode = s.line_mode;
 7134            s.move_with(|map, selection| {
 7135                let cursor = if selection.is_empty() && !line_mode {
 7136                    movement::right(map, selection.end)
 7137                } else {
 7138                    selection.end
 7139                };
 7140                selection.collapse_to(cursor, SelectionGoal::None)
 7141            });
 7142        })
 7143    }
 7144
 7145    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7146        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7147            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7148        })
 7149    }
 7150
 7151    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7152        if self.take_rename(true, cx).is_some() {
 7153            return;
 7154        }
 7155
 7156        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7157            cx.propagate();
 7158            return;
 7159        }
 7160
 7161        let text_layout_details = &self.text_layout_details(cx);
 7162        let selection_count = self.selections.count();
 7163        let first_selection = self.selections.first_anchor();
 7164
 7165        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7166            let line_mode = s.line_mode;
 7167            s.move_with(|map, selection| {
 7168                if !selection.is_empty() && !line_mode {
 7169                    selection.goal = SelectionGoal::None;
 7170                }
 7171                let (cursor, goal) = movement::up(
 7172                    map,
 7173                    selection.start,
 7174                    selection.goal,
 7175                    false,
 7176                    text_layout_details,
 7177                );
 7178                selection.collapse_to(cursor, goal);
 7179            });
 7180        });
 7181
 7182        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7183        {
 7184            cx.propagate();
 7185        }
 7186    }
 7187
 7188    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7189        if self.take_rename(true, cx).is_some() {
 7190            return;
 7191        }
 7192
 7193        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7194            cx.propagate();
 7195            return;
 7196        }
 7197
 7198        let text_layout_details = &self.text_layout_details(cx);
 7199
 7200        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7201            let line_mode = s.line_mode;
 7202            s.move_with(|map, selection| {
 7203                if !selection.is_empty() && !line_mode {
 7204                    selection.goal = SelectionGoal::None;
 7205                }
 7206                let (cursor, goal) = movement::up_by_rows(
 7207                    map,
 7208                    selection.start,
 7209                    action.lines,
 7210                    selection.goal,
 7211                    false,
 7212                    text_layout_details,
 7213                );
 7214                selection.collapse_to(cursor, goal);
 7215            });
 7216        })
 7217    }
 7218
 7219    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7220        if self.take_rename(true, cx).is_some() {
 7221            return;
 7222        }
 7223
 7224        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7225            cx.propagate();
 7226            return;
 7227        }
 7228
 7229        let text_layout_details = &self.text_layout_details(cx);
 7230
 7231        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7232            let line_mode = s.line_mode;
 7233            s.move_with(|map, selection| {
 7234                if !selection.is_empty() && !line_mode {
 7235                    selection.goal = SelectionGoal::None;
 7236                }
 7237                let (cursor, goal) = movement::down_by_rows(
 7238                    map,
 7239                    selection.start,
 7240                    action.lines,
 7241                    selection.goal,
 7242                    false,
 7243                    text_layout_details,
 7244                );
 7245                selection.collapse_to(cursor, goal);
 7246            });
 7247        })
 7248    }
 7249
 7250    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7251        let text_layout_details = &self.text_layout_details(cx);
 7252        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7253            s.move_heads_with(|map, head, goal| {
 7254                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7255            })
 7256        })
 7257    }
 7258
 7259    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7260        let text_layout_details = &self.text_layout_details(cx);
 7261        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7262            s.move_heads_with(|map, head, goal| {
 7263                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7264            })
 7265        })
 7266    }
 7267
 7268    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7269        let Some(row_count) = self.visible_row_count() else {
 7270            return;
 7271        };
 7272
 7273        let text_layout_details = &self.text_layout_details(cx);
 7274
 7275        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7276            s.move_heads_with(|map, head, goal| {
 7277                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7278            })
 7279        })
 7280    }
 7281
 7282    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7283        if self.take_rename(true, cx).is_some() {
 7284            return;
 7285        }
 7286
 7287        if self
 7288            .context_menu
 7289            .borrow_mut()
 7290            .as_mut()
 7291            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7292            .unwrap_or(false)
 7293        {
 7294            return;
 7295        }
 7296
 7297        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7298            cx.propagate();
 7299            return;
 7300        }
 7301
 7302        let Some(row_count) = self.visible_row_count() else {
 7303            return;
 7304        };
 7305
 7306        let autoscroll = if action.center_cursor {
 7307            Autoscroll::center()
 7308        } else {
 7309            Autoscroll::fit()
 7310        };
 7311
 7312        let text_layout_details = &self.text_layout_details(cx);
 7313
 7314        self.change_selections(Some(autoscroll), cx, |s| {
 7315            let line_mode = s.line_mode;
 7316            s.move_with(|map, selection| {
 7317                if !selection.is_empty() && !line_mode {
 7318                    selection.goal = SelectionGoal::None;
 7319                }
 7320                let (cursor, goal) = movement::up_by_rows(
 7321                    map,
 7322                    selection.end,
 7323                    row_count,
 7324                    selection.goal,
 7325                    false,
 7326                    text_layout_details,
 7327                );
 7328                selection.collapse_to(cursor, goal);
 7329            });
 7330        });
 7331    }
 7332
 7333    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7334        let text_layout_details = &self.text_layout_details(cx);
 7335        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7336            s.move_heads_with(|map, head, goal| {
 7337                movement::up(map, head, goal, false, text_layout_details)
 7338            })
 7339        })
 7340    }
 7341
 7342    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7343        self.take_rename(true, cx);
 7344
 7345        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7346            cx.propagate();
 7347            return;
 7348        }
 7349
 7350        let text_layout_details = &self.text_layout_details(cx);
 7351        let selection_count = self.selections.count();
 7352        let first_selection = self.selections.first_anchor();
 7353
 7354        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7355            let line_mode = s.line_mode;
 7356            s.move_with(|map, selection| {
 7357                if !selection.is_empty() && !line_mode {
 7358                    selection.goal = SelectionGoal::None;
 7359                }
 7360                let (cursor, goal) = movement::down(
 7361                    map,
 7362                    selection.end,
 7363                    selection.goal,
 7364                    false,
 7365                    text_layout_details,
 7366                );
 7367                selection.collapse_to(cursor, goal);
 7368            });
 7369        });
 7370
 7371        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7372        {
 7373            cx.propagate();
 7374        }
 7375    }
 7376
 7377    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7378        let Some(row_count) = self.visible_row_count() else {
 7379            return;
 7380        };
 7381
 7382        let text_layout_details = &self.text_layout_details(cx);
 7383
 7384        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7385            s.move_heads_with(|map, head, goal| {
 7386                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7387            })
 7388        })
 7389    }
 7390
 7391    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7392        if self.take_rename(true, cx).is_some() {
 7393            return;
 7394        }
 7395
 7396        if self
 7397            .context_menu
 7398            .borrow_mut()
 7399            .as_mut()
 7400            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7401            .unwrap_or(false)
 7402        {
 7403            return;
 7404        }
 7405
 7406        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7407            cx.propagate();
 7408            return;
 7409        }
 7410
 7411        let Some(row_count) = self.visible_row_count() else {
 7412            return;
 7413        };
 7414
 7415        let autoscroll = if action.center_cursor {
 7416            Autoscroll::center()
 7417        } else {
 7418            Autoscroll::fit()
 7419        };
 7420
 7421        let text_layout_details = &self.text_layout_details(cx);
 7422        self.change_selections(Some(autoscroll), cx, |s| {
 7423            let line_mode = s.line_mode;
 7424            s.move_with(|map, selection| {
 7425                if !selection.is_empty() && !line_mode {
 7426                    selection.goal = SelectionGoal::None;
 7427                }
 7428                let (cursor, goal) = movement::down_by_rows(
 7429                    map,
 7430                    selection.end,
 7431                    row_count,
 7432                    selection.goal,
 7433                    false,
 7434                    text_layout_details,
 7435                );
 7436                selection.collapse_to(cursor, goal);
 7437            });
 7438        });
 7439    }
 7440
 7441    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7442        let text_layout_details = &self.text_layout_details(cx);
 7443        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7444            s.move_heads_with(|map, head, goal| {
 7445                movement::down(map, head, goal, false, text_layout_details)
 7446            })
 7447        });
 7448    }
 7449
 7450    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7451        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7452            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7453        }
 7454    }
 7455
 7456    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7457        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7458            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7459        }
 7460    }
 7461
 7462    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7463        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7464            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7465        }
 7466    }
 7467
 7468    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7469        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7470            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7471        }
 7472    }
 7473
 7474    pub fn move_to_previous_word_start(
 7475        &mut self,
 7476        _: &MoveToPreviousWordStart,
 7477        cx: &mut ViewContext<Self>,
 7478    ) {
 7479        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7480            s.move_cursors_with(|map, head, _| {
 7481                (
 7482                    movement::previous_word_start(map, head),
 7483                    SelectionGoal::None,
 7484                )
 7485            });
 7486        })
 7487    }
 7488
 7489    pub fn move_to_previous_subword_start(
 7490        &mut self,
 7491        _: &MoveToPreviousSubwordStart,
 7492        cx: &mut ViewContext<Self>,
 7493    ) {
 7494        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7495            s.move_cursors_with(|map, head, _| {
 7496                (
 7497                    movement::previous_subword_start(map, head),
 7498                    SelectionGoal::None,
 7499                )
 7500            });
 7501        })
 7502    }
 7503
 7504    pub fn select_to_previous_word_start(
 7505        &mut self,
 7506        _: &SelectToPreviousWordStart,
 7507        cx: &mut ViewContext<Self>,
 7508    ) {
 7509        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7510            s.move_heads_with(|map, head, _| {
 7511                (
 7512                    movement::previous_word_start(map, head),
 7513                    SelectionGoal::None,
 7514                )
 7515            });
 7516        })
 7517    }
 7518
 7519    pub fn select_to_previous_subword_start(
 7520        &mut self,
 7521        _: &SelectToPreviousSubwordStart,
 7522        cx: &mut ViewContext<Self>,
 7523    ) {
 7524        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7525            s.move_heads_with(|map, head, _| {
 7526                (
 7527                    movement::previous_subword_start(map, head),
 7528                    SelectionGoal::None,
 7529                )
 7530            });
 7531        })
 7532    }
 7533
 7534    pub fn delete_to_previous_word_start(
 7535        &mut self,
 7536        action: &DeleteToPreviousWordStart,
 7537        cx: &mut ViewContext<Self>,
 7538    ) {
 7539        self.transact(cx, |this, cx| {
 7540            this.select_autoclose_pair(cx);
 7541            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7542                let line_mode = s.line_mode;
 7543                s.move_with(|map, selection| {
 7544                    if selection.is_empty() && !line_mode {
 7545                        let cursor = if action.ignore_newlines {
 7546                            movement::previous_word_start(map, selection.head())
 7547                        } else {
 7548                            movement::previous_word_start_or_newline(map, selection.head())
 7549                        };
 7550                        selection.set_head(cursor, SelectionGoal::None);
 7551                    }
 7552                });
 7553            });
 7554            this.insert("", cx);
 7555        });
 7556    }
 7557
 7558    pub fn delete_to_previous_subword_start(
 7559        &mut self,
 7560        _: &DeleteToPreviousSubwordStart,
 7561        cx: &mut ViewContext<Self>,
 7562    ) {
 7563        self.transact(cx, |this, cx| {
 7564            this.select_autoclose_pair(cx);
 7565            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7566                let line_mode = s.line_mode;
 7567                s.move_with(|map, selection| {
 7568                    if selection.is_empty() && !line_mode {
 7569                        let cursor = movement::previous_subword_start(map, selection.head());
 7570                        selection.set_head(cursor, SelectionGoal::None);
 7571                    }
 7572                });
 7573            });
 7574            this.insert("", cx);
 7575        });
 7576    }
 7577
 7578    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7579        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7580            s.move_cursors_with(|map, head, _| {
 7581                (movement::next_word_end(map, head), SelectionGoal::None)
 7582            });
 7583        })
 7584    }
 7585
 7586    pub fn move_to_next_subword_end(
 7587        &mut self,
 7588        _: &MoveToNextSubwordEnd,
 7589        cx: &mut ViewContext<Self>,
 7590    ) {
 7591        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7592            s.move_cursors_with(|map, head, _| {
 7593                (movement::next_subword_end(map, head), SelectionGoal::None)
 7594            });
 7595        })
 7596    }
 7597
 7598    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7599        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7600            s.move_heads_with(|map, head, _| {
 7601                (movement::next_word_end(map, head), SelectionGoal::None)
 7602            });
 7603        })
 7604    }
 7605
 7606    pub fn select_to_next_subword_end(
 7607        &mut self,
 7608        _: &SelectToNextSubwordEnd,
 7609        cx: &mut ViewContext<Self>,
 7610    ) {
 7611        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7612            s.move_heads_with(|map, head, _| {
 7613                (movement::next_subword_end(map, head), SelectionGoal::None)
 7614            });
 7615        })
 7616    }
 7617
 7618    pub fn delete_to_next_word_end(
 7619        &mut self,
 7620        action: &DeleteToNextWordEnd,
 7621        cx: &mut ViewContext<Self>,
 7622    ) {
 7623        self.transact(cx, |this, cx| {
 7624            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7625                let line_mode = s.line_mode;
 7626                s.move_with(|map, selection| {
 7627                    if selection.is_empty() && !line_mode {
 7628                        let cursor = if action.ignore_newlines {
 7629                            movement::next_word_end(map, selection.head())
 7630                        } else {
 7631                            movement::next_word_end_or_newline(map, selection.head())
 7632                        };
 7633                        selection.set_head(cursor, SelectionGoal::None);
 7634                    }
 7635                });
 7636            });
 7637            this.insert("", cx);
 7638        });
 7639    }
 7640
 7641    pub fn delete_to_next_subword_end(
 7642        &mut self,
 7643        _: &DeleteToNextSubwordEnd,
 7644        cx: &mut ViewContext<Self>,
 7645    ) {
 7646        self.transact(cx, |this, cx| {
 7647            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7648                s.move_with(|map, selection| {
 7649                    if selection.is_empty() {
 7650                        let cursor = movement::next_subword_end(map, selection.head());
 7651                        selection.set_head(cursor, SelectionGoal::None);
 7652                    }
 7653                });
 7654            });
 7655            this.insert("", cx);
 7656        });
 7657    }
 7658
 7659    pub fn move_to_beginning_of_line(
 7660        &mut self,
 7661        action: &MoveToBeginningOfLine,
 7662        cx: &mut ViewContext<Self>,
 7663    ) {
 7664        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7665            s.move_cursors_with(|map, head, _| {
 7666                (
 7667                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7668                    SelectionGoal::None,
 7669                )
 7670            });
 7671        })
 7672    }
 7673
 7674    pub fn select_to_beginning_of_line(
 7675        &mut self,
 7676        action: &SelectToBeginningOfLine,
 7677        cx: &mut ViewContext<Self>,
 7678    ) {
 7679        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7680            s.move_heads_with(|map, head, _| {
 7681                (
 7682                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7683                    SelectionGoal::None,
 7684                )
 7685            });
 7686        });
 7687    }
 7688
 7689    pub fn delete_to_beginning_of_line(
 7690        &mut self,
 7691        _: &DeleteToBeginningOfLine,
 7692        cx: &mut ViewContext<Self>,
 7693    ) {
 7694        self.transact(cx, |this, cx| {
 7695            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7696                s.move_with(|_, selection| {
 7697                    selection.reversed = true;
 7698                });
 7699            });
 7700
 7701            this.select_to_beginning_of_line(
 7702                &SelectToBeginningOfLine {
 7703                    stop_at_soft_wraps: false,
 7704                },
 7705                cx,
 7706            );
 7707            this.backspace(&Backspace, cx);
 7708        });
 7709    }
 7710
 7711    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7712        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7713            s.move_cursors_with(|map, head, _| {
 7714                (
 7715                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7716                    SelectionGoal::None,
 7717                )
 7718            });
 7719        })
 7720    }
 7721
 7722    pub fn select_to_end_of_line(
 7723        &mut self,
 7724        action: &SelectToEndOfLine,
 7725        cx: &mut ViewContext<Self>,
 7726    ) {
 7727        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7728            s.move_heads_with(|map, head, _| {
 7729                (
 7730                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7731                    SelectionGoal::None,
 7732                )
 7733            });
 7734        })
 7735    }
 7736
 7737    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7738        self.transact(cx, |this, cx| {
 7739            this.select_to_end_of_line(
 7740                &SelectToEndOfLine {
 7741                    stop_at_soft_wraps: false,
 7742                },
 7743                cx,
 7744            );
 7745            this.delete(&Delete, cx);
 7746        });
 7747    }
 7748
 7749    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7750        self.transact(cx, |this, cx| {
 7751            this.select_to_end_of_line(
 7752                &SelectToEndOfLine {
 7753                    stop_at_soft_wraps: false,
 7754                },
 7755                cx,
 7756            );
 7757            this.cut(&Cut, cx);
 7758        });
 7759    }
 7760
 7761    pub fn move_to_start_of_paragraph(
 7762        &mut self,
 7763        _: &MoveToStartOfParagraph,
 7764        cx: &mut ViewContext<Self>,
 7765    ) {
 7766        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7767            cx.propagate();
 7768            return;
 7769        }
 7770
 7771        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7772            s.move_with(|map, selection| {
 7773                selection.collapse_to(
 7774                    movement::start_of_paragraph(map, selection.head(), 1),
 7775                    SelectionGoal::None,
 7776                )
 7777            });
 7778        })
 7779    }
 7780
 7781    pub fn move_to_end_of_paragraph(
 7782        &mut self,
 7783        _: &MoveToEndOfParagraph,
 7784        cx: &mut ViewContext<Self>,
 7785    ) {
 7786        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7787            cx.propagate();
 7788            return;
 7789        }
 7790
 7791        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7792            s.move_with(|map, selection| {
 7793                selection.collapse_to(
 7794                    movement::end_of_paragraph(map, selection.head(), 1),
 7795                    SelectionGoal::None,
 7796                )
 7797            });
 7798        })
 7799    }
 7800
 7801    pub fn select_to_start_of_paragraph(
 7802        &mut self,
 7803        _: &SelectToStartOfParagraph,
 7804        cx: &mut ViewContext<Self>,
 7805    ) {
 7806        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7807            cx.propagate();
 7808            return;
 7809        }
 7810
 7811        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7812            s.move_heads_with(|map, head, _| {
 7813                (
 7814                    movement::start_of_paragraph(map, head, 1),
 7815                    SelectionGoal::None,
 7816                )
 7817            });
 7818        })
 7819    }
 7820
 7821    pub fn select_to_end_of_paragraph(
 7822        &mut self,
 7823        _: &SelectToEndOfParagraph,
 7824        cx: &mut ViewContext<Self>,
 7825    ) {
 7826        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7827            cx.propagate();
 7828            return;
 7829        }
 7830
 7831        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7832            s.move_heads_with(|map, head, _| {
 7833                (
 7834                    movement::end_of_paragraph(map, head, 1),
 7835                    SelectionGoal::None,
 7836                )
 7837            });
 7838        })
 7839    }
 7840
 7841    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7842        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7843            cx.propagate();
 7844            return;
 7845        }
 7846
 7847        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7848            s.select_ranges(vec![0..0]);
 7849        });
 7850    }
 7851
 7852    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7853        let mut selection = self.selections.last::<Point>(cx);
 7854        selection.set_head(Point::zero(), SelectionGoal::None);
 7855
 7856        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7857            s.select(vec![selection]);
 7858        });
 7859    }
 7860
 7861    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7862        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7863            cx.propagate();
 7864            return;
 7865        }
 7866
 7867        let cursor = self.buffer.read(cx).read(cx).len();
 7868        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7869            s.select_ranges(vec![cursor..cursor])
 7870        });
 7871    }
 7872
 7873    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7874        self.nav_history = nav_history;
 7875    }
 7876
 7877    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7878        self.nav_history.as_ref()
 7879    }
 7880
 7881    fn push_to_nav_history(
 7882        &mut self,
 7883        cursor_anchor: Anchor,
 7884        new_position: Option<Point>,
 7885        cx: &mut ViewContext<Self>,
 7886    ) {
 7887        if let Some(nav_history) = self.nav_history.as_mut() {
 7888            let buffer = self.buffer.read(cx).read(cx);
 7889            let cursor_position = cursor_anchor.to_point(&buffer);
 7890            let scroll_state = self.scroll_manager.anchor();
 7891            let scroll_top_row = scroll_state.top_row(&buffer);
 7892            drop(buffer);
 7893
 7894            if let Some(new_position) = new_position {
 7895                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7896                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7897                    return;
 7898                }
 7899            }
 7900
 7901            nav_history.push(
 7902                Some(NavigationData {
 7903                    cursor_anchor,
 7904                    cursor_position,
 7905                    scroll_anchor: scroll_state,
 7906                    scroll_top_row,
 7907                }),
 7908                cx,
 7909            );
 7910        }
 7911    }
 7912
 7913    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7914        let buffer = self.buffer.read(cx).snapshot(cx);
 7915        let mut selection = self.selections.first::<usize>(cx);
 7916        selection.set_head(buffer.len(), SelectionGoal::None);
 7917        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7918            s.select(vec![selection]);
 7919        });
 7920    }
 7921
 7922    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7923        let end = self.buffer.read(cx).read(cx).len();
 7924        self.change_selections(None, cx, |s| {
 7925            s.select_ranges(vec![0..end]);
 7926        });
 7927    }
 7928
 7929    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7930        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7931        let mut selections = self.selections.all::<Point>(cx);
 7932        let max_point = display_map.buffer_snapshot.max_point();
 7933        for selection in &mut selections {
 7934            let rows = selection.spanned_rows(true, &display_map);
 7935            selection.start = Point::new(rows.start.0, 0);
 7936            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7937            selection.reversed = false;
 7938        }
 7939        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7940            s.select(selections);
 7941        });
 7942    }
 7943
 7944    pub fn split_selection_into_lines(
 7945        &mut self,
 7946        _: &SplitSelectionIntoLines,
 7947        cx: &mut ViewContext<Self>,
 7948    ) {
 7949        let mut to_unfold = Vec::new();
 7950        let mut new_selection_ranges = Vec::new();
 7951        {
 7952            let selections = self.selections.all::<Point>(cx);
 7953            let buffer = self.buffer.read(cx).read(cx);
 7954            for selection in selections {
 7955                for row in selection.start.row..selection.end.row {
 7956                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7957                    new_selection_ranges.push(cursor..cursor);
 7958                }
 7959                new_selection_ranges.push(selection.end..selection.end);
 7960                to_unfold.push(selection.start..selection.end);
 7961            }
 7962        }
 7963        self.unfold_ranges(&to_unfold, true, true, cx);
 7964        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7965            s.select_ranges(new_selection_ranges);
 7966        });
 7967    }
 7968
 7969    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7970        self.add_selection(true, cx);
 7971    }
 7972
 7973    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7974        self.add_selection(false, cx);
 7975    }
 7976
 7977    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7978        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7979        let mut selections = self.selections.all::<Point>(cx);
 7980        let text_layout_details = self.text_layout_details(cx);
 7981        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7982            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7983            let range = oldest_selection.display_range(&display_map).sorted();
 7984
 7985            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7986            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7987            let positions = start_x.min(end_x)..start_x.max(end_x);
 7988
 7989            selections.clear();
 7990            let mut stack = Vec::new();
 7991            for row in range.start.row().0..=range.end.row().0 {
 7992                if let Some(selection) = self.selections.build_columnar_selection(
 7993                    &display_map,
 7994                    DisplayRow(row),
 7995                    &positions,
 7996                    oldest_selection.reversed,
 7997                    &text_layout_details,
 7998                ) {
 7999                    stack.push(selection.id);
 8000                    selections.push(selection);
 8001                }
 8002            }
 8003
 8004            if above {
 8005                stack.reverse();
 8006            }
 8007
 8008            AddSelectionsState { above, stack }
 8009        });
 8010
 8011        let last_added_selection = *state.stack.last().unwrap();
 8012        let mut new_selections = Vec::new();
 8013        if above == state.above {
 8014            let end_row = if above {
 8015                DisplayRow(0)
 8016            } else {
 8017                display_map.max_point().row()
 8018            };
 8019
 8020            'outer: for selection in selections {
 8021                if selection.id == last_added_selection {
 8022                    let range = selection.display_range(&display_map).sorted();
 8023                    debug_assert_eq!(range.start.row(), range.end.row());
 8024                    let mut row = range.start.row();
 8025                    let positions =
 8026                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8027                            px(start)..px(end)
 8028                        } else {
 8029                            let start_x =
 8030                                display_map.x_for_display_point(range.start, &text_layout_details);
 8031                            let end_x =
 8032                                display_map.x_for_display_point(range.end, &text_layout_details);
 8033                            start_x.min(end_x)..start_x.max(end_x)
 8034                        };
 8035
 8036                    while row != end_row {
 8037                        if above {
 8038                            row.0 -= 1;
 8039                        } else {
 8040                            row.0 += 1;
 8041                        }
 8042
 8043                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8044                            &display_map,
 8045                            row,
 8046                            &positions,
 8047                            selection.reversed,
 8048                            &text_layout_details,
 8049                        ) {
 8050                            state.stack.push(new_selection.id);
 8051                            if above {
 8052                                new_selections.push(new_selection);
 8053                                new_selections.push(selection);
 8054                            } else {
 8055                                new_selections.push(selection);
 8056                                new_selections.push(new_selection);
 8057                            }
 8058
 8059                            continue 'outer;
 8060                        }
 8061                    }
 8062                }
 8063
 8064                new_selections.push(selection);
 8065            }
 8066        } else {
 8067            new_selections = selections;
 8068            new_selections.retain(|s| s.id != last_added_selection);
 8069            state.stack.pop();
 8070        }
 8071
 8072        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8073            s.select(new_selections);
 8074        });
 8075        if state.stack.len() > 1 {
 8076            self.add_selections_state = Some(state);
 8077        }
 8078    }
 8079
 8080    pub fn select_next_match_internal(
 8081        &mut self,
 8082        display_map: &DisplaySnapshot,
 8083        replace_newest: bool,
 8084        autoscroll: Option<Autoscroll>,
 8085        cx: &mut ViewContext<Self>,
 8086    ) -> Result<()> {
 8087        fn select_next_match_ranges(
 8088            this: &mut Editor,
 8089            range: Range<usize>,
 8090            replace_newest: bool,
 8091            auto_scroll: Option<Autoscroll>,
 8092            cx: &mut ViewContext<Editor>,
 8093        ) {
 8094            this.unfold_ranges(&[range.clone()], false, true, cx);
 8095            this.change_selections(auto_scroll, cx, |s| {
 8096                if replace_newest {
 8097                    s.delete(s.newest_anchor().id);
 8098                }
 8099                s.insert_range(range.clone());
 8100            });
 8101        }
 8102
 8103        let buffer = &display_map.buffer_snapshot;
 8104        let mut selections = self.selections.all::<usize>(cx);
 8105        if let Some(mut select_next_state) = self.select_next_state.take() {
 8106            let query = &select_next_state.query;
 8107            if !select_next_state.done {
 8108                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8109                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8110                let mut next_selected_range = None;
 8111
 8112                let bytes_after_last_selection =
 8113                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8114                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8115                let query_matches = query
 8116                    .stream_find_iter(bytes_after_last_selection)
 8117                    .map(|result| (last_selection.end, result))
 8118                    .chain(
 8119                        query
 8120                            .stream_find_iter(bytes_before_first_selection)
 8121                            .map(|result| (0, result)),
 8122                    );
 8123
 8124                for (start_offset, query_match) in query_matches {
 8125                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8126                    let offset_range =
 8127                        start_offset + query_match.start()..start_offset + query_match.end();
 8128                    let display_range = offset_range.start.to_display_point(display_map)
 8129                        ..offset_range.end.to_display_point(display_map);
 8130
 8131                    if !select_next_state.wordwise
 8132                        || (!movement::is_inside_word(display_map, display_range.start)
 8133                            && !movement::is_inside_word(display_map, display_range.end))
 8134                    {
 8135                        // TODO: This is n^2, because we might check all the selections
 8136                        if !selections
 8137                            .iter()
 8138                            .any(|selection| selection.range().overlaps(&offset_range))
 8139                        {
 8140                            next_selected_range = Some(offset_range);
 8141                            break;
 8142                        }
 8143                    }
 8144                }
 8145
 8146                if let Some(next_selected_range) = next_selected_range {
 8147                    select_next_match_ranges(
 8148                        self,
 8149                        next_selected_range,
 8150                        replace_newest,
 8151                        autoscroll,
 8152                        cx,
 8153                    );
 8154                } else {
 8155                    select_next_state.done = true;
 8156                }
 8157            }
 8158
 8159            self.select_next_state = Some(select_next_state);
 8160        } else {
 8161            let mut only_carets = true;
 8162            let mut same_text_selected = true;
 8163            let mut selected_text = None;
 8164
 8165            let mut selections_iter = selections.iter().peekable();
 8166            while let Some(selection) = selections_iter.next() {
 8167                if selection.start != selection.end {
 8168                    only_carets = false;
 8169                }
 8170
 8171                if same_text_selected {
 8172                    if selected_text.is_none() {
 8173                        selected_text =
 8174                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8175                    }
 8176
 8177                    if let Some(next_selection) = selections_iter.peek() {
 8178                        if next_selection.range().len() == selection.range().len() {
 8179                            let next_selected_text = buffer
 8180                                .text_for_range(next_selection.range())
 8181                                .collect::<String>();
 8182                            if Some(next_selected_text) != selected_text {
 8183                                same_text_selected = false;
 8184                                selected_text = None;
 8185                            }
 8186                        } else {
 8187                            same_text_selected = false;
 8188                            selected_text = None;
 8189                        }
 8190                    }
 8191                }
 8192            }
 8193
 8194            if only_carets {
 8195                for selection in &mut selections {
 8196                    let word_range = movement::surrounding_word(
 8197                        display_map,
 8198                        selection.start.to_display_point(display_map),
 8199                    );
 8200                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8201                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8202                    selection.goal = SelectionGoal::None;
 8203                    selection.reversed = false;
 8204                    select_next_match_ranges(
 8205                        self,
 8206                        selection.start..selection.end,
 8207                        replace_newest,
 8208                        autoscroll,
 8209                        cx,
 8210                    );
 8211                }
 8212
 8213                if selections.len() == 1 {
 8214                    let selection = selections
 8215                        .last()
 8216                        .expect("ensured that there's only one selection");
 8217                    let query = buffer
 8218                        .text_for_range(selection.start..selection.end)
 8219                        .collect::<String>();
 8220                    let is_empty = query.is_empty();
 8221                    let select_state = SelectNextState {
 8222                        query: AhoCorasick::new(&[query])?,
 8223                        wordwise: true,
 8224                        done: is_empty,
 8225                    };
 8226                    self.select_next_state = Some(select_state);
 8227                } else {
 8228                    self.select_next_state = None;
 8229                }
 8230            } else if let Some(selected_text) = selected_text {
 8231                self.select_next_state = Some(SelectNextState {
 8232                    query: AhoCorasick::new(&[selected_text])?,
 8233                    wordwise: false,
 8234                    done: false,
 8235                });
 8236                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8237            }
 8238        }
 8239        Ok(())
 8240    }
 8241
 8242    pub fn select_all_matches(
 8243        &mut self,
 8244        _action: &SelectAllMatches,
 8245        cx: &mut ViewContext<Self>,
 8246    ) -> Result<()> {
 8247        self.push_to_selection_history();
 8248        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8249
 8250        self.select_next_match_internal(&display_map, false, None, cx)?;
 8251        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8252            return Ok(());
 8253        };
 8254        if select_next_state.done {
 8255            return Ok(());
 8256        }
 8257
 8258        let mut new_selections = self.selections.all::<usize>(cx);
 8259
 8260        let buffer = &display_map.buffer_snapshot;
 8261        let query_matches = select_next_state
 8262            .query
 8263            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8264
 8265        for query_match in query_matches {
 8266            let query_match = query_match.unwrap(); // can only fail due to I/O
 8267            let offset_range = query_match.start()..query_match.end();
 8268            let display_range = offset_range.start.to_display_point(&display_map)
 8269                ..offset_range.end.to_display_point(&display_map);
 8270
 8271            if !select_next_state.wordwise
 8272                || (!movement::is_inside_word(&display_map, display_range.start)
 8273                    && !movement::is_inside_word(&display_map, display_range.end))
 8274            {
 8275                self.selections.change_with(cx, |selections| {
 8276                    new_selections.push(Selection {
 8277                        id: selections.new_selection_id(),
 8278                        start: offset_range.start,
 8279                        end: offset_range.end,
 8280                        reversed: false,
 8281                        goal: SelectionGoal::None,
 8282                    });
 8283                });
 8284            }
 8285        }
 8286
 8287        new_selections.sort_by_key(|selection| selection.start);
 8288        let mut ix = 0;
 8289        while ix + 1 < new_selections.len() {
 8290            let current_selection = &new_selections[ix];
 8291            let next_selection = &new_selections[ix + 1];
 8292            if current_selection.range().overlaps(&next_selection.range()) {
 8293                if current_selection.id < next_selection.id {
 8294                    new_selections.remove(ix + 1);
 8295                } else {
 8296                    new_selections.remove(ix);
 8297                }
 8298            } else {
 8299                ix += 1;
 8300            }
 8301        }
 8302
 8303        select_next_state.done = true;
 8304        self.unfold_ranges(
 8305            &new_selections
 8306                .iter()
 8307                .map(|selection| selection.range())
 8308                .collect::<Vec<_>>(),
 8309            false,
 8310            false,
 8311            cx,
 8312        );
 8313        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8314            selections.select(new_selections)
 8315        });
 8316
 8317        Ok(())
 8318    }
 8319
 8320    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8321        self.push_to_selection_history();
 8322        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8323        self.select_next_match_internal(
 8324            &display_map,
 8325            action.replace_newest,
 8326            Some(Autoscroll::newest()),
 8327            cx,
 8328        )?;
 8329        Ok(())
 8330    }
 8331
 8332    pub fn select_previous(
 8333        &mut self,
 8334        action: &SelectPrevious,
 8335        cx: &mut ViewContext<Self>,
 8336    ) -> Result<()> {
 8337        self.push_to_selection_history();
 8338        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8339        let buffer = &display_map.buffer_snapshot;
 8340        let mut selections = self.selections.all::<usize>(cx);
 8341        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8342            let query = &select_prev_state.query;
 8343            if !select_prev_state.done {
 8344                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8345                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8346                let mut next_selected_range = None;
 8347                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8348                let bytes_before_last_selection =
 8349                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8350                let bytes_after_first_selection =
 8351                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8352                let query_matches = query
 8353                    .stream_find_iter(bytes_before_last_selection)
 8354                    .map(|result| (last_selection.start, result))
 8355                    .chain(
 8356                        query
 8357                            .stream_find_iter(bytes_after_first_selection)
 8358                            .map(|result| (buffer.len(), result)),
 8359                    );
 8360                for (end_offset, query_match) in query_matches {
 8361                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8362                    let offset_range =
 8363                        end_offset - query_match.end()..end_offset - query_match.start();
 8364                    let display_range = offset_range.start.to_display_point(&display_map)
 8365                        ..offset_range.end.to_display_point(&display_map);
 8366
 8367                    if !select_prev_state.wordwise
 8368                        || (!movement::is_inside_word(&display_map, display_range.start)
 8369                            && !movement::is_inside_word(&display_map, display_range.end))
 8370                    {
 8371                        next_selected_range = Some(offset_range);
 8372                        break;
 8373                    }
 8374                }
 8375
 8376                if let Some(next_selected_range) = next_selected_range {
 8377                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8378                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8379                        if action.replace_newest {
 8380                            s.delete(s.newest_anchor().id);
 8381                        }
 8382                        s.insert_range(next_selected_range);
 8383                    });
 8384                } else {
 8385                    select_prev_state.done = true;
 8386                }
 8387            }
 8388
 8389            self.select_prev_state = Some(select_prev_state);
 8390        } else {
 8391            let mut only_carets = true;
 8392            let mut same_text_selected = true;
 8393            let mut selected_text = None;
 8394
 8395            let mut selections_iter = selections.iter().peekable();
 8396            while let Some(selection) = selections_iter.next() {
 8397                if selection.start != selection.end {
 8398                    only_carets = false;
 8399                }
 8400
 8401                if same_text_selected {
 8402                    if selected_text.is_none() {
 8403                        selected_text =
 8404                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8405                    }
 8406
 8407                    if let Some(next_selection) = selections_iter.peek() {
 8408                        if next_selection.range().len() == selection.range().len() {
 8409                            let next_selected_text = buffer
 8410                                .text_for_range(next_selection.range())
 8411                                .collect::<String>();
 8412                            if Some(next_selected_text) != selected_text {
 8413                                same_text_selected = false;
 8414                                selected_text = None;
 8415                            }
 8416                        } else {
 8417                            same_text_selected = false;
 8418                            selected_text = None;
 8419                        }
 8420                    }
 8421                }
 8422            }
 8423
 8424            if only_carets {
 8425                for selection in &mut selections {
 8426                    let word_range = movement::surrounding_word(
 8427                        &display_map,
 8428                        selection.start.to_display_point(&display_map),
 8429                    );
 8430                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8431                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8432                    selection.goal = SelectionGoal::None;
 8433                    selection.reversed = false;
 8434                }
 8435                if selections.len() == 1 {
 8436                    let selection = selections
 8437                        .last()
 8438                        .expect("ensured that there's only one selection");
 8439                    let query = buffer
 8440                        .text_for_range(selection.start..selection.end)
 8441                        .collect::<String>();
 8442                    let is_empty = query.is_empty();
 8443                    let select_state = SelectNextState {
 8444                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8445                        wordwise: true,
 8446                        done: is_empty,
 8447                    };
 8448                    self.select_prev_state = Some(select_state);
 8449                } else {
 8450                    self.select_prev_state = None;
 8451                }
 8452
 8453                self.unfold_ranges(
 8454                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8455                    false,
 8456                    true,
 8457                    cx,
 8458                );
 8459                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8460                    s.select(selections);
 8461                });
 8462            } else if let Some(selected_text) = selected_text {
 8463                self.select_prev_state = Some(SelectNextState {
 8464                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8465                    wordwise: false,
 8466                    done: false,
 8467                });
 8468                self.select_previous(action, cx)?;
 8469            }
 8470        }
 8471        Ok(())
 8472    }
 8473
 8474    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8475        if self.read_only(cx) {
 8476            return;
 8477        }
 8478        let text_layout_details = &self.text_layout_details(cx);
 8479        self.transact(cx, |this, cx| {
 8480            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8481            let mut edits = Vec::new();
 8482            let mut selection_edit_ranges = Vec::new();
 8483            let mut last_toggled_row = None;
 8484            let snapshot = this.buffer.read(cx).read(cx);
 8485            let empty_str: Arc<str> = Arc::default();
 8486            let mut suffixes_inserted = Vec::new();
 8487            let ignore_indent = action.ignore_indent;
 8488
 8489            fn comment_prefix_range(
 8490                snapshot: &MultiBufferSnapshot,
 8491                row: MultiBufferRow,
 8492                comment_prefix: &str,
 8493                comment_prefix_whitespace: &str,
 8494                ignore_indent: bool,
 8495            ) -> Range<Point> {
 8496                let indent_size = if ignore_indent {
 8497                    0
 8498                } else {
 8499                    snapshot.indent_size_for_line(row).len
 8500                };
 8501
 8502                let start = Point::new(row.0, indent_size);
 8503
 8504                let mut line_bytes = snapshot
 8505                    .bytes_in_range(start..snapshot.max_point())
 8506                    .flatten()
 8507                    .copied();
 8508
 8509                // If this line currently begins with the line comment prefix, then record
 8510                // the range containing the prefix.
 8511                if line_bytes
 8512                    .by_ref()
 8513                    .take(comment_prefix.len())
 8514                    .eq(comment_prefix.bytes())
 8515                {
 8516                    // Include any whitespace that matches the comment prefix.
 8517                    let matching_whitespace_len = line_bytes
 8518                        .zip(comment_prefix_whitespace.bytes())
 8519                        .take_while(|(a, b)| a == b)
 8520                        .count() as u32;
 8521                    let end = Point::new(
 8522                        start.row,
 8523                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8524                    );
 8525                    start..end
 8526                } else {
 8527                    start..start
 8528                }
 8529            }
 8530
 8531            fn comment_suffix_range(
 8532                snapshot: &MultiBufferSnapshot,
 8533                row: MultiBufferRow,
 8534                comment_suffix: &str,
 8535                comment_suffix_has_leading_space: bool,
 8536            ) -> Range<Point> {
 8537                let end = Point::new(row.0, snapshot.line_len(row));
 8538                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8539
 8540                let mut line_end_bytes = snapshot
 8541                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8542                    .flatten()
 8543                    .copied();
 8544
 8545                let leading_space_len = if suffix_start_column > 0
 8546                    && line_end_bytes.next() == Some(b' ')
 8547                    && comment_suffix_has_leading_space
 8548                {
 8549                    1
 8550                } else {
 8551                    0
 8552                };
 8553
 8554                // If this line currently begins with the line comment prefix, then record
 8555                // the range containing the prefix.
 8556                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8557                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8558                    start..end
 8559                } else {
 8560                    end..end
 8561                }
 8562            }
 8563
 8564            // TODO: Handle selections that cross excerpts
 8565            for selection in &mut selections {
 8566                let start_column = snapshot
 8567                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8568                    .len;
 8569                let language = if let Some(language) =
 8570                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8571                {
 8572                    language
 8573                } else {
 8574                    continue;
 8575                };
 8576
 8577                selection_edit_ranges.clear();
 8578
 8579                // If multiple selections contain a given row, avoid processing that
 8580                // row more than once.
 8581                let mut start_row = MultiBufferRow(selection.start.row);
 8582                if last_toggled_row == Some(start_row) {
 8583                    start_row = start_row.next_row();
 8584                }
 8585                let end_row =
 8586                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8587                        MultiBufferRow(selection.end.row - 1)
 8588                    } else {
 8589                        MultiBufferRow(selection.end.row)
 8590                    };
 8591                last_toggled_row = Some(end_row);
 8592
 8593                if start_row > end_row {
 8594                    continue;
 8595                }
 8596
 8597                // If the language has line comments, toggle those.
 8598                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8599
 8600                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8601                if ignore_indent {
 8602                    full_comment_prefixes = full_comment_prefixes
 8603                        .into_iter()
 8604                        .map(|s| Arc::from(s.trim_end()))
 8605                        .collect();
 8606                }
 8607
 8608                if !full_comment_prefixes.is_empty() {
 8609                    let first_prefix = full_comment_prefixes
 8610                        .first()
 8611                        .expect("prefixes is non-empty");
 8612                    let prefix_trimmed_lengths = full_comment_prefixes
 8613                        .iter()
 8614                        .map(|p| p.trim_end_matches(' ').len())
 8615                        .collect::<SmallVec<[usize; 4]>>();
 8616
 8617                    let mut all_selection_lines_are_comments = true;
 8618
 8619                    for row in start_row.0..=end_row.0 {
 8620                        let row = MultiBufferRow(row);
 8621                        if start_row < end_row && snapshot.is_line_blank(row) {
 8622                            continue;
 8623                        }
 8624
 8625                        let prefix_range = full_comment_prefixes
 8626                            .iter()
 8627                            .zip(prefix_trimmed_lengths.iter().copied())
 8628                            .map(|(prefix, trimmed_prefix_len)| {
 8629                                comment_prefix_range(
 8630                                    snapshot.deref(),
 8631                                    row,
 8632                                    &prefix[..trimmed_prefix_len],
 8633                                    &prefix[trimmed_prefix_len..],
 8634                                    ignore_indent,
 8635                                )
 8636                            })
 8637                            .max_by_key(|range| range.end.column - range.start.column)
 8638                            .expect("prefixes is non-empty");
 8639
 8640                        if prefix_range.is_empty() {
 8641                            all_selection_lines_are_comments = false;
 8642                        }
 8643
 8644                        selection_edit_ranges.push(prefix_range);
 8645                    }
 8646
 8647                    if all_selection_lines_are_comments {
 8648                        edits.extend(
 8649                            selection_edit_ranges
 8650                                .iter()
 8651                                .cloned()
 8652                                .map(|range| (range, empty_str.clone())),
 8653                        );
 8654                    } else {
 8655                        let min_column = selection_edit_ranges
 8656                            .iter()
 8657                            .map(|range| range.start.column)
 8658                            .min()
 8659                            .unwrap_or(0);
 8660                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8661                            let position = Point::new(range.start.row, min_column);
 8662                            (position..position, first_prefix.clone())
 8663                        }));
 8664                    }
 8665                } else if let Some((full_comment_prefix, comment_suffix)) =
 8666                    language.block_comment_delimiters()
 8667                {
 8668                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8669                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8670                    let prefix_range = comment_prefix_range(
 8671                        snapshot.deref(),
 8672                        start_row,
 8673                        comment_prefix,
 8674                        comment_prefix_whitespace,
 8675                        ignore_indent,
 8676                    );
 8677                    let suffix_range = comment_suffix_range(
 8678                        snapshot.deref(),
 8679                        end_row,
 8680                        comment_suffix.trim_start_matches(' '),
 8681                        comment_suffix.starts_with(' '),
 8682                    );
 8683
 8684                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8685                        edits.push((
 8686                            prefix_range.start..prefix_range.start,
 8687                            full_comment_prefix.clone(),
 8688                        ));
 8689                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8690                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8691                    } else {
 8692                        edits.push((prefix_range, empty_str.clone()));
 8693                        edits.push((suffix_range, empty_str.clone()));
 8694                    }
 8695                } else {
 8696                    continue;
 8697                }
 8698            }
 8699
 8700            drop(snapshot);
 8701            this.buffer.update(cx, |buffer, cx| {
 8702                buffer.edit(edits, None, cx);
 8703            });
 8704
 8705            // Adjust selections so that they end before any comment suffixes that
 8706            // were inserted.
 8707            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8708            let mut selections = this.selections.all::<Point>(cx);
 8709            let snapshot = this.buffer.read(cx).read(cx);
 8710            for selection in &mut selections {
 8711                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8712                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8713                        Ordering::Less => {
 8714                            suffixes_inserted.next();
 8715                            continue;
 8716                        }
 8717                        Ordering::Greater => break,
 8718                        Ordering::Equal => {
 8719                            if selection.end.column == snapshot.line_len(row) {
 8720                                if selection.is_empty() {
 8721                                    selection.start.column -= suffix_len as u32;
 8722                                }
 8723                                selection.end.column -= suffix_len as u32;
 8724                            }
 8725                            break;
 8726                        }
 8727                    }
 8728                }
 8729            }
 8730
 8731            drop(snapshot);
 8732            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8733
 8734            let selections = this.selections.all::<Point>(cx);
 8735            let selections_on_single_row = selections.windows(2).all(|selections| {
 8736                selections[0].start.row == selections[1].start.row
 8737                    && selections[0].end.row == selections[1].end.row
 8738                    && selections[0].start.row == selections[0].end.row
 8739            });
 8740            let selections_selecting = selections
 8741                .iter()
 8742                .any(|selection| selection.start != selection.end);
 8743            let advance_downwards = action.advance_downwards
 8744                && selections_on_single_row
 8745                && !selections_selecting
 8746                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8747
 8748            if advance_downwards {
 8749                let snapshot = this.buffer.read(cx).snapshot(cx);
 8750
 8751                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8752                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8753                        let mut point = display_point.to_point(display_snapshot);
 8754                        point.row += 1;
 8755                        point = snapshot.clip_point(point, Bias::Left);
 8756                        let display_point = point.to_display_point(display_snapshot);
 8757                        let goal = SelectionGoal::HorizontalPosition(
 8758                            display_snapshot
 8759                                .x_for_display_point(display_point, text_layout_details)
 8760                                .into(),
 8761                        );
 8762                        (display_point, goal)
 8763                    })
 8764                });
 8765            }
 8766        });
 8767    }
 8768
 8769    pub fn select_enclosing_symbol(
 8770        &mut self,
 8771        _: &SelectEnclosingSymbol,
 8772        cx: &mut ViewContext<Self>,
 8773    ) {
 8774        let buffer = self.buffer.read(cx).snapshot(cx);
 8775        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8776
 8777        fn update_selection(
 8778            selection: &Selection<usize>,
 8779            buffer_snap: &MultiBufferSnapshot,
 8780        ) -> Option<Selection<usize>> {
 8781            let cursor = selection.head();
 8782            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8783            for symbol in symbols.iter().rev() {
 8784                let start = symbol.range.start.to_offset(buffer_snap);
 8785                let end = symbol.range.end.to_offset(buffer_snap);
 8786                let new_range = start..end;
 8787                if start < selection.start || end > selection.end {
 8788                    return Some(Selection {
 8789                        id: selection.id,
 8790                        start: new_range.start,
 8791                        end: new_range.end,
 8792                        goal: SelectionGoal::None,
 8793                        reversed: selection.reversed,
 8794                    });
 8795                }
 8796            }
 8797            None
 8798        }
 8799
 8800        let mut selected_larger_symbol = false;
 8801        let new_selections = old_selections
 8802            .iter()
 8803            .map(|selection| match update_selection(selection, &buffer) {
 8804                Some(new_selection) => {
 8805                    if new_selection.range() != selection.range() {
 8806                        selected_larger_symbol = true;
 8807                    }
 8808                    new_selection
 8809                }
 8810                None => selection.clone(),
 8811            })
 8812            .collect::<Vec<_>>();
 8813
 8814        if selected_larger_symbol {
 8815            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8816                s.select(new_selections);
 8817            });
 8818        }
 8819    }
 8820
 8821    pub fn select_larger_syntax_node(
 8822        &mut self,
 8823        _: &SelectLargerSyntaxNode,
 8824        cx: &mut ViewContext<Self>,
 8825    ) {
 8826        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8827        let buffer = self.buffer.read(cx).snapshot(cx);
 8828        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8829
 8830        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8831        let mut selected_larger_node = false;
 8832        let new_selections = old_selections
 8833            .iter()
 8834            .map(|selection| {
 8835                let old_range = selection.start..selection.end;
 8836                let mut new_range = old_range.clone();
 8837                let mut new_node = None;
 8838                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 8839                {
 8840                    new_node = Some(node);
 8841                    new_range = containing_range;
 8842                    if !display_map.intersects_fold(new_range.start)
 8843                        && !display_map.intersects_fold(new_range.end)
 8844                    {
 8845                        break;
 8846                    }
 8847                }
 8848
 8849                if let Some(node) = new_node {
 8850                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 8851                    // nodes. Parent and grandparent are also logged because this operation will not
 8852                    // visit nodes that have the same range as their parent.
 8853                    log::info!("Node: {node:?}");
 8854                    let parent = node.parent();
 8855                    log::info!("Parent: {parent:?}");
 8856                    let grandparent = parent.and_then(|x| x.parent());
 8857                    log::info!("Grandparent: {grandparent:?}");
 8858                }
 8859
 8860                selected_larger_node |= new_range != old_range;
 8861                Selection {
 8862                    id: selection.id,
 8863                    start: new_range.start,
 8864                    end: new_range.end,
 8865                    goal: SelectionGoal::None,
 8866                    reversed: selection.reversed,
 8867                }
 8868            })
 8869            .collect::<Vec<_>>();
 8870
 8871        if selected_larger_node {
 8872            stack.push(old_selections);
 8873            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8874                s.select(new_selections);
 8875            });
 8876        }
 8877        self.select_larger_syntax_node_stack = stack;
 8878    }
 8879
 8880    pub fn select_smaller_syntax_node(
 8881        &mut self,
 8882        _: &SelectSmallerSyntaxNode,
 8883        cx: &mut ViewContext<Self>,
 8884    ) {
 8885        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8886        if let Some(selections) = stack.pop() {
 8887            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8888                s.select(selections.to_vec());
 8889            });
 8890        }
 8891        self.select_larger_syntax_node_stack = stack;
 8892    }
 8893
 8894    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8895        if !EditorSettings::get_global(cx).gutter.runnables {
 8896            self.clear_tasks();
 8897            return Task::ready(());
 8898        }
 8899        let project = self.project.as_ref().map(Model::downgrade);
 8900        cx.spawn(|this, mut cx| async move {
 8901            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8902            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8903                return;
 8904            };
 8905            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8906                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8907            }) else {
 8908                return;
 8909            };
 8910
 8911            let hide_runnables = project
 8912                .update(&mut cx, |project, cx| {
 8913                    // Do not display any test indicators in non-dev server remote projects.
 8914                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8915                })
 8916                .unwrap_or(true);
 8917            if hide_runnables {
 8918                return;
 8919            }
 8920            let new_rows =
 8921                cx.background_executor()
 8922                    .spawn({
 8923                        let snapshot = display_snapshot.clone();
 8924                        async move {
 8925                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8926                        }
 8927                    })
 8928                    .await;
 8929            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8930
 8931            this.update(&mut cx, |this, _| {
 8932                this.clear_tasks();
 8933                for (key, value) in rows {
 8934                    this.insert_tasks(key, value);
 8935                }
 8936            })
 8937            .ok();
 8938        })
 8939    }
 8940    fn fetch_runnable_ranges(
 8941        snapshot: &DisplaySnapshot,
 8942        range: Range<Anchor>,
 8943    ) -> Vec<language::RunnableRange> {
 8944        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8945    }
 8946
 8947    fn runnable_rows(
 8948        project: Model<Project>,
 8949        snapshot: DisplaySnapshot,
 8950        runnable_ranges: Vec<RunnableRange>,
 8951        mut cx: AsyncWindowContext,
 8952    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8953        runnable_ranges
 8954            .into_iter()
 8955            .filter_map(|mut runnable| {
 8956                let tasks = cx
 8957                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8958                    .ok()?;
 8959                if tasks.is_empty() {
 8960                    return None;
 8961                }
 8962
 8963                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8964
 8965                let row = snapshot
 8966                    .buffer_snapshot
 8967                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8968                    .1
 8969                    .start
 8970                    .row;
 8971
 8972                let context_range =
 8973                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8974                Some((
 8975                    (runnable.buffer_id, row),
 8976                    RunnableTasks {
 8977                        templates: tasks,
 8978                        offset: MultiBufferOffset(runnable.run_range.start),
 8979                        context_range,
 8980                        column: point.column,
 8981                        extra_variables: runnable.extra_captures,
 8982                    },
 8983                ))
 8984            })
 8985            .collect()
 8986    }
 8987
 8988    fn templates_with_tags(
 8989        project: &Model<Project>,
 8990        runnable: &mut Runnable,
 8991        cx: &WindowContext,
 8992    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8993        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8994            let (worktree_id, file) = project
 8995                .buffer_for_id(runnable.buffer, cx)
 8996                .and_then(|buffer| buffer.read(cx).file())
 8997                .map(|file| (file.worktree_id(cx), file.clone()))
 8998                .unzip();
 8999
 9000            (
 9001                project.task_store().read(cx).task_inventory().cloned(),
 9002                worktree_id,
 9003                file,
 9004            )
 9005        });
 9006
 9007        let tags = mem::take(&mut runnable.tags);
 9008        let mut tags: Vec<_> = tags
 9009            .into_iter()
 9010            .flat_map(|tag| {
 9011                let tag = tag.0.clone();
 9012                inventory
 9013                    .as_ref()
 9014                    .into_iter()
 9015                    .flat_map(|inventory| {
 9016                        inventory.read(cx).list_tasks(
 9017                            file.clone(),
 9018                            Some(runnable.language.clone()),
 9019                            worktree_id,
 9020                            cx,
 9021                        )
 9022                    })
 9023                    .filter(move |(_, template)| {
 9024                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9025                    })
 9026            })
 9027            .sorted_by_key(|(kind, _)| kind.to_owned())
 9028            .collect();
 9029        if let Some((leading_tag_source, _)) = tags.first() {
 9030            // Strongest source wins; if we have worktree tag binding, prefer that to
 9031            // global and language bindings;
 9032            // if we have a global binding, prefer that to language binding.
 9033            let first_mismatch = tags
 9034                .iter()
 9035                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9036            if let Some(index) = first_mismatch {
 9037                tags.truncate(index);
 9038            }
 9039        }
 9040
 9041        tags
 9042    }
 9043
 9044    pub fn move_to_enclosing_bracket(
 9045        &mut self,
 9046        _: &MoveToEnclosingBracket,
 9047        cx: &mut ViewContext<Self>,
 9048    ) {
 9049        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9050            s.move_offsets_with(|snapshot, selection| {
 9051                let Some(enclosing_bracket_ranges) =
 9052                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9053                else {
 9054                    return;
 9055                };
 9056
 9057                let mut best_length = usize::MAX;
 9058                let mut best_inside = false;
 9059                let mut best_in_bracket_range = false;
 9060                let mut best_destination = None;
 9061                for (open, close) in enclosing_bracket_ranges {
 9062                    let close = close.to_inclusive();
 9063                    let length = close.end() - open.start;
 9064                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9065                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9066                        || close.contains(&selection.head());
 9067
 9068                    // If best is next to a bracket and current isn't, skip
 9069                    if !in_bracket_range && best_in_bracket_range {
 9070                        continue;
 9071                    }
 9072
 9073                    // Prefer smaller lengths unless best is inside and current isn't
 9074                    if length > best_length && (best_inside || !inside) {
 9075                        continue;
 9076                    }
 9077
 9078                    best_length = length;
 9079                    best_inside = inside;
 9080                    best_in_bracket_range = in_bracket_range;
 9081                    best_destination = Some(
 9082                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9083                            if inside {
 9084                                open.end
 9085                            } else {
 9086                                open.start
 9087                            }
 9088                        } else if inside {
 9089                            *close.start()
 9090                        } else {
 9091                            *close.end()
 9092                        },
 9093                    );
 9094                }
 9095
 9096                if let Some(destination) = best_destination {
 9097                    selection.collapse_to(destination, SelectionGoal::None);
 9098                }
 9099            })
 9100        });
 9101    }
 9102
 9103    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9104        self.end_selection(cx);
 9105        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9106        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9107            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9108            self.select_next_state = entry.select_next_state;
 9109            self.select_prev_state = entry.select_prev_state;
 9110            self.add_selections_state = entry.add_selections_state;
 9111            self.request_autoscroll(Autoscroll::newest(), cx);
 9112        }
 9113        self.selection_history.mode = SelectionHistoryMode::Normal;
 9114    }
 9115
 9116    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9117        self.end_selection(cx);
 9118        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9119        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9120            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9121            self.select_next_state = entry.select_next_state;
 9122            self.select_prev_state = entry.select_prev_state;
 9123            self.add_selections_state = entry.add_selections_state;
 9124            self.request_autoscroll(Autoscroll::newest(), cx);
 9125        }
 9126        self.selection_history.mode = SelectionHistoryMode::Normal;
 9127    }
 9128
 9129    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9130        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9131    }
 9132
 9133    pub fn expand_excerpts_down(
 9134        &mut self,
 9135        action: &ExpandExcerptsDown,
 9136        cx: &mut ViewContext<Self>,
 9137    ) {
 9138        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9139    }
 9140
 9141    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9142        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9143    }
 9144
 9145    pub fn expand_excerpts_for_direction(
 9146        &mut self,
 9147        lines: u32,
 9148        direction: ExpandExcerptDirection,
 9149        cx: &mut ViewContext<Self>,
 9150    ) {
 9151        let selections = self.selections.disjoint_anchors();
 9152
 9153        let lines = if lines == 0 {
 9154            EditorSettings::get_global(cx).expand_excerpt_lines
 9155        } else {
 9156            lines
 9157        };
 9158
 9159        self.buffer.update(cx, |buffer, cx| {
 9160            let snapshot = buffer.snapshot(cx);
 9161            let mut excerpt_ids = selections
 9162                .iter()
 9163                .flat_map(|selection| {
 9164                    snapshot
 9165                        .excerpts_for_range(selection.range())
 9166                        .map(|excerpt| excerpt.id())
 9167                })
 9168                .collect::<Vec<_>>();
 9169            excerpt_ids.sort();
 9170            excerpt_ids.dedup();
 9171            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
 9172        })
 9173    }
 9174
 9175    pub fn expand_excerpt(
 9176        &mut self,
 9177        excerpt: ExcerptId,
 9178        direction: ExpandExcerptDirection,
 9179        cx: &mut ViewContext<Self>,
 9180    ) {
 9181        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9182        self.buffer.update(cx, |buffer, cx| {
 9183            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9184        })
 9185    }
 9186
 9187    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9188        self.go_to_diagnostic_impl(Direction::Next, cx)
 9189    }
 9190
 9191    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9192        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9193    }
 9194
 9195    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9196        let buffer = self.buffer.read(cx).snapshot(cx);
 9197        let selection = self.selections.newest::<usize>(cx);
 9198
 9199        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9200        if direction == Direction::Next {
 9201            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9202                self.activate_diagnostics(popover.group_id(), cx);
 9203                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
 9204                    let primary_range_start = active_diagnostics.primary_range.start;
 9205                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9206                        let mut new_selection = s.newest_anchor().clone();
 9207                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
 9208                        s.select_anchors(vec![new_selection.clone()]);
 9209                    });
 9210                }
 9211                return;
 9212            }
 9213        }
 9214
 9215        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9216            active_diagnostics
 9217                .primary_range
 9218                .to_offset(&buffer)
 9219                .to_inclusive()
 9220        });
 9221        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9222            if active_primary_range.contains(&selection.head()) {
 9223                *active_primary_range.start()
 9224            } else {
 9225                selection.head()
 9226            }
 9227        } else {
 9228            selection.head()
 9229        };
 9230        let snapshot = self.snapshot(cx);
 9231        loop {
 9232            let diagnostics = if direction == Direction::Prev {
 9233                buffer
 9234                    .diagnostics_in_range(0..search_start, true)
 9235                    .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
 9236                        diagnostic,
 9237                        range: range.to_offset(&buffer),
 9238                    })
 9239                    .collect::<Vec<_>>()
 9240            } else {
 9241                buffer
 9242                    .diagnostics_in_range(search_start..buffer.len(), false)
 9243                    .map(|DiagnosticEntry { diagnostic, range }| DiagnosticEntry {
 9244                        diagnostic,
 9245                        range: range.to_offset(&buffer),
 9246                    })
 9247                    .collect::<Vec<_>>()
 9248            }
 9249            .into_iter()
 9250            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9251            let group = diagnostics
 9252                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9253                // be sorted in a stable way
 9254                // skip until we are at current active diagnostic, if it exists
 9255                .skip_while(|entry| {
 9256                    (match direction {
 9257                        Direction::Prev => entry.range.start >= search_start,
 9258                        Direction::Next => entry.range.start <= search_start,
 9259                    }) && self
 9260                        .active_diagnostics
 9261                        .as_ref()
 9262                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9263                })
 9264                .find_map(|entry| {
 9265                    if entry.diagnostic.is_primary
 9266                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9267                        && !entry.range.is_empty()
 9268                        // if we match with the active diagnostic, skip it
 9269                        && Some(entry.diagnostic.group_id)
 9270                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9271                    {
 9272                        Some((entry.range, entry.diagnostic.group_id))
 9273                    } else {
 9274                        None
 9275                    }
 9276                });
 9277
 9278            if let Some((primary_range, group_id)) = group {
 9279                self.activate_diagnostics(group_id, cx);
 9280                if self.active_diagnostics.is_some() {
 9281                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9282                        s.select(vec![Selection {
 9283                            id: selection.id,
 9284                            start: primary_range.start,
 9285                            end: primary_range.start,
 9286                            reversed: false,
 9287                            goal: SelectionGoal::None,
 9288                        }]);
 9289                    });
 9290                }
 9291                break;
 9292            } else {
 9293                // Cycle around to the start of the buffer, potentially moving back to the start of
 9294                // the currently active diagnostic.
 9295                active_primary_range.take();
 9296                if direction == Direction::Prev {
 9297                    if search_start == buffer.len() {
 9298                        break;
 9299                    } else {
 9300                        search_start = buffer.len();
 9301                    }
 9302                } else if search_start == 0 {
 9303                    break;
 9304                } else {
 9305                    search_start = 0;
 9306                }
 9307            }
 9308        }
 9309    }
 9310
 9311    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9312        let snapshot = self.snapshot(cx);
 9313        let selection = self.selections.newest::<Point>(cx);
 9314        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9315    }
 9316
 9317    fn go_to_hunk_after_position(
 9318        &mut self,
 9319        snapshot: &EditorSnapshot,
 9320        position: Point,
 9321        cx: &mut ViewContext<Editor>,
 9322    ) -> Option<MultiBufferDiffHunk> {
 9323        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9324            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9325                snapshot,
 9326                position,
 9327                ix > 0,
 9328                snapshot.diff_map.diff_hunks_in_range(
 9329                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9330                    &snapshot.buffer_snapshot,
 9331                ),
 9332                cx,
 9333            ) {
 9334                return Some(hunk);
 9335            }
 9336        }
 9337        None
 9338    }
 9339
 9340    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9341        let snapshot = self.snapshot(cx);
 9342        let selection = self.selections.newest::<Point>(cx);
 9343        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9344    }
 9345
 9346    fn go_to_hunk_before_position(
 9347        &mut self,
 9348        snapshot: &EditorSnapshot,
 9349        position: Point,
 9350        cx: &mut ViewContext<Editor>,
 9351    ) -> Option<MultiBufferDiffHunk> {
 9352        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9353            .into_iter()
 9354            .enumerate()
 9355        {
 9356            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9357                snapshot,
 9358                position,
 9359                ix > 0,
 9360                snapshot
 9361                    .diff_map
 9362                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9363                cx,
 9364            ) {
 9365                return Some(hunk);
 9366            }
 9367        }
 9368        None
 9369    }
 9370
 9371    fn go_to_next_hunk_in_direction(
 9372        &mut self,
 9373        snapshot: &DisplaySnapshot,
 9374        initial_point: Point,
 9375        is_wrapped: bool,
 9376        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9377        cx: &mut ViewContext<Editor>,
 9378    ) -> Option<MultiBufferDiffHunk> {
 9379        let display_point = initial_point.to_display_point(snapshot);
 9380        let mut hunks = hunks
 9381            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9382            .filter(|(display_hunk, _)| {
 9383                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9384            })
 9385            .dedup();
 9386
 9387        if let Some((display_hunk, hunk)) = hunks.next() {
 9388            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9389                let row = display_hunk.start_display_row();
 9390                let point = DisplayPoint::new(row, 0);
 9391                s.select_display_ranges([point..point]);
 9392            });
 9393
 9394            Some(hunk)
 9395        } else {
 9396            None
 9397        }
 9398    }
 9399
 9400    pub fn go_to_definition(
 9401        &mut self,
 9402        _: &GoToDefinition,
 9403        cx: &mut ViewContext<Self>,
 9404    ) -> Task<Result<Navigated>> {
 9405        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9406        cx.spawn(|editor, mut cx| async move {
 9407            if definition.await? == Navigated::Yes {
 9408                return Ok(Navigated::Yes);
 9409            }
 9410            match editor.update(&mut cx, |editor, cx| {
 9411                editor.find_all_references(&FindAllReferences, cx)
 9412            })? {
 9413                Some(references) => references.await,
 9414                None => Ok(Navigated::No),
 9415            }
 9416        })
 9417    }
 9418
 9419    pub fn go_to_declaration(
 9420        &mut self,
 9421        _: &GoToDeclaration,
 9422        cx: &mut ViewContext<Self>,
 9423    ) -> Task<Result<Navigated>> {
 9424        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9425    }
 9426
 9427    pub fn go_to_declaration_split(
 9428        &mut self,
 9429        _: &GoToDeclaration,
 9430        cx: &mut ViewContext<Self>,
 9431    ) -> Task<Result<Navigated>> {
 9432        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9433    }
 9434
 9435    pub fn go_to_implementation(
 9436        &mut self,
 9437        _: &GoToImplementation,
 9438        cx: &mut ViewContext<Self>,
 9439    ) -> Task<Result<Navigated>> {
 9440        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9441    }
 9442
 9443    pub fn go_to_implementation_split(
 9444        &mut self,
 9445        _: &GoToImplementationSplit,
 9446        cx: &mut ViewContext<Self>,
 9447    ) -> Task<Result<Navigated>> {
 9448        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9449    }
 9450
 9451    pub fn go_to_type_definition(
 9452        &mut self,
 9453        _: &GoToTypeDefinition,
 9454        cx: &mut ViewContext<Self>,
 9455    ) -> Task<Result<Navigated>> {
 9456        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9457    }
 9458
 9459    pub fn go_to_definition_split(
 9460        &mut self,
 9461        _: &GoToDefinitionSplit,
 9462        cx: &mut ViewContext<Self>,
 9463    ) -> Task<Result<Navigated>> {
 9464        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9465    }
 9466
 9467    pub fn go_to_type_definition_split(
 9468        &mut self,
 9469        _: &GoToTypeDefinitionSplit,
 9470        cx: &mut ViewContext<Self>,
 9471    ) -> Task<Result<Navigated>> {
 9472        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9473    }
 9474
 9475    fn go_to_definition_of_kind(
 9476        &mut self,
 9477        kind: GotoDefinitionKind,
 9478        split: bool,
 9479        cx: &mut ViewContext<Self>,
 9480    ) -> Task<Result<Navigated>> {
 9481        let Some(provider) = self.semantics_provider.clone() else {
 9482            return Task::ready(Ok(Navigated::No));
 9483        };
 9484        let head = self.selections.newest::<usize>(cx).head();
 9485        let buffer = self.buffer.read(cx);
 9486        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9487            text_anchor
 9488        } else {
 9489            return Task::ready(Ok(Navigated::No));
 9490        };
 9491
 9492        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9493            return Task::ready(Ok(Navigated::No));
 9494        };
 9495
 9496        cx.spawn(|editor, mut cx| async move {
 9497            let definitions = definitions.await?;
 9498            let navigated = editor
 9499                .update(&mut cx, |editor, cx| {
 9500                    editor.navigate_to_hover_links(
 9501                        Some(kind),
 9502                        definitions
 9503                            .into_iter()
 9504                            .filter(|location| {
 9505                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9506                            })
 9507                            .map(HoverLink::Text)
 9508                            .collect::<Vec<_>>(),
 9509                        split,
 9510                        cx,
 9511                    )
 9512                })?
 9513                .await?;
 9514            anyhow::Ok(navigated)
 9515        })
 9516    }
 9517
 9518    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9519        let selection = self.selections.newest_anchor();
 9520        let head = selection.head();
 9521        let tail = selection.tail();
 9522
 9523        let Some((buffer, start_position)) =
 9524            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9525        else {
 9526            return;
 9527        };
 9528
 9529        let end_position = if head != tail {
 9530            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9531                return;
 9532            };
 9533            Some(pos)
 9534        } else {
 9535            None
 9536        };
 9537
 9538        let url_finder = cx.spawn(|editor, mut cx| async move {
 9539            let url = if let Some(end_pos) = end_position {
 9540                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9541            } else {
 9542                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9543            };
 9544
 9545            if let Some(url) = url {
 9546                editor.update(&mut cx, |_, cx| {
 9547                    cx.open_url(&url);
 9548                })
 9549            } else {
 9550                Ok(())
 9551            }
 9552        });
 9553
 9554        url_finder.detach();
 9555    }
 9556
 9557    pub fn open_selected_filename(&mut self, _: &OpenSelectedFilename, cx: &mut ViewContext<Self>) {
 9558        let Some(workspace) = self.workspace() else {
 9559            return;
 9560        };
 9561
 9562        let position = self.selections.newest_anchor().head();
 9563
 9564        let Some((buffer, buffer_position)) =
 9565            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9566        else {
 9567            return;
 9568        };
 9569
 9570        let project = self.project.clone();
 9571
 9572        cx.spawn(|_, mut cx| async move {
 9573            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9574
 9575            if let Some((_, path)) = result {
 9576                workspace
 9577                    .update(&mut cx, |workspace, cx| {
 9578                        workspace.open_resolved_path(path, cx)
 9579                    })?
 9580                    .await?;
 9581            }
 9582            anyhow::Ok(())
 9583        })
 9584        .detach();
 9585    }
 9586
 9587    pub(crate) fn navigate_to_hover_links(
 9588        &mut self,
 9589        kind: Option<GotoDefinitionKind>,
 9590        mut definitions: Vec<HoverLink>,
 9591        split: bool,
 9592        cx: &mut ViewContext<Editor>,
 9593    ) -> Task<Result<Navigated>> {
 9594        // If there is one definition, just open it directly
 9595        if definitions.len() == 1 {
 9596            let definition = definitions.pop().unwrap();
 9597
 9598            enum TargetTaskResult {
 9599                Location(Option<Location>),
 9600                AlreadyNavigated,
 9601            }
 9602
 9603            let target_task = match definition {
 9604                HoverLink::Text(link) => {
 9605                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9606                }
 9607                HoverLink::InlayHint(lsp_location, server_id) => {
 9608                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9609                    cx.background_executor().spawn(async move {
 9610                        let location = computation.await?;
 9611                        Ok(TargetTaskResult::Location(location))
 9612                    })
 9613                }
 9614                HoverLink::Url(url) => {
 9615                    cx.open_url(&url);
 9616                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9617                }
 9618                HoverLink::File(path) => {
 9619                    if let Some(workspace) = self.workspace() {
 9620                        cx.spawn(|_, mut cx| async move {
 9621                            workspace
 9622                                .update(&mut cx, |workspace, cx| {
 9623                                    workspace.open_resolved_path(path, cx)
 9624                                })?
 9625                                .await
 9626                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9627                        })
 9628                    } else {
 9629                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9630                    }
 9631                }
 9632            };
 9633            cx.spawn(|editor, mut cx| async move {
 9634                let target = match target_task.await.context("target resolution task")? {
 9635                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9636                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9637                    TargetTaskResult::Location(Some(target)) => target,
 9638                };
 9639
 9640                editor.update(&mut cx, |editor, cx| {
 9641                    let Some(workspace) = editor.workspace() else {
 9642                        return Navigated::No;
 9643                    };
 9644                    let pane = workspace.read(cx).active_pane().clone();
 9645
 9646                    let range = target.range.to_offset(target.buffer.read(cx));
 9647                    let range = editor.range_for_match(&range);
 9648
 9649                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9650                        let buffer = target.buffer.read(cx);
 9651                        let range = check_multiline_range(buffer, range);
 9652                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9653                            s.select_ranges([range]);
 9654                        });
 9655                    } else {
 9656                        cx.window_context().defer(move |cx| {
 9657                            let target_editor: View<Self> =
 9658                                workspace.update(cx, |workspace, cx| {
 9659                                    let pane = if split {
 9660                                        workspace.adjacent_pane(cx)
 9661                                    } else {
 9662                                        workspace.active_pane().clone()
 9663                                    };
 9664
 9665                                    workspace.open_project_item(
 9666                                        pane,
 9667                                        target.buffer.clone(),
 9668                                        true,
 9669                                        true,
 9670                                        cx,
 9671                                    )
 9672                                });
 9673                            target_editor.update(cx, |target_editor, cx| {
 9674                                // When selecting a definition in a different buffer, disable the nav history
 9675                                // to avoid creating a history entry at the previous cursor location.
 9676                                pane.update(cx, |pane, _| pane.disable_history());
 9677                                let buffer = target.buffer.read(cx);
 9678                                let range = check_multiline_range(buffer, range);
 9679                                target_editor.change_selections(
 9680                                    Some(Autoscroll::focused()),
 9681                                    cx,
 9682                                    |s| {
 9683                                        s.select_ranges([range]);
 9684                                    },
 9685                                );
 9686                                pane.update(cx, |pane, _| pane.enable_history());
 9687                            });
 9688                        });
 9689                    }
 9690                    Navigated::Yes
 9691                })
 9692            })
 9693        } else if !definitions.is_empty() {
 9694            cx.spawn(|editor, mut cx| async move {
 9695                let (title, location_tasks, workspace) = editor
 9696                    .update(&mut cx, |editor, cx| {
 9697                        let tab_kind = match kind {
 9698                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9699                            _ => "Definitions",
 9700                        };
 9701                        let title = definitions
 9702                            .iter()
 9703                            .find_map(|definition| match definition {
 9704                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9705                                    let buffer = origin.buffer.read(cx);
 9706                                    format!(
 9707                                        "{} for {}",
 9708                                        tab_kind,
 9709                                        buffer
 9710                                            .text_for_range(origin.range.clone())
 9711                                            .collect::<String>()
 9712                                    )
 9713                                }),
 9714                                HoverLink::InlayHint(_, _) => None,
 9715                                HoverLink::Url(_) => None,
 9716                                HoverLink::File(_) => None,
 9717                            })
 9718                            .unwrap_or(tab_kind.to_string());
 9719                        let location_tasks = definitions
 9720                            .into_iter()
 9721                            .map(|definition| match definition {
 9722                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9723                                HoverLink::InlayHint(lsp_location, server_id) => {
 9724                                    editor.compute_target_location(lsp_location, server_id, cx)
 9725                                }
 9726                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9727                                HoverLink::File(_) => Task::ready(Ok(None)),
 9728                            })
 9729                            .collect::<Vec<_>>();
 9730                        (title, location_tasks, editor.workspace().clone())
 9731                    })
 9732                    .context("location tasks preparation")?;
 9733
 9734                let locations = future::join_all(location_tasks)
 9735                    .await
 9736                    .into_iter()
 9737                    .filter_map(|location| location.transpose())
 9738                    .collect::<Result<_>>()
 9739                    .context("location tasks")?;
 9740
 9741                let Some(workspace) = workspace else {
 9742                    return Ok(Navigated::No);
 9743                };
 9744                let opened = workspace
 9745                    .update(&mut cx, |workspace, cx| {
 9746                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9747                    })
 9748                    .ok();
 9749
 9750                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9751            })
 9752        } else {
 9753            Task::ready(Ok(Navigated::No))
 9754        }
 9755    }
 9756
 9757    fn compute_target_location(
 9758        &self,
 9759        lsp_location: lsp::Location,
 9760        server_id: LanguageServerId,
 9761        cx: &mut ViewContext<Self>,
 9762    ) -> Task<anyhow::Result<Option<Location>>> {
 9763        let Some(project) = self.project.clone() else {
 9764            return Task::ready(Ok(None));
 9765        };
 9766
 9767        cx.spawn(move |editor, mut cx| async move {
 9768            let location_task = editor.update(&mut cx, |_, cx| {
 9769                project.update(cx, |project, cx| {
 9770                    let language_server_name = project
 9771                        .language_server_statuses(cx)
 9772                        .find(|(id, _)| server_id == *id)
 9773                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9774                    language_server_name.map(|language_server_name| {
 9775                        project.open_local_buffer_via_lsp(
 9776                            lsp_location.uri.clone(),
 9777                            server_id,
 9778                            language_server_name,
 9779                            cx,
 9780                        )
 9781                    })
 9782                })
 9783            })?;
 9784            let location = match location_task {
 9785                Some(task) => Some({
 9786                    let target_buffer_handle = task.await.context("open local buffer")?;
 9787                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9788                        let target_start = target_buffer
 9789                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9790                        let target_end = target_buffer
 9791                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9792                        target_buffer.anchor_after(target_start)
 9793                            ..target_buffer.anchor_before(target_end)
 9794                    })?;
 9795                    Location {
 9796                        buffer: target_buffer_handle,
 9797                        range,
 9798                    }
 9799                }),
 9800                None => None,
 9801            };
 9802            Ok(location)
 9803        })
 9804    }
 9805
 9806    pub fn find_all_references(
 9807        &mut self,
 9808        _: &FindAllReferences,
 9809        cx: &mut ViewContext<Self>,
 9810    ) -> Option<Task<Result<Navigated>>> {
 9811        let selection = self.selections.newest::<usize>(cx);
 9812        let multi_buffer = self.buffer.read(cx);
 9813        let head = selection.head();
 9814
 9815        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9816        let head_anchor = multi_buffer_snapshot.anchor_at(
 9817            head,
 9818            if head < selection.tail() {
 9819                Bias::Right
 9820            } else {
 9821                Bias::Left
 9822            },
 9823        );
 9824
 9825        match self
 9826            .find_all_references_task_sources
 9827            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9828        {
 9829            Ok(_) => {
 9830                log::info!(
 9831                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9832                );
 9833                return None;
 9834            }
 9835            Err(i) => {
 9836                self.find_all_references_task_sources.insert(i, head_anchor);
 9837            }
 9838        }
 9839
 9840        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9841        let workspace = self.workspace()?;
 9842        let project = workspace.read(cx).project().clone();
 9843        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9844        Some(cx.spawn(|editor, mut cx| async move {
 9845            let _cleanup = defer({
 9846                let mut cx = cx.clone();
 9847                move || {
 9848                    let _ = editor.update(&mut cx, |editor, _| {
 9849                        if let Ok(i) =
 9850                            editor
 9851                                .find_all_references_task_sources
 9852                                .binary_search_by(|anchor| {
 9853                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9854                                })
 9855                        {
 9856                            editor.find_all_references_task_sources.remove(i);
 9857                        }
 9858                    });
 9859                }
 9860            });
 9861
 9862            let locations = references.await?;
 9863            if locations.is_empty() {
 9864                return anyhow::Ok(Navigated::No);
 9865            }
 9866
 9867            workspace.update(&mut cx, |workspace, cx| {
 9868                let title = locations
 9869                    .first()
 9870                    .as_ref()
 9871                    .map(|location| {
 9872                        let buffer = location.buffer.read(cx);
 9873                        format!(
 9874                            "References to `{}`",
 9875                            buffer
 9876                                .text_for_range(location.range.clone())
 9877                                .collect::<String>()
 9878                        )
 9879                    })
 9880                    .unwrap();
 9881                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9882                Navigated::Yes
 9883            })
 9884        }))
 9885    }
 9886
 9887    /// Opens a multibuffer with the given project locations in it
 9888    pub fn open_locations_in_multibuffer(
 9889        workspace: &mut Workspace,
 9890        mut locations: Vec<Location>,
 9891        title: String,
 9892        split: bool,
 9893        cx: &mut ViewContext<Workspace>,
 9894    ) {
 9895        // If there are multiple definitions, open them in a multibuffer
 9896        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9897        let mut locations = locations.into_iter().peekable();
 9898        let mut ranges_to_highlight = Vec::new();
 9899        let capability = workspace.project().read(cx).capability();
 9900
 9901        let excerpt_buffer = cx.new_model(|cx| {
 9902            let mut multibuffer = MultiBuffer::new(capability);
 9903            while let Some(location) = locations.next() {
 9904                let buffer = location.buffer.read(cx);
 9905                let mut ranges_for_buffer = Vec::new();
 9906                let range = location.range.to_offset(buffer);
 9907                ranges_for_buffer.push(range.clone());
 9908
 9909                while let Some(next_location) = locations.peek() {
 9910                    if next_location.buffer == location.buffer {
 9911                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9912                        locations.next();
 9913                    } else {
 9914                        break;
 9915                    }
 9916                }
 9917
 9918                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9919                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9920                    location.buffer.clone(),
 9921                    ranges_for_buffer,
 9922                    DEFAULT_MULTIBUFFER_CONTEXT,
 9923                    cx,
 9924                ))
 9925            }
 9926
 9927            multibuffer.with_title(title)
 9928        });
 9929
 9930        let editor = cx.new_view(|cx| {
 9931            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9932        });
 9933        editor.update(cx, |editor, cx| {
 9934            if let Some(first_range) = ranges_to_highlight.first() {
 9935                editor.change_selections(None, cx, |selections| {
 9936                    selections.clear_disjoint();
 9937                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9938                });
 9939            }
 9940            editor.highlight_background::<Self>(
 9941                &ranges_to_highlight,
 9942                |theme| theme.editor_highlighted_line_background,
 9943                cx,
 9944            );
 9945            editor.register_buffers_with_language_servers(cx);
 9946        });
 9947
 9948        let item = Box::new(editor);
 9949        let item_id = item.item_id();
 9950
 9951        if split {
 9952            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9953        } else {
 9954            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9955                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9956                    pane.close_current_preview_item(cx)
 9957                } else {
 9958                    None
 9959                }
 9960            });
 9961            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9962        }
 9963        workspace.active_pane().update(cx, |pane, cx| {
 9964            pane.set_preview_item_id(Some(item_id), cx);
 9965        });
 9966    }
 9967
 9968    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9969        use language::ToOffset as _;
 9970
 9971        let provider = self.semantics_provider.clone()?;
 9972        let selection = self.selections.newest_anchor().clone();
 9973        let (cursor_buffer, cursor_buffer_position) = self
 9974            .buffer
 9975            .read(cx)
 9976            .text_anchor_for_position(selection.head(), cx)?;
 9977        let (tail_buffer, cursor_buffer_position_end) = self
 9978            .buffer
 9979            .read(cx)
 9980            .text_anchor_for_position(selection.tail(), cx)?;
 9981        if tail_buffer != cursor_buffer {
 9982            return None;
 9983        }
 9984
 9985        let snapshot = cursor_buffer.read(cx).snapshot();
 9986        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9987        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9988        let prepare_rename = provider
 9989            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9990            .unwrap_or_else(|| Task::ready(Ok(None)));
 9991        drop(snapshot);
 9992
 9993        Some(cx.spawn(|this, mut cx| async move {
 9994            let rename_range = if let Some(range) = prepare_rename.await? {
 9995                Some(range)
 9996            } else {
 9997                this.update(&mut cx, |this, cx| {
 9998                    let buffer = this.buffer.read(cx).snapshot(cx);
 9999                    let mut buffer_highlights = this
10000                        .document_highlights_for_position(selection.head(), &buffer)
10001                        .filter(|highlight| {
10002                            highlight.start.excerpt_id == selection.head().excerpt_id
10003                                && highlight.end.excerpt_id == selection.head().excerpt_id
10004                        });
10005                    buffer_highlights
10006                        .next()
10007                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10008                })?
10009            };
10010            if let Some(rename_range) = rename_range {
10011                this.update(&mut cx, |this, cx| {
10012                    let snapshot = cursor_buffer.read(cx).snapshot();
10013                    let rename_buffer_range = rename_range.to_offset(&snapshot);
10014                    let cursor_offset_in_rename_range =
10015                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10016                    let cursor_offset_in_rename_range_end =
10017                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10018
10019                    this.take_rename(false, cx);
10020                    let buffer = this.buffer.read(cx).read(cx);
10021                    let cursor_offset = selection.head().to_offset(&buffer);
10022                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10023                    let rename_end = rename_start + rename_buffer_range.len();
10024                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10025                    let mut old_highlight_id = None;
10026                    let old_name: Arc<str> = buffer
10027                        .chunks(rename_start..rename_end, true)
10028                        .map(|chunk| {
10029                            if old_highlight_id.is_none() {
10030                                old_highlight_id = chunk.syntax_highlight_id;
10031                            }
10032                            chunk.text
10033                        })
10034                        .collect::<String>()
10035                        .into();
10036
10037                    drop(buffer);
10038
10039                    // Position the selection in the rename editor so that it matches the current selection.
10040                    this.show_local_selections = false;
10041                    let rename_editor = cx.new_view(|cx| {
10042                        let mut editor = Editor::single_line(cx);
10043                        editor.buffer.update(cx, |buffer, cx| {
10044                            buffer.edit([(0..0, old_name.clone())], None, cx)
10045                        });
10046                        let rename_selection_range = match cursor_offset_in_rename_range
10047                            .cmp(&cursor_offset_in_rename_range_end)
10048                        {
10049                            Ordering::Equal => {
10050                                editor.select_all(&SelectAll, cx);
10051                                return editor;
10052                            }
10053                            Ordering::Less => {
10054                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10055                            }
10056                            Ordering::Greater => {
10057                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10058                            }
10059                        };
10060                        if rename_selection_range.end > old_name.len() {
10061                            editor.select_all(&SelectAll, cx);
10062                        } else {
10063                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10064                                s.select_ranges([rename_selection_range]);
10065                            });
10066                        }
10067                        editor
10068                    });
10069                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10070                        if e == &EditorEvent::Focused {
10071                            cx.emit(EditorEvent::FocusedIn)
10072                        }
10073                    })
10074                    .detach();
10075
10076                    let write_highlights =
10077                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10078                    let read_highlights =
10079                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
10080                    let ranges = write_highlights
10081                        .iter()
10082                        .flat_map(|(_, ranges)| ranges.iter())
10083                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10084                        .cloned()
10085                        .collect();
10086
10087                    this.highlight_text::<Rename>(
10088                        ranges,
10089                        HighlightStyle {
10090                            fade_out: Some(0.6),
10091                            ..Default::default()
10092                        },
10093                        cx,
10094                    );
10095                    let rename_focus_handle = rename_editor.focus_handle(cx);
10096                    cx.focus(&rename_focus_handle);
10097                    let block_id = this.insert_blocks(
10098                        [BlockProperties {
10099                            style: BlockStyle::Flex,
10100                            placement: BlockPlacement::Below(range.start),
10101                            height: 1,
10102                            render: Arc::new({
10103                                let rename_editor = rename_editor.clone();
10104                                move |cx: &mut BlockContext| {
10105                                    let mut text_style = cx.editor_style.text.clone();
10106                                    if let Some(highlight_style) = old_highlight_id
10107                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10108                                    {
10109                                        text_style = text_style.highlight(highlight_style);
10110                                    }
10111                                    div()
10112                                        .block_mouse_down()
10113                                        .pl(cx.anchor_x)
10114                                        .child(EditorElement::new(
10115                                            &rename_editor,
10116                                            EditorStyle {
10117                                                background: cx.theme().system().transparent,
10118                                                local_player: cx.editor_style.local_player,
10119                                                text: text_style,
10120                                                scrollbar_width: cx.editor_style.scrollbar_width,
10121                                                syntax: cx.editor_style.syntax.clone(),
10122                                                status: cx.editor_style.status.clone(),
10123                                                inlay_hints_style: HighlightStyle {
10124                                                    font_weight: Some(FontWeight::BOLD),
10125                                                    ..make_inlay_hints_style(cx)
10126                                                },
10127                                                inline_completion_styles: make_suggestion_styles(
10128                                                    cx,
10129                                                ),
10130                                                ..EditorStyle::default()
10131                                            },
10132                                        ))
10133                                        .into_any_element()
10134                                }
10135                            }),
10136                            priority: 0,
10137                        }],
10138                        Some(Autoscroll::fit()),
10139                        cx,
10140                    )[0];
10141                    this.pending_rename = Some(RenameState {
10142                        range,
10143                        old_name,
10144                        editor: rename_editor,
10145                        block_id,
10146                    });
10147                })?;
10148            }
10149
10150            Ok(())
10151        }))
10152    }
10153
10154    pub fn confirm_rename(
10155        &mut self,
10156        _: &ConfirmRename,
10157        cx: &mut ViewContext<Self>,
10158    ) -> Option<Task<Result<()>>> {
10159        let rename = self.take_rename(false, cx)?;
10160        let workspace = self.workspace()?.downgrade();
10161        let (buffer, start) = self
10162            .buffer
10163            .read(cx)
10164            .text_anchor_for_position(rename.range.start, cx)?;
10165        let (end_buffer, _) = self
10166            .buffer
10167            .read(cx)
10168            .text_anchor_for_position(rename.range.end, cx)?;
10169        if buffer != end_buffer {
10170            return None;
10171        }
10172
10173        let old_name = rename.old_name;
10174        let new_name = rename.editor.read(cx).text(cx);
10175
10176        let rename = self.semantics_provider.as_ref()?.perform_rename(
10177            &buffer,
10178            start,
10179            new_name.clone(),
10180            cx,
10181        )?;
10182
10183        Some(cx.spawn(|editor, mut cx| async move {
10184            let project_transaction = rename.await?;
10185            Self::open_project_transaction(
10186                &editor,
10187                workspace,
10188                project_transaction,
10189                format!("Rename: {}{}", old_name, new_name),
10190                cx.clone(),
10191            )
10192            .await?;
10193
10194            editor.update(&mut cx, |editor, cx| {
10195                editor.refresh_document_highlights(cx);
10196            })?;
10197            Ok(())
10198        }))
10199    }
10200
10201    fn take_rename(
10202        &mut self,
10203        moving_cursor: bool,
10204        cx: &mut ViewContext<Self>,
10205    ) -> Option<RenameState> {
10206        let rename = self.pending_rename.take()?;
10207        if rename.editor.focus_handle(cx).is_focused(cx) {
10208            cx.focus(&self.focus_handle);
10209        }
10210
10211        self.remove_blocks(
10212            [rename.block_id].into_iter().collect(),
10213            Some(Autoscroll::fit()),
10214            cx,
10215        );
10216        self.clear_highlights::<Rename>(cx);
10217        self.show_local_selections = true;
10218
10219        if moving_cursor {
10220            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10221                editor.selections.newest::<usize>(cx).head()
10222            });
10223
10224            // Update the selection to match the position of the selection inside
10225            // the rename editor.
10226            let snapshot = self.buffer.read(cx).read(cx);
10227            let rename_range = rename.range.to_offset(&snapshot);
10228            let cursor_in_editor = snapshot
10229                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10230                .min(rename_range.end);
10231            drop(snapshot);
10232
10233            self.change_selections(None, cx, |s| {
10234                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10235            });
10236        } else {
10237            self.refresh_document_highlights(cx);
10238        }
10239
10240        Some(rename)
10241    }
10242
10243    pub fn pending_rename(&self) -> Option<&RenameState> {
10244        self.pending_rename.as_ref()
10245    }
10246
10247    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10248        let project = match &self.project {
10249            Some(project) => project.clone(),
10250            None => return None,
10251        };
10252
10253        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10254    }
10255
10256    fn format_selections(
10257        &mut self,
10258        _: &FormatSelections,
10259        cx: &mut ViewContext<Self>,
10260    ) -> Option<Task<Result<()>>> {
10261        let project = match &self.project {
10262            Some(project) => project.clone(),
10263            None => return None,
10264        };
10265
10266        let selections = self
10267            .selections
10268            .all_adjusted(cx)
10269            .into_iter()
10270            .filter(|s| !s.is_empty())
10271            .collect_vec();
10272
10273        Some(self.perform_format(
10274            project,
10275            FormatTrigger::Manual,
10276            FormatTarget::Ranges(selections),
10277            cx,
10278        ))
10279    }
10280
10281    fn perform_format(
10282        &mut self,
10283        project: Model<Project>,
10284        trigger: FormatTrigger,
10285        target: FormatTarget,
10286        cx: &mut ViewContext<Self>,
10287    ) -> Task<Result<()>> {
10288        let buffer = self.buffer().clone();
10289        let mut buffers = buffer.read(cx).all_buffers();
10290        if trigger == FormatTrigger::Save {
10291            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10292        }
10293
10294        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10295        let format = project.update(cx, |project, cx| {
10296            project.format(buffers, true, trigger, target, cx)
10297        });
10298
10299        cx.spawn(|_, mut cx| async move {
10300            let transaction = futures::select_biased! {
10301                () = timeout => {
10302                    log::warn!("timed out waiting for formatting");
10303                    None
10304                }
10305                transaction = format.log_err().fuse() => transaction,
10306            };
10307
10308            buffer
10309                .update(&mut cx, |buffer, cx| {
10310                    if let Some(transaction) = transaction {
10311                        if !buffer.is_singleton() {
10312                            buffer.push_transaction(&transaction.0, cx);
10313                        }
10314                    }
10315
10316                    cx.notify();
10317                })
10318                .ok();
10319
10320            Ok(())
10321        })
10322    }
10323
10324    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10325        if let Some(project) = self.project.clone() {
10326            self.buffer.update(cx, |multi_buffer, cx| {
10327                project.update(cx, |project, cx| {
10328                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10329                });
10330            })
10331        }
10332    }
10333
10334    fn cancel_language_server_work(
10335        &mut self,
10336        _: &actions::CancelLanguageServerWork,
10337        cx: &mut ViewContext<Self>,
10338    ) {
10339        if let Some(project) = self.project.clone() {
10340            self.buffer.update(cx, |multi_buffer, cx| {
10341                project.update(cx, |project, cx| {
10342                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10343                });
10344            })
10345        }
10346    }
10347
10348    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10349        cx.show_character_palette();
10350    }
10351
10352    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10353        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10354            let buffer = self.buffer.read(cx).snapshot(cx);
10355            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10356            let is_valid = buffer
10357                .diagnostics_in_range(active_diagnostics.primary_range.clone(), false)
10358                .any(|entry| {
10359                    let range = entry.range.to_offset(&buffer);
10360                    entry.diagnostic.is_primary
10361                        && !range.is_empty()
10362                        && range.start == primary_range_start
10363                        && entry.diagnostic.message == active_diagnostics.primary_message
10364                });
10365
10366            if is_valid != active_diagnostics.is_valid {
10367                active_diagnostics.is_valid = is_valid;
10368                let mut new_styles = HashMap::default();
10369                for (block_id, diagnostic) in &active_diagnostics.blocks {
10370                    new_styles.insert(
10371                        *block_id,
10372                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10373                    );
10374                }
10375                self.display_map.update(cx, |display_map, _cx| {
10376                    display_map.replace_blocks(new_styles)
10377                });
10378            }
10379        }
10380    }
10381
10382    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
10383        self.dismiss_diagnostics(cx);
10384        let snapshot = self.snapshot(cx);
10385        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10386            let buffer = self.buffer.read(cx).snapshot(cx);
10387
10388            let mut primary_range = None;
10389            let mut primary_message = None;
10390            let mut group_end = Point::zero();
10391            let diagnostic_group = buffer
10392                .diagnostic_group(group_id)
10393                .filter_map(|entry| {
10394                    let start = entry.range.start.to_point(&buffer);
10395                    let end = entry.range.end.to_point(&buffer);
10396                    if snapshot.is_line_folded(MultiBufferRow(start.row))
10397                        && (start.row == end.row
10398                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
10399                    {
10400                        return None;
10401                    }
10402                    if end > group_end {
10403                        group_end = end;
10404                    }
10405                    if entry.diagnostic.is_primary {
10406                        primary_range = Some(entry.range.clone());
10407                        primary_message = Some(entry.diagnostic.message.clone());
10408                    }
10409                    Some(entry)
10410                })
10411                .collect::<Vec<_>>();
10412            let primary_range = primary_range?;
10413            let primary_message = primary_message?;
10414
10415            let blocks = display_map
10416                .insert_blocks(
10417                    diagnostic_group.iter().map(|entry| {
10418                        let diagnostic = entry.diagnostic.clone();
10419                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10420                        BlockProperties {
10421                            style: BlockStyle::Fixed,
10422                            placement: BlockPlacement::Below(
10423                                buffer.anchor_after(entry.range.start),
10424                            ),
10425                            height: message_height,
10426                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10427                            priority: 0,
10428                        }
10429                    }),
10430                    cx,
10431                )
10432                .into_iter()
10433                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10434                .collect();
10435
10436            Some(ActiveDiagnosticGroup {
10437                primary_range,
10438                primary_message,
10439                group_id,
10440                blocks,
10441                is_valid: true,
10442            })
10443        });
10444    }
10445
10446    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10447        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10448            self.display_map.update(cx, |display_map, cx| {
10449                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10450            });
10451            cx.notify();
10452        }
10453    }
10454
10455    pub fn set_selections_from_remote(
10456        &mut self,
10457        selections: Vec<Selection<Anchor>>,
10458        pending_selection: Option<Selection<Anchor>>,
10459        cx: &mut ViewContext<Self>,
10460    ) {
10461        let old_cursor_position = self.selections.newest_anchor().head();
10462        self.selections.change_with(cx, |s| {
10463            s.select_anchors(selections);
10464            if let Some(pending_selection) = pending_selection {
10465                s.set_pending(pending_selection, SelectMode::Character);
10466            } else {
10467                s.clear_pending();
10468            }
10469        });
10470        self.selections_did_change(false, &old_cursor_position, true, cx);
10471    }
10472
10473    fn push_to_selection_history(&mut self) {
10474        self.selection_history.push(SelectionHistoryEntry {
10475            selections: self.selections.disjoint_anchors(),
10476            select_next_state: self.select_next_state.clone(),
10477            select_prev_state: self.select_prev_state.clone(),
10478            add_selections_state: self.add_selections_state.clone(),
10479        });
10480    }
10481
10482    pub fn transact(
10483        &mut self,
10484        cx: &mut ViewContext<Self>,
10485        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10486    ) -> Option<TransactionId> {
10487        self.start_transaction_at(Instant::now(), cx);
10488        update(self, cx);
10489        self.end_transaction_at(Instant::now(), cx)
10490    }
10491
10492    pub fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10493        self.end_selection(cx);
10494        if let Some(tx_id) = self
10495            .buffer
10496            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10497        {
10498            self.selection_history
10499                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10500            cx.emit(EditorEvent::TransactionBegun {
10501                transaction_id: tx_id,
10502            })
10503        }
10504    }
10505
10506    pub fn end_transaction_at(
10507        &mut self,
10508        now: Instant,
10509        cx: &mut ViewContext<Self>,
10510    ) -> Option<TransactionId> {
10511        if let Some(transaction_id) = self
10512            .buffer
10513            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10514        {
10515            if let Some((_, end_selections)) =
10516                self.selection_history.transaction_mut(transaction_id)
10517            {
10518                *end_selections = Some(self.selections.disjoint_anchors());
10519            } else {
10520                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10521            }
10522
10523            cx.emit(EditorEvent::Edited { transaction_id });
10524            Some(transaction_id)
10525        } else {
10526            None
10527        }
10528    }
10529
10530    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10531        if self.is_singleton(cx) {
10532            let selection = self.selections.newest::<Point>(cx);
10533
10534            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10535            let range = if selection.is_empty() {
10536                let point = selection.head().to_display_point(&display_map);
10537                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10538                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10539                    .to_point(&display_map);
10540                start..end
10541            } else {
10542                selection.range()
10543            };
10544            if display_map.folds_in_range(range).next().is_some() {
10545                self.unfold_lines(&Default::default(), cx)
10546            } else {
10547                self.fold(&Default::default(), cx)
10548            }
10549        } else {
10550            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10551            let mut toggled_buffers = HashSet::default();
10552            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10553                self.selections
10554                    .disjoint_anchors()
10555                    .into_iter()
10556                    .map(|selection| selection.range()),
10557            ) {
10558                let buffer_id = buffer_snapshot.remote_id();
10559                if toggled_buffers.insert(buffer_id) {
10560                    if self.buffer_folded(buffer_id, cx) {
10561                        self.unfold_buffer(buffer_id, cx);
10562                    } else {
10563                        self.fold_buffer(buffer_id, cx);
10564                    }
10565                }
10566            }
10567        }
10568    }
10569
10570    pub fn toggle_fold_recursive(
10571        &mut self,
10572        _: &actions::ToggleFoldRecursive,
10573        cx: &mut ViewContext<Self>,
10574    ) {
10575        let selection = self.selections.newest::<Point>(cx);
10576
10577        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10578        let range = if selection.is_empty() {
10579            let point = selection.head().to_display_point(&display_map);
10580            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10581            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10582                .to_point(&display_map);
10583            start..end
10584        } else {
10585            selection.range()
10586        };
10587        if display_map.folds_in_range(range).next().is_some() {
10588            self.unfold_recursive(&Default::default(), cx)
10589        } else {
10590            self.fold_recursive(&Default::default(), cx)
10591        }
10592    }
10593
10594    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10595        if self.is_singleton(cx) {
10596            let mut to_fold = Vec::new();
10597            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10598            let selections = self.selections.all_adjusted(cx);
10599
10600            for selection in selections {
10601                let range = selection.range().sorted();
10602                let buffer_start_row = range.start.row;
10603
10604                if range.start.row != range.end.row {
10605                    let mut found = false;
10606                    let mut row = range.start.row;
10607                    while row <= range.end.row {
10608                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10609                        {
10610                            found = true;
10611                            row = crease.range().end.row + 1;
10612                            to_fold.push(crease);
10613                        } else {
10614                            row += 1
10615                        }
10616                    }
10617                    if found {
10618                        continue;
10619                    }
10620                }
10621
10622                for row in (0..=range.start.row).rev() {
10623                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10624                        if crease.range().end.row >= buffer_start_row {
10625                            to_fold.push(crease);
10626                            if row <= range.start.row {
10627                                break;
10628                            }
10629                        }
10630                    }
10631                }
10632            }
10633
10634            self.fold_creases(to_fold, true, cx);
10635        } else {
10636            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10637            let mut folded_buffers = HashSet::default();
10638            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10639                self.selections
10640                    .disjoint_anchors()
10641                    .into_iter()
10642                    .map(|selection| selection.range()),
10643            ) {
10644                let buffer_id = buffer_snapshot.remote_id();
10645                if folded_buffers.insert(buffer_id) {
10646                    self.fold_buffer(buffer_id, cx);
10647                }
10648            }
10649        }
10650    }
10651
10652    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10653        if !self.buffer.read(cx).is_singleton() {
10654            return;
10655        }
10656
10657        let fold_at_level = fold_at.level;
10658        let snapshot = self.buffer.read(cx).snapshot(cx);
10659        let mut to_fold = Vec::new();
10660        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10661
10662        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10663            while start_row < end_row {
10664                match self
10665                    .snapshot(cx)
10666                    .crease_for_buffer_row(MultiBufferRow(start_row))
10667                {
10668                    Some(crease) => {
10669                        let nested_start_row = crease.range().start.row + 1;
10670                        let nested_end_row = crease.range().end.row;
10671
10672                        if current_level < fold_at_level {
10673                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10674                        } else if current_level == fold_at_level {
10675                            to_fold.push(crease);
10676                        }
10677
10678                        start_row = nested_end_row + 1;
10679                    }
10680                    None => start_row += 1,
10681                }
10682            }
10683        }
10684
10685        self.fold_creases(to_fold, true, cx);
10686    }
10687
10688    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10689        if self.buffer.read(cx).is_singleton() {
10690            let mut fold_ranges = Vec::new();
10691            let snapshot = self.buffer.read(cx).snapshot(cx);
10692
10693            for row in 0..snapshot.max_row().0 {
10694                if let Some(foldable_range) =
10695                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10696                {
10697                    fold_ranges.push(foldable_range);
10698                }
10699            }
10700
10701            self.fold_creases(fold_ranges, true, cx);
10702        } else {
10703            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10704                editor
10705                    .update(&mut cx, |editor, cx| {
10706                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10707                            editor.fold_buffer(buffer_id, cx);
10708                        }
10709                    })
10710                    .ok();
10711            });
10712        }
10713    }
10714
10715    pub fn fold_function_bodies(
10716        &mut self,
10717        _: &actions::FoldFunctionBodies,
10718        cx: &mut ViewContext<Self>,
10719    ) {
10720        let snapshot = self.buffer.read(cx).snapshot(cx);
10721        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10722            return;
10723        };
10724        let creases = buffer
10725            .function_body_fold_ranges(0..buffer.len())
10726            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10727            .collect();
10728
10729        self.fold_creases(creases, true, cx);
10730    }
10731
10732    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10733        let mut to_fold = Vec::new();
10734        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10735        let selections = self.selections.all_adjusted(cx);
10736
10737        for selection in selections {
10738            let range = selection.range().sorted();
10739            let buffer_start_row = range.start.row;
10740
10741            if range.start.row != range.end.row {
10742                let mut found = false;
10743                for row in range.start.row..=range.end.row {
10744                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10745                        found = true;
10746                        to_fold.push(crease);
10747                    }
10748                }
10749                if found {
10750                    continue;
10751                }
10752            }
10753
10754            for row in (0..=range.start.row).rev() {
10755                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10756                    if crease.range().end.row >= buffer_start_row {
10757                        to_fold.push(crease);
10758                    } else {
10759                        break;
10760                    }
10761                }
10762            }
10763        }
10764
10765        self.fold_creases(to_fold, true, cx);
10766    }
10767
10768    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10769        let buffer_row = fold_at.buffer_row;
10770        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10771
10772        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10773            let autoscroll = self
10774                .selections
10775                .all::<Point>(cx)
10776                .iter()
10777                .any(|selection| crease.range().overlaps(&selection.range()));
10778
10779            self.fold_creases(vec![crease], autoscroll, cx);
10780        }
10781    }
10782
10783    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10784        if self.is_singleton(cx) {
10785            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10786            let buffer = &display_map.buffer_snapshot;
10787            let selections = self.selections.all::<Point>(cx);
10788            let ranges = selections
10789                .iter()
10790                .map(|s| {
10791                    let range = s.display_range(&display_map).sorted();
10792                    let mut start = range.start.to_point(&display_map);
10793                    let mut end = range.end.to_point(&display_map);
10794                    start.column = 0;
10795                    end.column = buffer.line_len(MultiBufferRow(end.row));
10796                    start..end
10797                })
10798                .collect::<Vec<_>>();
10799
10800            self.unfold_ranges(&ranges, true, true, cx);
10801        } else {
10802            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10803            let mut unfolded_buffers = HashSet::default();
10804            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10805                self.selections
10806                    .disjoint_anchors()
10807                    .into_iter()
10808                    .map(|selection| selection.range()),
10809            ) {
10810                let buffer_id = buffer_snapshot.remote_id();
10811                if unfolded_buffers.insert(buffer_id) {
10812                    self.unfold_buffer(buffer_id, cx);
10813                }
10814            }
10815        }
10816    }
10817
10818    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10819        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10820        let selections = self.selections.all::<Point>(cx);
10821        let ranges = selections
10822            .iter()
10823            .map(|s| {
10824                let mut range = s.display_range(&display_map).sorted();
10825                *range.start.column_mut() = 0;
10826                *range.end.column_mut() = display_map.line_len(range.end.row());
10827                let start = range.start.to_point(&display_map);
10828                let end = range.end.to_point(&display_map);
10829                start..end
10830            })
10831            .collect::<Vec<_>>();
10832
10833        self.unfold_ranges(&ranges, true, true, cx);
10834    }
10835
10836    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10837        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10838
10839        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10840            ..Point::new(
10841                unfold_at.buffer_row.0,
10842                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10843            );
10844
10845        let autoscroll = self
10846            .selections
10847            .all::<Point>(cx)
10848            .iter()
10849            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10850
10851        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10852    }
10853
10854    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10855        if self.buffer.read(cx).is_singleton() {
10856            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10857            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10858        } else {
10859            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10860                editor
10861                    .update(&mut cx, |editor, cx| {
10862                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10863                            editor.unfold_buffer(buffer_id, cx);
10864                        }
10865                    })
10866                    .ok();
10867            });
10868        }
10869    }
10870
10871    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10872        let selections = self.selections.all::<Point>(cx);
10873        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10874        let line_mode = self.selections.line_mode;
10875        let ranges = selections
10876            .into_iter()
10877            .map(|s| {
10878                if line_mode {
10879                    let start = Point::new(s.start.row, 0);
10880                    let end = Point::new(
10881                        s.end.row,
10882                        display_map
10883                            .buffer_snapshot
10884                            .line_len(MultiBufferRow(s.end.row)),
10885                    );
10886                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10887                } else {
10888                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10889                }
10890            })
10891            .collect::<Vec<_>>();
10892        self.fold_creases(ranges, true, cx);
10893    }
10894
10895    pub fn fold_creases<T: ToOffset + Clone>(
10896        &mut self,
10897        creases: Vec<Crease<T>>,
10898        auto_scroll: bool,
10899        cx: &mut ViewContext<Self>,
10900    ) {
10901        if creases.is_empty() {
10902            return;
10903        }
10904
10905        let mut buffers_affected = HashSet::default();
10906        let multi_buffer = self.buffer().read(cx);
10907        for crease in &creases {
10908            if let Some((_, buffer, _)) =
10909                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10910            {
10911                buffers_affected.insert(buffer.read(cx).remote_id());
10912            };
10913        }
10914
10915        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10916
10917        if auto_scroll {
10918            self.request_autoscroll(Autoscroll::fit(), cx);
10919        }
10920
10921        for buffer_id in buffers_affected {
10922            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10923        }
10924
10925        cx.notify();
10926
10927        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10928            // Clear diagnostics block when folding a range that contains it.
10929            let snapshot = self.snapshot(cx);
10930            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10931                drop(snapshot);
10932                self.active_diagnostics = Some(active_diagnostics);
10933                self.dismiss_diagnostics(cx);
10934            } else {
10935                self.active_diagnostics = Some(active_diagnostics);
10936            }
10937        }
10938
10939        self.scrollbar_marker_state.dirty = true;
10940    }
10941
10942    /// Removes any folds whose ranges intersect any of the given ranges.
10943    pub fn unfold_ranges<T: ToOffset + Clone>(
10944        &mut self,
10945        ranges: &[Range<T>],
10946        inclusive: bool,
10947        auto_scroll: bool,
10948        cx: &mut ViewContext<Self>,
10949    ) {
10950        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10951            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10952        });
10953    }
10954
10955    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10956        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10957            return;
10958        }
10959        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10960            return;
10961        };
10962        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10963        self.display_map
10964            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10965        cx.emit(EditorEvent::BufferFoldToggled {
10966            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10967            folded: true,
10968        });
10969        cx.notify();
10970    }
10971
10972    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10973        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10974            return;
10975        }
10976        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10977            return;
10978        };
10979        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10980        self.display_map.update(cx, |display_map, cx| {
10981            display_map.unfold_buffer(buffer_id, cx);
10982        });
10983        cx.emit(EditorEvent::BufferFoldToggled {
10984            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10985            folded: false,
10986        });
10987        cx.notify();
10988    }
10989
10990    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10991        self.display_map.read(cx).buffer_folded(buffer)
10992    }
10993
10994    /// Removes any folds with the given ranges.
10995    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10996        &mut self,
10997        ranges: &[Range<T>],
10998        type_id: TypeId,
10999        auto_scroll: bool,
11000        cx: &mut ViewContext<Self>,
11001    ) {
11002        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
11003            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
11004        });
11005    }
11006
11007    fn remove_folds_with<T: ToOffset + Clone>(
11008        &mut self,
11009        ranges: &[Range<T>],
11010        auto_scroll: bool,
11011        cx: &mut ViewContext<Self>,
11012        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
11013    ) {
11014        if ranges.is_empty() {
11015            return;
11016        }
11017
11018        let mut buffers_affected = HashSet::default();
11019        let multi_buffer = self.buffer().read(cx);
11020        for range in ranges {
11021            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
11022                buffers_affected.insert(buffer.read(cx).remote_id());
11023            };
11024        }
11025
11026        self.display_map.update(cx, update);
11027
11028        if auto_scroll {
11029            self.request_autoscroll(Autoscroll::fit(), cx);
11030        }
11031
11032        for buffer_id in buffers_affected {
11033            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
11034        }
11035
11036        cx.notify();
11037        self.scrollbar_marker_state.dirty = true;
11038        self.active_indent_guides_state.dirty = true;
11039    }
11040
11041    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
11042        self.display_map.read(cx).fold_placeholder.clone()
11043    }
11044
11045    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
11046        if hovered != self.gutter_hovered {
11047            self.gutter_hovered = hovered;
11048            cx.notify();
11049        }
11050    }
11051
11052    pub fn insert_blocks(
11053        &mut self,
11054        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11055        autoscroll: Option<Autoscroll>,
11056        cx: &mut ViewContext<Self>,
11057    ) -> Vec<CustomBlockId> {
11058        let blocks = self
11059            .display_map
11060            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11061        if let Some(autoscroll) = autoscroll {
11062            self.request_autoscroll(autoscroll, cx);
11063        }
11064        cx.notify();
11065        blocks
11066    }
11067
11068    pub fn resize_blocks(
11069        &mut self,
11070        heights: HashMap<CustomBlockId, u32>,
11071        autoscroll: Option<Autoscroll>,
11072        cx: &mut ViewContext<Self>,
11073    ) {
11074        self.display_map
11075            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11076        if let Some(autoscroll) = autoscroll {
11077            self.request_autoscroll(autoscroll, cx);
11078        }
11079        cx.notify();
11080    }
11081
11082    pub fn replace_blocks(
11083        &mut self,
11084        renderers: HashMap<CustomBlockId, RenderBlock>,
11085        autoscroll: Option<Autoscroll>,
11086        cx: &mut ViewContext<Self>,
11087    ) {
11088        self.display_map
11089            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11090        if let Some(autoscroll) = autoscroll {
11091            self.request_autoscroll(autoscroll, cx);
11092        }
11093        cx.notify();
11094    }
11095
11096    pub fn remove_blocks(
11097        &mut self,
11098        block_ids: HashSet<CustomBlockId>,
11099        autoscroll: Option<Autoscroll>,
11100        cx: &mut ViewContext<Self>,
11101    ) {
11102        self.display_map.update(cx, |display_map, cx| {
11103            display_map.remove_blocks(block_ids, cx)
11104        });
11105        if let Some(autoscroll) = autoscroll {
11106            self.request_autoscroll(autoscroll, cx);
11107        }
11108        cx.notify();
11109    }
11110
11111    pub fn row_for_block(
11112        &self,
11113        block_id: CustomBlockId,
11114        cx: &mut ViewContext<Self>,
11115    ) -> Option<DisplayRow> {
11116        self.display_map
11117            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11118    }
11119
11120    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11121        self.focused_block = Some(focused_block);
11122    }
11123
11124    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11125        self.focused_block.take()
11126    }
11127
11128    pub fn insert_creases(
11129        &mut self,
11130        creases: impl IntoIterator<Item = Crease<Anchor>>,
11131        cx: &mut ViewContext<Self>,
11132    ) -> Vec<CreaseId> {
11133        self.display_map
11134            .update(cx, |map, cx| map.insert_creases(creases, cx))
11135    }
11136
11137    pub fn remove_creases(
11138        &mut self,
11139        ids: impl IntoIterator<Item = CreaseId>,
11140        cx: &mut ViewContext<Self>,
11141    ) {
11142        self.display_map
11143            .update(cx, |map, cx| map.remove_creases(ids, cx));
11144    }
11145
11146    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11147        self.display_map
11148            .update(cx, |map, cx| map.snapshot(cx))
11149            .longest_row()
11150    }
11151
11152    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11153        self.display_map
11154            .update(cx, |map, cx| map.snapshot(cx))
11155            .max_point()
11156    }
11157
11158    pub fn text(&self, cx: &AppContext) -> String {
11159        self.buffer.read(cx).read(cx).text()
11160    }
11161
11162    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11163        let text = self.text(cx);
11164        let text = text.trim();
11165
11166        if text.is_empty() {
11167            return None;
11168        }
11169
11170        Some(text.to_string())
11171    }
11172
11173    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11174        self.transact(cx, |this, cx| {
11175            this.buffer
11176                .read(cx)
11177                .as_singleton()
11178                .expect("you can only call set_text on editors for singleton buffers")
11179                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11180        });
11181    }
11182
11183    pub fn display_text(&self, cx: &mut AppContext) -> String {
11184        self.display_map
11185            .update(cx, |map, cx| map.snapshot(cx))
11186            .text()
11187    }
11188
11189    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11190        let mut wrap_guides = smallvec::smallvec![];
11191
11192        if self.show_wrap_guides == Some(false) {
11193            return wrap_guides;
11194        }
11195
11196        let settings = self.buffer.read(cx).settings_at(0, cx);
11197        if settings.show_wrap_guides {
11198            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11199                wrap_guides.push((soft_wrap as usize, true));
11200            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11201                wrap_guides.push((soft_wrap as usize, true));
11202            }
11203            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11204        }
11205
11206        wrap_guides
11207    }
11208
11209    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11210        let settings = self.buffer.read(cx).settings_at(0, cx);
11211        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11212        match mode {
11213            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11214                SoftWrap::None
11215            }
11216            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11217            language_settings::SoftWrap::PreferredLineLength => {
11218                SoftWrap::Column(settings.preferred_line_length)
11219            }
11220            language_settings::SoftWrap::Bounded => {
11221                SoftWrap::Bounded(settings.preferred_line_length)
11222            }
11223        }
11224    }
11225
11226    pub fn set_soft_wrap_mode(
11227        &mut self,
11228        mode: language_settings::SoftWrap,
11229        cx: &mut ViewContext<Self>,
11230    ) {
11231        self.soft_wrap_mode_override = Some(mode);
11232        cx.notify();
11233    }
11234
11235    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11236        self.text_style_refinement = Some(style);
11237    }
11238
11239    /// called by the Element so we know what style we were most recently rendered with.
11240    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11241        let rem_size = cx.rem_size();
11242        self.display_map.update(cx, |map, cx| {
11243            map.set_font(
11244                style.text.font(),
11245                style.text.font_size.to_pixels(rem_size),
11246                cx,
11247            )
11248        });
11249        self.style = Some(style);
11250    }
11251
11252    pub fn style(&self) -> Option<&EditorStyle> {
11253        self.style.as_ref()
11254    }
11255
11256    // Called by the element. This method is not designed to be called outside of the editor
11257    // element's layout code because it does not notify when rewrapping is computed synchronously.
11258    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11259        self.display_map
11260            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11261    }
11262
11263    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11264        if self.soft_wrap_mode_override.is_some() {
11265            self.soft_wrap_mode_override.take();
11266        } else {
11267            let soft_wrap = match self.soft_wrap_mode(cx) {
11268                SoftWrap::GitDiff => return,
11269                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11270                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11271                    language_settings::SoftWrap::None
11272                }
11273            };
11274            self.soft_wrap_mode_override = Some(soft_wrap);
11275        }
11276        cx.notify();
11277    }
11278
11279    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11280        let Some(workspace) = self.workspace() else {
11281            return;
11282        };
11283        let fs = workspace.read(cx).app_state().fs.clone();
11284        let current_show = TabBarSettings::get_global(cx).show;
11285        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11286            setting.show = Some(!current_show);
11287        });
11288    }
11289
11290    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11291        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11292            self.buffer
11293                .read(cx)
11294                .settings_at(0, cx)
11295                .indent_guides
11296                .enabled
11297        });
11298        self.show_indent_guides = Some(!currently_enabled);
11299        cx.notify();
11300    }
11301
11302    fn should_show_indent_guides(&self) -> Option<bool> {
11303        self.show_indent_guides
11304    }
11305
11306    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11307        let mut editor_settings = EditorSettings::get_global(cx).clone();
11308        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11309        EditorSettings::override_global(editor_settings, cx);
11310    }
11311
11312    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11313        self.use_relative_line_numbers
11314            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11315    }
11316
11317    pub fn toggle_relative_line_numbers(
11318        &mut self,
11319        _: &ToggleRelativeLineNumbers,
11320        cx: &mut ViewContext<Self>,
11321    ) {
11322        let is_relative = self.should_use_relative_line_numbers(cx);
11323        self.set_relative_line_number(Some(!is_relative), cx)
11324    }
11325
11326    pub fn set_relative_line_number(
11327        &mut self,
11328        is_relative: Option<bool>,
11329        cx: &mut ViewContext<Self>,
11330    ) {
11331        self.use_relative_line_numbers = is_relative;
11332        cx.notify();
11333    }
11334
11335    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11336        self.show_gutter = show_gutter;
11337        cx.notify();
11338    }
11339
11340    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut ViewContext<Self>) {
11341        self.show_scrollbars = show_scrollbars;
11342        cx.notify();
11343    }
11344
11345    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11346        self.show_line_numbers = Some(show_line_numbers);
11347        cx.notify();
11348    }
11349
11350    pub fn set_show_git_diff_gutter(
11351        &mut self,
11352        show_git_diff_gutter: bool,
11353        cx: &mut ViewContext<Self>,
11354    ) {
11355        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11356        cx.notify();
11357    }
11358
11359    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11360        self.show_code_actions = Some(show_code_actions);
11361        cx.notify();
11362    }
11363
11364    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11365        self.show_runnables = Some(show_runnables);
11366        cx.notify();
11367    }
11368
11369    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11370        if self.display_map.read(cx).masked != masked {
11371            self.display_map.update(cx, |map, _| map.masked = masked);
11372        }
11373        cx.notify()
11374    }
11375
11376    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11377        self.show_wrap_guides = Some(show_wrap_guides);
11378        cx.notify();
11379    }
11380
11381    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11382        self.show_indent_guides = Some(show_indent_guides);
11383        cx.notify();
11384    }
11385
11386    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11387        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11388            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11389                if let Some(dir) = file.abs_path(cx).parent() {
11390                    return Some(dir.to_owned());
11391                }
11392            }
11393
11394            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11395                return Some(project_path.path.to_path_buf());
11396            }
11397        }
11398
11399        None
11400    }
11401
11402    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11403        self.active_excerpt(cx)?
11404            .1
11405            .read(cx)
11406            .file()
11407            .and_then(|f| f.as_local())
11408    }
11409
11410    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11411        if let Some(target) = self.target_file(cx) {
11412            cx.reveal_path(&target.abs_path(cx));
11413        }
11414    }
11415
11416    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11417        if let Some(file) = self.target_file(cx) {
11418            if let Some(path) = file.abs_path(cx).to_str() {
11419                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11420            }
11421        }
11422    }
11423
11424    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11425        if let Some(file) = self.target_file(cx) {
11426            if let Some(path) = file.path().to_str() {
11427                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11428            }
11429        }
11430    }
11431
11432    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11433        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11434
11435        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11436            self.start_git_blame(true, cx);
11437        }
11438
11439        cx.notify();
11440    }
11441
11442    pub fn toggle_git_blame_inline(
11443        &mut self,
11444        _: &ToggleGitBlameInline,
11445        cx: &mut ViewContext<Self>,
11446    ) {
11447        self.toggle_git_blame_inline_internal(true, cx);
11448        cx.notify();
11449    }
11450
11451    pub fn git_blame_inline_enabled(&self) -> bool {
11452        self.git_blame_inline_enabled
11453    }
11454
11455    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11456        self.show_selection_menu = self
11457            .show_selection_menu
11458            .map(|show_selections_menu| !show_selections_menu)
11459            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11460
11461        cx.notify();
11462    }
11463
11464    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11465        self.show_selection_menu
11466            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11467    }
11468
11469    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11470        if let Some(project) = self.project.as_ref() {
11471            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11472                return;
11473            };
11474
11475            if buffer.read(cx).file().is_none() {
11476                return;
11477            }
11478
11479            let focused = self.focus_handle(cx).contains_focused(cx);
11480
11481            let project = project.clone();
11482            let blame =
11483                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11484            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11485            self.blame = Some(blame);
11486        }
11487    }
11488
11489    fn toggle_git_blame_inline_internal(
11490        &mut self,
11491        user_triggered: bool,
11492        cx: &mut ViewContext<Self>,
11493    ) {
11494        if self.git_blame_inline_enabled {
11495            self.git_blame_inline_enabled = false;
11496            self.show_git_blame_inline = false;
11497            self.show_git_blame_inline_delay_task.take();
11498        } else {
11499            self.git_blame_inline_enabled = true;
11500            self.start_git_blame_inline(user_triggered, cx);
11501        }
11502
11503        cx.notify();
11504    }
11505
11506    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11507        self.start_git_blame(user_triggered, cx);
11508
11509        if ProjectSettings::get_global(cx)
11510            .git
11511            .inline_blame_delay()
11512            .is_some()
11513        {
11514            self.start_inline_blame_timer(cx);
11515        } else {
11516            self.show_git_blame_inline = true
11517        }
11518    }
11519
11520    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11521        self.blame.as_ref()
11522    }
11523
11524    pub fn show_git_blame_gutter(&self) -> bool {
11525        self.show_git_blame_gutter
11526    }
11527
11528    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11529        self.show_git_blame_gutter && self.has_blame_entries(cx)
11530    }
11531
11532    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11533        self.show_git_blame_inline
11534            && self.focus_handle.is_focused(cx)
11535            && !self.newest_selection_head_on_empty_line(cx)
11536            && self.has_blame_entries(cx)
11537    }
11538
11539    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11540        self.blame()
11541            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11542    }
11543
11544    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11545        let cursor_anchor = self.selections.newest_anchor().head();
11546
11547        let snapshot = self.buffer.read(cx).snapshot(cx);
11548        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11549
11550        snapshot.line_len(buffer_row) == 0
11551    }
11552
11553    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11554        let buffer_and_selection = maybe!({
11555            let selection = self.selections.newest::<Point>(cx);
11556            let selection_range = selection.range();
11557
11558            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11559                (buffer, selection_range.start.row..selection_range.end.row)
11560            } else {
11561                let multi_buffer = self.buffer().read(cx);
11562                let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11563                let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
11564
11565                let (excerpt, range) = if selection.reversed {
11566                    buffer_ranges.first()
11567                } else {
11568                    buffer_ranges.last()
11569                }?;
11570
11571                let snapshot = excerpt.buffer();
11572                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11573                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11574                (
11575                    multi_buffer.buffer(excerpt.buffer_id()).unwrap().clone(),
11576                    selection,
11577                )
11578            };
11579
11580            Some((buffer, selection))
11581        });
11582
11583        let Some((buffer, selection)) = buffer_and_selection else {
11584            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11585        };
11586
11587        let Some(project) = self.project.as_ref() else {
11588            return Task::ready(Err(anyhow!("editor does not have project")));
11589        };
11590
11591        project.update(cx, |project, cx| {
11592            project.get_permalink_to_line(&buffer, selection, cx)
11593        })
11594    }
11595
11596    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11597        let permalink_task = self.get_permalink_to_line(cx);
11598        let workspace = self.workspace();
11599
11600        cx.spawn(|_, mut cx| async move {
11601            match permalink_task.await {
11602                Ok(permalink) => {
11603                    cx.update(|cx| {
11604                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11605                    })
11606                    .ok();
11607                }
11608                Err(err) => {
11609                    let message = format!("Failed to copy permalink: {err}");
11610
11611                    Err::<(), anyhow::Error>(err).log_err();
11612
11613                    if let Some(workspace) = workspace {
11614                        workspace
11615                            .update(&mut cx, |workspace, cx| {
11616                                struct CopyPermalinkToLine;
11617
11618                                workspace.show_toast(
11619                                    Toast::new(
11620                                        NotificationId::unique::<CopyPermalinkToLine>(),
11621                                        message,
11622                                    ),
11623                                    cx,
11624                                )
11625                            })
11626                            .ok();
11627                    }
11628                }
11629            }
11630        })
11631        .detach();
11632    }
11633
11634    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11635        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11636        if let Some(file) = self.target_file(cx) {
11637            if let Some(path) = file.path().to_str() {
11638                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11639            }
11640        }
11641    }
11642
11643    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11644        let permalink_task = self.get_permalink_to_line(cx);
11645        let workspace = self.workspace();
11646
11647        cx.spawn(|_, mut cx| async move {
11648            match permalink_task.await {
11649                Ok(permalink) => {
11650                    cx.update(|cx| {
11651                        cx.open_url(permalink.as_ref());
11652                    })
11653                    .ok();
11654                }
11655                Err(err) => {
11656                    let message = format!("Failed to open permalink: {err}");
11657
11658                    Err::<(), anyhow::Error>(err).log_err();
11659
11660                    if let Some(workspace) = workspace {
11661                        workspace
11662                            .update(&mut cx, |workspace, cx| {
11663                                struct OpenPermalinkToLine;
11664
11665                                workspace.show_toast(
11666                                    Toast::new(
11667                                        NotificationId::unique::<OpenPermalinkToLine>(),
11668                                        message,
11669                                    ),
11670                                    cx,
11671                                )
11672                            })
11673                            .ok();
11674                    }
11675                }
11676            }
11677        })
11678        .detach();
11679    }
11680
11681    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11682        self.insert_uuid(UuidVersion::V4, cx);
11683    }
11684
11685    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11686        self.insert_uuid(UuidVersion::V7, cx);
11687    }
11688
11689    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11690        self.transact(cx, |this, cx| {
11691            let edits = this
11692                .selections
11693                .all::<Point>(cx)
11694                .into_iter()
11695                .map(|selection| {
11696                    let uuid = match version {
11697                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11698                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11699                    };
11700
11701                    (selection.range(), uuid.to_string())
11702                });
11703            this.edit(edits, cx);
11704            this.refresh_inline_completion(true, false, cx);
11705        });
11706    }
11707
11708    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11709    /// last highlight added will be used.
11710    ///
11711    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11712    pub fn highlight_rows<T: 'static>(
11713        &mut self,
11714        range: Range<Anchor>,
11715        color: Hsla,
11716        should_autoscroll: bool,
11717        cx: &mut ViewContext<Self>,
11718    ) {
11719        let snapshot = self.buffer().read(cx).snapshot(cx);
11720        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11721        let ix = row_highlights.binary_search_by(|highlight| {
11722            Ordering::Equal
11723                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11724                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11725        });
11726
11727        if let Err(mut ix) = ix {
11728            let index = post_inc(&mut self.highlight_order);
11729
11730            // If this range intersects with the preceding highlight, then merge it with
11731            // the preceding highlight. Otherwise insert a new highlight.
11732            let mut merged = false;
11733            if ix > 0 {
11734                let prev_highlight = &mut row_highlights[ix - 1];
11735                if prev_highlight
11736                    .range
11737                    .end
11738                    .cmp(&range.start, &snapshot)
11739                    .is_ge()
11740                {
11741                    ix -= 1;
11742                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11743                        prev_highlight.range.end = range.end;
11744                    }
11745                    merged = true;
11746                    prev_highlight.index = index;
11747                    prev_highlight.color = color;
11748                    prev_highlight.should_autoscroll = should_autoscroll;
11749                }
11750            }
11751
11752            if !merged {
11753                row_highlights.insert(
11754                    ix,
11755                    RowHighlight {
11756                        range: range.clone(),
11757                        index,
11758                        color,
11759                        should_autoscroll,
11760                    },
11761                );
11762            }
11763
11764            // If any of the following highlights intersect with this one, merge them.
11765            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11766                let highlight = &row_highlights[ix];
11767                if next_highlight
11768                    .range
11769                    .start
11770                    .cmp(&highlight.range.end, &snapshot)
11771                    .is_le()
11772                {
11773                    if next_highlight
11774                        .range
11775                        .end
11776                        .cmp(&highlight.range.end, &snapshot)
11777                        .is_gt()
11778                    {
11779                        row_highlights[ix].range.end = next_highlight.range.end;
11780                    }
11781                    row_highlights.remove(ix + 1);
11782                } else {
11783                    break;
11784                }
11785            }
11786        }
11787    }
11788
11789    /// Remove any highlighted row ranges of the given type that intersect the
11790    /// given ranges.
11791    pub fn remove_highlighted_rows<T: 'static>(
11792        &mut self,
11793        ranges_to_remove: Vec<Range<Anchor>>,
11794        cx: &mut ViewContext<Self>,
11795    ) {
11796        let snapshot = self.buffer().read(cx).snapshot(cx);
11797        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11798        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11799        row_highlights.retain(|highlight| {
11800            while let Some(range_to_remove) = ranges_to_remove.peek() {
11801                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11802                    Ordering::Less | Ordering::Equal => {
11803                        ranges_to_remove.next();
11804                    }
11805                    Ordering::Greater => {
11806                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11807                            Ordering::Less | Ordering::Equal => {
11808                                return false;
11809                            }
11810                            Ordering::Greater => break,
11811                        }
11812                    }
11813                }
11814            }
11815
11816            true
11817        })
11818    }
11819
11820    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11821    pub fn clear_row_highlights<T: 'static>(&mut self) {
11822        self.highlighted_rows.remove(&TypeId::of::<T>());
11823    }
11824
11825    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11826    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11827        self.highlighted_rows
11828            .get(&TypeId::of::<T>())
11829            .map_or(&[] as &[_], |vec| vec.as_slice())
11830            .iter()
11831            .map(|highlight| (highlight.range.clone(), highlight.color))
11832    }
11833
11834    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11835    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
11836    /// Allows to ignore certain kinds of highlights.
11837    pub fn highlighted_display_rows(
11838        &mut self,
11839        cx: &mut WindowContext,
11840    ) -> BTreeMap<DisplayRow, Hsla> {
11841        let snapshot = self.snapshot(cx);
11842        let mut used_highlight_orders = HashMap::default();
11843        self.highlighted_rows
11844            .iter()
11845            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11846            .fold(
11847                BTreeMap::<DisplayRow, Hsla>::new(),
11848                |mut unique_rows, highlight| {
11849                    let start = highlight.range.start.to_display_point(&snapshot);
11850                    let end = highlight.range.end.to_display_point(&snapshot);
11851                    let start_row = start.row().0;
11852                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11853                        && end.column() == 0
11854                    {
11855                        end.row().0.saturating_sub(1)
11856                    } else {
11857                        end.row().0
11858                    };
11859                    for row in start_row..=end_row {
11860                        let used_index =
11861                            used_highlight_orders.entry(row).or_insert(highlight.index);
11862                        if highlight.index >= *used_index {
11863                            *used_index = highlight.index;
11864                            unique_rows.insert(DisplayRow(row), highlight.color);
11865                        }
11866                    }
11867                    unique_rows
11868                },
11869            )
11870    }
11871
11872    pub fn highlighted_display_row_for_autoscroll(
11873        &self,
11874        snapshot: &DisplaySnapshot,
11875    ) -> Option<DisplayRow> {
11876        self.highlighted_rows
11877            .values()
11878            .flat_map(|highlighted_rows| highlighted_rows.iter())
11879            .filter_map(|highlight| {
11880                if highlight.should_autoscroll {
11881                    Some(highlight.range.start.to_display_point(snapshot).row())
11882                } else {
11883                    None
11884                }
11885            })
11886            .min()
11887    }
11888
11889    pub fn set_search_within_ranges(
11890        &mut self,
11891        ranges: &[Range<Anchor>],
11892        cx: &mut ViewContext<Self>,
11893    ) {
11894        self.highlight_background::<SearchWithinRange>(
11895            ranges,
11896            |colors| colors.editor_document_highlight_read_background,
11897            cx,
11898        )
11899    }
11900
11901    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11902        self.breadcrumb_header = Some(new_header);
11903    }
11904
11905    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11906        self.clear_background_highlights::<SearchWithinRange>(cx);
11907    }
11908
11909    pub fn highlight_background<T: 'static>(
11910        &mut self,
11911        ranges: &[Range<Anchor>],
11912        color_fetcher: fn(&ThemeColors) -> Hsla,
11913        cx: &mut ViewContext<Self>,
11914    ) {
11915        self.background_highlights
11916            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11917        self.scrollbar_marker_state.dirty = true;
11918        cx.notify();
11919    }
11920
11921    pub fn clear_background_highlights<T: 'static>(
11922        &mut self,
11923        cx: &mut ViewContext<Self>,
11924    ) -> Option<BackgroundHighlight> {
11925        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11926        if !text_highlights.1.is_empty() {
11927            self.scrollbar_marker_state.dirty = true;
11928            cx.notify();
11929        }
11930        Some(text_highlights)
11931    }
11932
11933    pub fn highlight_gutter<T: 'static>(
11934        &mut self,
11935        ranges: &[Range<Anchor>],
11936        color_fetcher: fn(&AppContext) -> Hsla,
11937        cx: &mut ViewContext<Self>,
11938    ) {
11939        self.gutter_highlights
11940            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11941        cx.notify();
11942    }
11943
11944    pub fn clear_gutter_highlights<T: 'static>(
11945        &mut self,
11946        cx: &mut ViewContext<Self>,
11947    ) -> Option<GutterHighlight> {
11948        cx.notify();
11949        self.gutter_highlights.remove(&TypeId::of::<T>())
11950    }
11951
11952    #[cfg(feature = "test-support")]
11953    pub fn all_text_background_highlights(
11954        &mut self,
11955        cx: &mut ViewContext<Self>,
11956    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11957        let snapshot = self.snapshot(cx);
11958        let buffer = &snapshot.buffer_snapshot;
11959        let start = buffer.anchor_before(0);
11960        let end = buffer.anchor_after(buffer.len());
11961        let theme = cx.theme().colors();
11962        self.background_highlights_in_range(start..end, &snapshot, theme)
11963    }
11964
11965    #[cfg(feature = "test-support")]
11966    pub fn search_background_highlights(
11967        &mut self,
11968        cx: &mut ViewContext<Self>,
11969    ) -> Vec<Range<Point>> {
11970        let snapshot = self.buffer().read(cx).snapshot(cx);
11971
11972        let highlights = self
11973            .background_highlights
11974            .get(&TypeId::of::<items::BufferSearchHighlights>());
11975
11976        if let Some((_color, ranges)) = highlights {
11977            ranges
11978                .iter()
11979                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11980                .collect_vec()
11981        } else {
11982            vec![]
11983        }
11984    }
11985
11986    fn document_highlights_for_position<'a>(
11987        &'a self,
11988        position: Anchor,
11989        buffer: &'a MultiBufferSnapshot,
11990    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11991        let read_highlights = self
11992            .background_highlights
11993            .get(&TypeId::of::<DocumentHighlightRead>())
11994            .map(|h| &h.1);
11995        let write_highlights = self
11996            .background_highlights
11997            .get(&TypeId::of::<DocumentHighlightWrite>())
11998            .map(|h| &h.1);
11999        let left_position = position.bias_left(buffer);
12000        let right_position = position.bias_right(buffer);
12001        read_highlights
12002            .into_iter()
12003            .chain(write_highlights)
12004            .flat_map(move |ranges| {
12005                let start_ix = match ranges.binary_search_by(|probe| {
12006                    let cmp = probe.end.cmp(&left_position, buffer);
12007                    if cmp.is_ge() {
12008                        Ordering::Greater
12009                    } else {
12010                        Ordering::Less
12011                    }
12012                }) {
12013                    Ok(i) | Err(i) => i,
12014                };
12015
12016                ranges[start_ix..]
12017                    .iter()
12018                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
12019            })
12020    }
12021
12022    pub fn has_background_highlights<T: 'static>(&self) -> bool {
12023        self.background_highlights
12024            .get(&TypeId::of::<T>())
12025            .map_or(false, |(_, highlights)| !highlights.is_empty())
12026    }
12027
12028    pub fn background_highlights_in_range(
12029        &self,
12030        search_range: Range<Anchor>,
12031        display_snapshot: &DisplaySnapshot,
12032        theme: &ThemeColors,
12033    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12034        let mut results = Vec::new();
12035        for (color_fetcher, ranges) in self.background_highlights.values() {
12036            let color = color_fetcher(theme);
12037            let start_ix = match ranges.binary_search_by(|probe| {
12038                let cmp = probe
12039                    .end
12040                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12041                if cmp.is_gt() {
12042                    Ordering::Greater
12043                } else {
12044                    Ordering::Less
12045                }
12046            }) {
12047                Ok(i) | Err(i) => i,
12048            };
12049            for range in &ranges[start_ix..] {
12050                if range
12051                    .start
12052                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12053                    .is_ge()
12054                {
12055                    break;
12056                }
12057
12058                let start = range.start.to_display_point(display_snapshot);
12059                let end = range.end.to_display_point(display_snapshot);
12060                results.push((start..end, color))
12061            }
12062        }
12063        results
12064    }
12065
12066    pub fn background_highlight_row_ranges<T: 'static>(
12067        &self,
12068        search_range: Range<Anchor>,
12069        display_snapshot: &DisplaySnapshot,
12070        count: usize,
12071    ) -> Vec<RangeInclusive<DisplayPoint>> {
12072        let mut results = Vec::new();
12073        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
12074            return vec![];
12075        };
12076
12077        let start_ix = match ranges.binary_search_by(|probe| {
12078            let cmp = probe
12079                .end
12080                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12081            if cmp.is_gt() {
12082                Ordering::Greater
12083            } else {
12084                Ordering::Less
12085            }
12086        }) {
12087            Ok(i) | Err(i) => i,
12088        };
12089        let mut push_region = |start: Option<Point>, end: Option<Point>| {
12090            if let (Some(start_display), Some(end_display)) = (start, end) {
12091                results.push(
12092                    start_display.to_display_point(display_snapshot)
12093                        ..=end_display.to_display_point(display_snapshot),
12094                );
12095            }
12096        };
12097        let mut start_row: Option<Point> = None;
12098        let mut end_row: Option<Point> = None;
12099        if ranges.len() > count {
12100            return Vec::new();
12101        }
12102        for range in &ranges[start_ix..] {
12103            if range
12104                .start
12105                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12106                .is_ge()
12107            {
12108                break;
12109            }
12110            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12111            if let Some(current_row) = &end_row {
12112                if end.row == current_row.row {
12113                    continue;
12114                }
12115            }
12116            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12117            if start_row.is_none() {
12118                assert_eq!(end_row, None);
12119                start_row = Some(start);
12120                end_row = Some(end);
12121                continue;
12122            }
12123            if let Some(current_end) = end_row.as_mut() {
12124                if start.row > current_end.row + 1 {
12125                    push_region(start_row, end_row);
12126                    start_row = Some(start);
12127                    end_row = Some(end);
12128                } else {
12129                    // Merge two hunks.
12130                    *current_end = end;
12131                }
12132            } else {
12133                unreachable!();
12134            }
12135        }
12136        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12137        push_region(start_row, end_row);
12138        results
12139    }
12140
12141    pub fn gutter_highlights_in_range(
12142        &self,
12143        search_range: Range<Anchor>,
12144        display_snapshot: &DisplaySnapshot,
12145        cx: &AppContext,
12146    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12147        let mut results = Vec::new();
12148        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12149            let color = color_fetcher(cx);
12150            let start_ix = match ranges.binary_search_by(|probe| {
12151                let cmp = probe
12152                    .end
12153                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12154                if cmp.is_gt() {
12155                    Ordering::Greater
12156                } else {
12157                    Ordering::Less
12158                }
12159            }) {
12160                Ok(i) | Err(i) => i,
12161            };
12162            for range in &ranges[start_ix..] {
12163                if range
12164                    .start
12165                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12166                    .is_ge()
12167                {
12168                    break;
12169                }
12170
12171                let start = range.start.to_display_point(display_snapshot);
12172                let end = range.end.to_display_point(display_snapshot);
12173                results.push((start..end, color))
12174            }
12175        }
12176        results
12177    }
12178
12179    /// Get the text ranges corresponding to the redaction query
12180    pub fn redacted_ranges(
12181        &self,
12182        search_range: Range<Anchor>,
12183        display_snapshot: &DisplaySnapshot,
12184        cx: &WindowContext,
12185    ) -> Vec<Range<DisplayPoint>> {
12186        display_snapshot
12187            .buffer_snapshot
12188            .redacted_ranges(search_range, |file| {
12189                if let Some(file) = file {
12190                    file.is_private()
12191                        && EditorSettings::get(
12192                            Some(SettingsLocation {
12193                                worktree_id: file.worktree_id(cx),
12194                                path: file.path().as_ref(),
12195                            }),
12196                            cx,
12197                        )
12198                        .redact_private_values
12199                } else {
12200                    false
12201                }
12202            })
12203            .map(|range| {
12204                range.start.to_display_point(display_snapshot)
12205                    ..range.end.to_display_point(display_snapshot)
12206            })
12207            .collect()
12208    }
12209
12210    pub fn highlight_text<T: 'static>(
12211        &mut self,
12212        ranges: Vec<Range<Anchor>>,
12213        style: HighlightStyle,
12214        cx: &mut ViewContext<Self>,
12215    ) {
12216        self.display_map.update(cx, |map, _| {
12217            map.highlight_text(TypeId::of::<T>(), ranges, style)
12218        });
12219        cx.notify();
12220    }
12221
12222    pub(crate) fn highlight_inlays<T: 'static>(
12223        &mut self,
12224        highlights: Vec<InlayHighlight>,
12225        style: HighlightStyle,
12226        cx: &mut ViewContext<Self>,
12227    ) {
12228        self.display_map.update(cx, |map, _| {
12229            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12230        });
12231        cx.notify();
12232    }
12233
12234    pub fn text_highlights<'a, T: 'static>(
12235        &'a self,
12236        cx: &'a AppContext,
12237    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12238        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12239    }
12240
12241    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12242        let cleared = self
12243            .display_map
12244            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12245        if cleared {
12246            cx.notify();
12247        }
12248    }
12249
12250    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12251        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12252            && self.focus_handle.is_focused(cx)
12253    }
12254
12255    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12256        self.show_cursor_when_unfocused = is_enabled;
12257        cx.notify();
12258    }
12259
12260    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12261        self.project
12262            .as_ref()
12263            .map(|project| project.read(cx).lsp_store())
12264    }
12265
12266    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12267        cx.notify();
12268    }
12269
12270    fn on_buffer_event(
12271        &mut self,
12272        multibuffer: Model<MultiBuffer>,
12273        event: &multi_buffer::Event,
12274        cx: &mut ViewContext<Self>,
12275    ) {
12276        match event {
12277            multi_buffer::Event::Edited {
12278                singleton_buffer_edited,
12279                edited_buffer: buffer_edited,
12280            } => {
12281                self.scrollbar_marker_state.dirty = true;
12282                self.active_indent_guides_state.dirty = true;
12283                self.refresh_active_diagnostics(cx);
12284                self.refresh_code_actions(cx);
12285                if self.has_active_inline_completion() {
12286                    self.update_visible_inline_completion(cx);
12287                }
12288                if let Some(buffer) = buffer_edited {
12289                    let buffer_id = buffer.read(cx).remote_id();
12290                    if !self.registered_buffers.contains_key(&buffer_id) {
12291                        if let Some(lsp_store) = self.lsp_store(cx) {
12292                            lsp_store.update(cx, |lsp_store, cx| {
12293                                self.registered_buffers.insert(
12294                                    buffer_id,
12295                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12296                                );
12297                            })
12298                        }
12299                    }
12300                }
12301                cx.emit(EditorEvent::BufferEdited);
12302                cx.emit(SearchEvent::MatchesInvalidated);
12303                if *singleton_buffer_edited {
12304                    if let Some(project) = &self.project {
12305                        let project = project.read(cx);
12306                        #[allow(clippy::mutable_key_type)]
12307                        let languages_affected = multibuffer
12308                            .read(cx)
12309                            .all_buffers()
12310                            .into_iter()
12311                            .filter_map(|buffer| {
12312                                let buffer = buffer.read(cx);
12313                                let language = buffer.language()?;
12314                                if project.is_local()
12315                                    && project
12316                                        .language_servers_for_local_buffer(buffer, cx)
12317                                        .count()
12318                                        == 0
12319                                {
12320                                    None
12321                                } else {
12322                                    Some(language)
12323                                }
12324                            })
12325                            .cloned()
12326                            .collect::<HashSet<_>>();
12327                        if !languages_affected.is_empty() {
12328                            self.refresh_inlay_hints(
12329                                InlayHintRefreshReason::BufferEdited(languages_affected),
12330                                cx,
12331                            );
12332                        }
12333                    }
12334                }
12335
12336                let Some(project) = &self.project else { return };
12337                let (telemetry, is_via_ssh) = {
12338                    let project = project.read(cx);
12339                    let telemetry = project.client().telemetry().clone();
12340                    let is_via_ssh = project.is_via_ssh();
12341                    (telemetry, is_via_ssh)
12342                };
12343                refresh_linked_ranges(self, cx);
12344                telemetry.log_edit_event("editor", is_via_ssh);
12345            }
12346            multi_buffer::Event::ExcerptsAdded {
12347                buffer,
12348                predecessor,
12349                excerpts,
12350            } => {
12351                self.tasks_update_task = Some(self.refresh_runnables(cx));
12352                let buffer_id = buffer.read(cx).remote_id();
12353                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12354                    if let Some(project) = &self.project {
12355                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12356                    }
12357                }
12358                cx.emit(EditorEvent::ExcerptsAdded {
12359                    buffer: buffer.clone(),
12360                    predecessor: *predecessor,
12361                    excerpts: excerpts.clone(),
12362                });
12363                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12364            }
12365            multi_buffer::Event::ExcerptsRemoved { ids } => {
12366                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12367                let buffer = self.buffer.read(cx);
12368                self.registered_buffers
12369                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12370                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12371            }
12372            multi_buffer::Event::ExcerptsEdited { ids } => {
12373                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12374            }
12375            multi_buffer::Event::ExcerptsExpanded { ids } => {
12376                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12377            }
12378            multi_buffer::Event::Reparsed(buffer_id) => {
12379                self.tasks_update_task = Some(self.refresh_runnables(cx));
12380
12381                cx.emit(EditorEvent::Reparsed(*buffer_id));
12382            }
12383            multi_buffer::Event::LanguageChanged(buffer_id) => {
12384                linked_editing_ranges::refresh_linked_ranges(self, cx);
12385                cx.emit(EditorEvent::Reparsed(*buffer_id));
12386                cx.notify();
12387            }
12388            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12389            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12390            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12391                cx.emit(EditorEvent::TitleChanged)
12392            }
12393            // multi_buffer::Event::DiffBaseChanged => {
12394            //     self.scrollbar_marker_state.dirty = true;
12395            //     cx.emit(EditorEvent::DiffBaseChanged);
12396            //     cx.notify();
12397            // }
12398            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12399            multi_buffer::Event::DiagnosticsUpdated => {
12400                self.refresh_active_diagnostics(cx);
12401                self.scrollbar_marker_state.dirty = true;
12402                cx.notify();
12403            }
12404            _ => {}
12405        };
12406    }
12407
12408    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12409        cx.notify();
12410    }
12411
12412    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12413        self.tasks_update_task = Some(self.refresh_runnables(cx));
12414        self.refresh_inline_completion(true, false, cx);
12415        self.refresh_inlay_hints(
12416            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12417                self.selections.newest_anchor().head(),
12418                &self.buffer.read(cx).snapshot(cx),
12419                cx,
12420            )),
12421            cx,
12422        );
12423
12424        let old_cursor_shape = self.cursor_shape;
12425
12426        {
12427            let editor_settings = EditorSettings::get_global(cx);
12428            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12429            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12430            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12431        }
12432
12433        if old_cursor_shape != self.cursor_shape {
12434            cx.emit(EditorEvent::CursorShapeChanged);
12435        }
12436
12437        let project_settings = ProjectSettings::get_global(cx);
12438        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12439
12440        if self.mode == EditorMode::Full {
12441            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12442            if self.git_blame_inline_enabled != inline_blame_enabled {
12443                self.toggle_git_blame_inline_internal(false, cx);
12444            }
12445        }
12446
12447        cx.notify();
12448    }
12449
12450    pub fn set_searchable(&mut self, searchable: bool) {
12451        self.searchable = searchable;
12452    }
12453
12454    pub fn searchable(&self) -> bool {
12455        self.searchable
12456    }
12457
12458    fn open_proposed_changes_editor(
12459        &mut self,
12460        _: &OpenProposedChangesEditor,
12461        cx: &mut ViewContext<Self>,
12462    ) {
12463        let Some(workspace) = self.workspace() else {
12464            cx.propagate();
12465            return;
12466        };
12467
12468        let selections = self.selections.all::<usize>(cx);
12469        let multi_buffer = self.buffer.read(cx);
12470        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12471        let mut new_selections_by_buffer = HashMap::default();
12472        for selection in selections {
12473            for (excerpt, range) in
12474                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
12475            {
12476                let mut range = range.to_point(excerpt.buffer());
12477                range.start.column = 0;
12478                range.end.column = excerpt.buffer().line_len(range.end.row);
12479                new_selections_by_buffer
12480                    .entry(multi_buffer.buffer(excerpt.buffer_id()).unwrap())
12481                    .or_insert(Vec::new())
12482                    .push(range)
12483            }
12484        }
12485
12486        let proposed_changes_buffers = new_selections_by_buffer
12487            .into_iter()
12488            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12489            .collect::<Vec<_>>();
12490        let proposed_changes_editor = cx.new_view(|cx| {
12491            ProposedChangesEditor::new(
12492                "Proposed changes",
12493                proposed_changes_buffers,
12494                self.project.clone(),
12495                cx,
12496            )
12497        });
12498
12499        cx.window_context().defer(move |cx| {
12500            workspace.update(cx, |workspace, cx| {
12501                workspace.active_pane().update(cx, |pane, cx| {
12502                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12503                });
12504            });
12505        });
12506    }
12507
12508    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12509        self.open_excerpts_common(None, true, cx)
12510    }
12511
12512    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12513        self.open_excerpts_common(None, false, cx)
12514    }
12515
12516    fn open_excerpts_common(
12517        &mut self,
12518        jump_data: Option<JumpData>,
12519        split: bool,
12520        cx: &mut ViewContext<Self>,
12521    ) {
12522        let Some(workspace) = self.workspace() else {
12523            cx.propagate();
12524            return;
12525        };
12526
12527        if self.buffer.read(cx).is_singleton() {
12528            cx.propagate();
12529            return;
12530        }
12531
12532        let mut new_selections_by_buffer = HashMap::default();
12533        match &jump_data {
12534            Some(JumpData::MultiBufferPoint {
12535                excerpt_id,
12536                position,
12537                anchor,
12538                line_offset_from_top,
12539            }) => {
12540                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12541                if let Some(buffer) = multi_buffer_snapshot
12542                    .buffer_id_for_excerpt(*excerpt_id)
12543                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12544                {
12545                    let buffer_snapshot = buffer.read(cx).snapshot();
12546                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
12547                        language::ToPoint::to_point(anchor, &buffer_snapshot)
12548                    } else {
12549                        buffer_snapshot.clip_point(*position, Bias::Left)
12550                    };
12551                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12552                    new_selections_by_buffer.insert(
12553                        buffer,
12554                        (
12555                            vec![jump_to_offset..jump_to_offset],
12556                            Some(*line_offset_from_top),
12557                        ),
12558                    );
12559                }
12560            }
12561            Some(JumpData::MultiBufferRow {
12562                row,
12563                line_offset_from_top,
12564            }) => {
12565                let point = MultiBufferPoint::new(row.0, 0);
12566                if let Some((buffer, buffer_point, _)) =
12567                    self.buffer.read(cx).point_to_buffer_point(point, cx)
12568                {
12569                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
12570                    new_selections_by_buffer
12571                        .entry(buffer)
12572                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
12573                        .0
12574                        .push(buffer_offset..buffer_offset)
12575                }
12576            }
12577            None => {
12578                let selections = self.selections.all::<usize>(cx);
12579                let multi_buffer = self.buffer.read(cx);
12580                for selection in selections {
12581                    for (excerpt, mut range) in multi_buffer
12582                        .snapshot(cx)
12583                        .range_to_buffer_ranges(selection.range())
12584                    {
12585                        // When editing branch buffers, jump to the corresponding location
12586                        // in their base buffer.
12587                        let mut buffer_handle = multi_buffer.buffer(excerpt.buffer_id()).unwrap();
12588                        let buffer = buffer_handle.read(cx);
12589                        if let Some(base_buffer) = buffer.base_buffer() {
12590                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12591                            buffer_handle = base_buffer;
12592                        }
12593
12594                        if selection.reversed {
12595                            mem::swap(&mut range.start, &mut range.end);
12596                        }
12597                        new_selections_by_buffer
12598                            .entry(buffer_handle)
12599                            .or_insert((Vec::new(), None))
12600                            .0
12601                            .push(range)
12602                    }
12603                }
12604            }
12605        }
12606
12607        if new_selections_by_buffer.is_empty() {
12608            return;
12609        }
12610
12611        // We defer the pane interaction because we ourselves are a workspace item
12612        // and activating a new item causes the pane to call a method on us reentrantly,
12613        // which panics if we're on the stack.
12614        cx.window_context().defer(move |cx| {
12615            workspace.update(cx, |workspace, cx| {
12616                let pane = if split {
12617                    workspace.adjacent_pane(cx)
12618                } else {
12619                    workspace.active_pane().clone()
12620                };
12621
12622                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12623                    let editor = buffer
12624                        .read(cx)
12625                        .file()
12626                        .is_none()
12627                        .then(|| {
12628                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
12629                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12630                            // Instead, we try to activate the existing editor in the pane first.
12631                            let (editor, pane_item_index) =
12632                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12633                                    let editor = item.downcast::<Editor>()?;
12634                                    let singleton_buffer =
12635                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12636                                    if singleton_buffer == buffer {
12637                                        Some((editor, i))
12638                                    } else {
12639                                        None
12640                                    }
12641                                })?;
12642                            pane.update(cx, |pane, cx| {
12643                                pane.activate_item(pane_item_index, true, true, cx)
12644                            });
12645                            Some(editor)
12646                        })
12647                        .flatten()
12648                        .unwrap_or_else(|| {
12649                            workspace.open_project_item::<Self>(
12650                                pane.clone(),
12651                                buffer,
12652                                true,
12653                                true,
12654                                cx,
12655                            )
12656                        });
12657
12658                    editor.update(cx, |editor, cx| {
12659                        let autoscroll = match scroll_offset {
12660                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12661                            None => Autoscroll::newest(),
12662                        };
12663                        let nav_history = editor.nav_history.take();
12664                        editor.change_selections(Some(autoscroll), cx, |s| {
12665                            s.select_ranges(ranges);
12666                        });
12667                        editor.nav_history = nav_history;
12668                    });
12669                }
12670            })
12671        });
12672    }
12673
12674    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12675        let snapshot = self.buffer.read(cx).read(cx);
12676        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12677        Some(
12678            ranges
12679                .iter()
12680                .map(move |range| {
12681                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12682                })
12683                .collect(),
12684        )
12685    }
12686
12687    fn selection_replacement_ranges(
12688        &self,
12689        range: Range<OffsetUtf16>,
12690        cx: &mut AppContext,
12691    ) -> Vec<Range<OffsetUtf16>> {
12692        let selections = self.selections.all::<OffsetUtf16>(cx);
12693        let newest_selection = selections
12694            .iter()
12695            .max_by_key(|selection| selection.id)
12696            .unwrap();
12697        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12698        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12699        let snapshot = self.buffer.read(cx).read(cx);
12700        selections
12701            .into_iter()
12702            .map(|mut selection| {
12703                selection.start.0 =
12704                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12705                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12706                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12707                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12708            })
12709            .collect()
12710    }
12711
12712    fn report_editor_event(
12713        &self,
12714        event_type: &'static str,
12715        file_extension: Option<String>,
12716        cx: &AppContext,
12717    ) {
12718        if cfg!(any(test, feature = "test-support")) {
12719            return;
12720        }
12721
12722        let Some(project) = &self.project else { return };
12723
12724        // If None, we are in a file without an extension
12725        let file = self
12726            .buffer
12727            .read(cx)
12728            .as_singleton()
12729            .and_then(|b| b.read(cx).file());
12730        let file_extension = file_extension.or(file
12731            .as_ref()
12732            .and_then(|file| Path::new(file.file_name(cx)).extension())
12733            .and_then(|e| e.to_str())
12734            .map(|a| a.to_string()));
12735
12736        let vim_mode = cx
12737            .global::<SettingsStore>()
12738            .raw_user_settings()
12739            .get("vim_mode")
12740            == Some(&serde_json::Value::Bool(true));
12741
12742        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12743            == language::language_settings::InlineCompletionProvider::Copilot;
12744        let copilot_enabled_for_language = self
12745            .buffer
12746            .read(cx)
12747            .settings_at(0, cx)
12748            .show_inline_completions;
12749
12750        let project = project.read(cx);
12751        telemetry::event!(
12752            event_type,
12753            file_extension,
12754            vim_mode,
12755            copilot_enabled,
12756            copilot_enabled_for_language,
12757            is_via_ssh = project.is_via_ssh(),
12758        );
12759    }
12760
12761    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12762    /// with each line being an array of {text, highlight} objects.
12763    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12764        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12765            return;
12766        };
12767
12768        #[derive(Serialize)]
12769        struct Chunk<'a> {
12770            text: String,
12771            highlight: Option<&'a str>,
12772        }
12773
12774        let snapshot = buffer.read(cx).snapshot();
12775        let range = self
12776            .selected_text_range(false, cx)
12777            .and_then(|selection| {
12778                if selection.range.is_empty() {
12779                    None
12780                } else {
12781                    Some(selection.range)
12782                }
12783            })
12784            .unwrap_or_else(|| 0..snapshot.len());
12785
12786        let chunks = snapshot.chunks(range, true);
12787        let mut lines = Vec::new();
12788        let mut line: VecDeque<Chunk> = VecDeque::new();
12789
12790        let Some(style) = self.style.as_ref() else {
12791            return;
12792        };
12793
12794        for chunk in chunks {
12795            let highlight = chunk
12796                .syntax_highlight_id
12797                .and_then(|id| id.name(&style.syntax));
12798            let mut chunk_lines = chunk.text.split('\n').peekable();
12799            while let Some(text) = chunk_lines.next() {
12800                let mut merged_with_last_token = false;
12801                if let Some(last_token) = line.back_mut() {
12802                    if last_token.highlight == highlight {
12803                        last_token.text.push_str(text);
12804                        merged_with_last_token = true;
12805                    }
12806                }
12807
12808                if !merged_with_last_token {
12809                    line.push_back(Chunk {
12810                        text: text.into(),
12811                        highlight,
12812                    });
12813                }
12814
12815                if chunk_lines.peek().is_some() {
12816                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12817                        line.pop_front();
12818                    }
12819                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12820                        line.pop_back();
12821                    }
12822
12823                    lines.push(mem::take(&mut line));
12824                }
12825            }
12826        }
12827
12828        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12829            return;
12830        };
12831        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12832    }
12833
12834    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12835        self.request_autoscroll(Autoscroll::newest(), cx);
12836        let position = self.selections.newest_display(cx).start;
12837        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12838    }
12839
12840    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12841        &self.inlay_hint_cache
12842    }
12843
12844    pub fn replay_insert_event(
12845        &mut self,
12846        text: &str,
12847        relative_utf16_range: Option<Range<isize>>,
12848        cx: &mut ViewContext<Self>,
12849    ) {
12850        if !self.input_enabled {
12851            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12852            return;
12853        }
12854        if let Some(relative_utf16_range) = relative_utf16_range {
12855            let selections = self.selections.all::<OffsetUtf16>(cx);
12856            self.change_selections(None, cx, |s| {
12857                let new_ranges = selections.into_iter().map(|range| {
12858                    let start = OffsetUtf16(
12859                        range
12860                            .head()
12861                            .0
12862                            .saturating_add_signed(relative_utf16_range.start),
12863                    );
12864                    let end = OffsetUtf16(
12865                        range
12866                            .head()
12867                            .0
12868                            .saturating_add_signed(relative_utf16_range.end),
12869                    );
12870                    start..end
12871                });
12872                s.select_ranges(new_ranges);
12873            });
12874        }
12875
12876        self.handle_input(text, cx);
12877    }
12878
12879    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12880        let Some(provider) = self.semantics_provider.as_ref() else {
12881            return false;
12882        };
12883
12884        let mut supports = false;
12885        self.buffer().read(cx).for_each_buffer(|buffer| {
12886            supports |= provider.supports_inlay_hints(buffer, cx);
12887        });
12888        supports
12889    }
12890
12891    pub fn focus(&self, cx: &mut WindowContext) {
12892        cx.focus(&self.focus_handle)
12893    }
12894
12895    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12896        self.focus_handle.is_focused(cx)
12897    }
12898
12899    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12900        cx.emit(EditorEvent::Focused);
12901
12902        if let Some(descendant) = self
12903            .last_focused_descendant
12904            .take()
12905            .and_then(|descendant| descendant.upgrade())
12906        {
12907            cx.focus(&descendant);
12908        } else {
12909            if let Some(blame) = self.blame.as_ref() {
12910                blame.update(cx, GitBlame::focus)
12911            }
12912
12913            self.blink_manager.update(cx, BlinkManager::enable);
12914            self.show_cursor_names(cx);
12915            self.buffer.update(cx, |buffer, cx| {
12916                buffer.finalize_last_transaction(cx);
12917                if self.leader_peer_id.is_none() {
12918                    buffer.set_active_selections(
12919                        &self.selections.disjoint_anchors(),
12920                        self.selections.line_mode,
12921                        self.cursor_shape,
12922                        cx,
12923                    );
12924                }
12925            });
12926        }
12927    }
12928
12929    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12930        cx.emit(EditorEvent::FocusedIn)
12931    }
12932
12933    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12934        if event.blurred != self.focus_handle {
12935            self.last_focused_descendant = Some(event.blurred);
12936        }
12937    }
12938
12939    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12940        self.blink_manager.update(cx, BlinkManager::disable);
12941        self.buffer
12942            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12943
12944        if let Some(blame) = self.blame.as_ref() {
12945            blame.update(cx, GitBlame::blur)
12946        }
12947        if !self.hover_state.focused(cx) {
12948            hide_hover(self, cx);
12949        }
12950
12951        self.hide_context_menu(cx);
12952        cx.emit(EditorEvent::Blurred);
12953        cx.notify();
12954    }
12955
12956    pub fn register_action<A: Action>(
12957        &mut self,
12958        listener: impl Fn(&A, &mut WindowContext) + 'static,
12959    ) -> Subscription {
12960        let id = self.next_editor_action_id.post_inc();
12961        let listener = Arc::new(listener);
12962        self.editor_actions.borrow_mut().insert(
12963            id,
12964            Box::new(move |cx| {
12965                let cx = cx.window_context();
12966                let listener = listener.clone();
12967                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12968                    let action = action.downcast_ref().unwrap();
12969                    if phase == DispatchPhase::Bubble {
12970                        listener(action, cx)
12971                    }
12972                })
12973            }),
12974        );
12975
12976        let editor_actions = self.editor_actions.clone();
12977        Subscription::new(move || {
12978            editor_actions.borrow_mut().remove(&id);
12979        })
12980    }
12981
12982    pub fn file_header_size(&self) -> u32 {
12983        FILE_HEADER_HEIGHT
12984    }
12985
12986    pub fn revert(
12987        &mut self,
12988        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12989        cx: &mut ViewContext<Self>,
12990    ) {
12991        self.buffer().update(cx, |multi_buffer, cx| {
12992            for (buffer_id, changes) in revert_changes {
12993                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12994                    buffer.update(cx, |buffer, cx| {
12995                        buffer.edit(
12996                            changes.into_iter().map(|(range, text)| {
12997                                (range, text.to_string().map(Arc::<str>::from))
12998                            }),
12999                            None,
13000                            cx,
13001                        );
13002                    });
13003                }
13004            }
13005        });
13006        self.change_selections(None, cx, |selections| selections.refresh());
13007    }
13008
13009    pub fn to_pixel_point(
13010        &mut self,
13011        source: multi_buffer::Anchor,
13012        editor_snapshot: &EditorSnapshot,
13013        cx: &mut ViewContext<Self>,
13014    ) -> Option<gpui::Point<Pixels>> {
13015        let source_point = source.to_display_point(editor_snapshot);
13016        self.display_to_pixel_point(source_point, editor_snapshot, cx)
13017    }
13018
13019    pub fn display_to_pixel_point(
13020        &self,
13021        source: DisplayPoint,
13022        editor_snapshot: &EditorSnapshot,
13023        cx: &WindowContext,
13024    ) -> Option<gpui::Point<Pixels>> {
13025        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
13026        let text_layout_details = self.text_layout_details(cx);
13027        let scroll_top = text_layout_details
13028            .scroll_anchor
13029            .scroll_position(editor_snapshot)
13030            .y;
13031
13032        if source.row().as_f32() < scroll_top.floor() {
13033            return None;
13034        }
13035        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
13036        let source_y = line_height * (source.row().as_f32() - scroll_top);
13037        Some(gpui::Point::new(source_x, source_y))
13038    }
13039
13040    pub fn has_active_completions_menu(&self) -> bool {
13041        self.context_menu.borrow().as_ref().map_or(false, |menu| {
13042            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
13043        })
13044    }
13045
13046    pub fn register_addon<T: Addon>(&mut self, instance: T) {
13047        self.addons
13048            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
13049    }
13050
13051    pub fn unregister_addon<T: Addon>(&mut self) {
13052        self.addons.remove(&std::any::TypeId::of::<T>());
13053    }
13054
13055    pub fn addon<T: Addon>(&self) -> Option<&T> {
13056        let type_id = std::any::TypeId::of::<T>();
13057        self.addons
13058            .get(&type_id)
13059            .and_then(|item| item.to_any().downcast_ref::<T>())
13060    }
13061
13062    pub fn add_change_set(
13063        &mut self,
13064        change_set: Model<BufferChangeSet>,
13065        cx: &mut ViewContext<Self>,
13066    ) {
13067        self.diff_map.add_change_set(change_set, cx);
13068    }
13069
13070    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
13071        let text_layout_details = self.text_layout_details(cx);
13072        let style = &text_layout_details.editor_style;
13073        let font_id = cx.text_system().resolve_font(&style.text.font());
13074        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13075        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13076
13077        let em_width = cx
13078            .text_system()
13079            .typographic_bounds(font_id, font_size, 'm')
13080            .unwrap()
13081            .size
13082            .width;
13083
13084        gpui::Point::new(em_width, line_height)
13085    }
13086}
13087
13088fn get_unstaged_changes_for_buffers(
13089    project: &Model<Project>,
13090    buffers: impl IntoIterator<Item = Model<Buffer>>,
13091    cx: &mut ViewContext<Editor>,
13092) {
13093    let mut tasks = Vec::new();
13094    project.update(cx, |project, cx| {
13095        for buffer in buffers {
13096            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
13097        }
13098    });
13099    cx.spawn(|this, mut cx| async move {
13100        let change_sets = futures::future::join_all(tasks).await;
13101        this.update(&mut cx, |this, cx| {
13102            for change_set in change_sets {
13103                if let Some(change_set) = change_set.log_err() {
13104                    this.diff_map.add_change_set(change_set, cx);
13105                }
13106            }
13107        })
13108        .ok();
13109    })
13110    .detach();
13111}
13112
13113fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
13114    let tab_size = tab_size.get() as usize;
13115    let mut width = offset;
13116
13117    for ch in text.chars() {
13118        width += if ch == '\t' {
13119            tab_size - (width % tab_size)
13120        } else {
13121            1
13122        };
13123    }
13124
13125    width - offset
13126}
13127
13128#[cfg(test)]
13129mod tests {
13130    use super::*;
13131
13132    #[test]
13133    fn test_string_size_with_expanded_tabs() {
13134        let nz = |val| NonZeroU32::new(val).unwrap();
13135        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
13136        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
13137        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
13138        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
13139        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13140        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13141        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13142        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13143    }
13144}
13145
13146/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13147struct WordBreakingTokenizer<'a> {
13148    input: &'a str,
13149}
13150
13151impl<'a> WordBreakingTokenizer<'a> {
13152    fn new(input: &'a str) -> Self {
13153        Self { input }
13154    }
13155}
13156
13157fn is_char_ideographic(ch: char) -> bool {
13158    use unicode_script::Script::*;
13159    use unicode_script::UnicodeScript;
13160    matches!(ch.script(), Han | Tangut | Yi)
13161}
13162
13163fn is_grapheme_ideographic(text: &str) -> bool {
13164    text.chars().any(is_char_ideographic)
13165}
13166
13167fn is_grapheme_whitespace(text: &str) -> bool {
13168    text.chars().any(|x| x.is_whitespace())
13169}
13170
13171fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13172    text.chars().next().map_or(false, |ch| {
13173        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13174    })
13175}
13176
13177#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13178struct WordBreakToken<'a> {
13179    token: &'a str,
13180    grapheme_len: usize,
13181    is_whitespace: bool,
13182}
13183
13184impl<'a> Iterator for WordBreakingTokenizer<'a> {
13185    /// Yields a span, the count of graphemes in the token, and whether it was
13186    /// whitespace. Note that it also breaks at word boundaries.
13187    type Item = WordBreakToken<'a>;
13188
13189    fn next(&mut self) -> Option<Self::Item> {
13190        use unicode_segmentation::UnicodeSegmentation;
13191        if self.input.is_empty() {
13192            return None;
13193        }
13194
13195        let mut iter = self.input.graphemes(true).peekable();
13196        let mut offset = 0;
13197        let mut graphemes = 0;
13198        if let Some(first_grapheme) = iter.next() {
13199            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13200            offset += first_grapheme.len();
13201            graphemes += 1;
13202            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13203                if let Some(grapheme) = iter.peek().copied() {
13204                    if should_stay_with_preceding_ideograph(grapheme) {
13205                        offset += grapheme.len();
13206                        graphemes += 1;
13207                    }
13208                }
13209            } else {
13210                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13211                let mut next_word_bound = words.peek().copied();
13212                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13213                    next_word_bound = words.next();
13214                }
13215                while let Some(grapheme) = iter.peek().copied() {
13216                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13217                        break;
13218                    };
13219                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13220                        break;
13221                    };
13222                    offset += grapheme.len();
13223                    graphemes += 1;
13224                    iter.next();
13225                }
13226            }
13227            let token = &self.input[..offset];
13228            self.input = &self.input[offset..];
13229            if is_whitespace {
13230                Some(WordBreakToken {
13231                    token: " ",
13232                    grapheme_len: 1,
13233                    is_whitespace: true,
13234                })
13235            } else {
13236                Some(WordBreakToken {
13237                    token,
13238                    grapheme_len: graphemes,
13239                    is_whitespace: false,
13240                })
13241            }
13242        } else {
13243            None
13244        }
13245    }
13246}
13247
13248#[test]
13249fn test_word_breaking_tokenizer() {
13250    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13251        ("", &[]),
13252        ("  ", &[(" ", 1, true)]),
13253        ("Ʒ", &[("Ʒ", 1, false)]),
13254        ("Ǽ", &[("Ǽ", 1, false)]),
13255        ("", &[("", 1, false)]),
13256        ("⋑⋑", &[("⋑⋑", 2, false)]),
13257        (
13258            "原理,进而",
13259            &[
13260                ("", 1, false),
13261                ("理,", 2, false),
13262                ("", 1, false),
13263                ("", 1, false),
13264            ],
13265        ),
13266        (
13267            "hello world",
13268            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13269        ),
13270        (
13271            "hello, world",
13272            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13273        ),
13274        (
13275            "  hello world",
13276            &[
13277                (" ", 1, true),
13278                ("hello", 5, false),
13279                (" ", 1, true),
13280                ("world", 5, false),
13281            ],
13282        ),
13283        (
13284            "这是什么 \n 钢笔",
13285            &[
13286                ("", 1, false),
13287                ("", 1, false),
13288                ("", 1, false),
13289                ("", 1, false),
13290                (" ", 1, true),
13291                ("", 1, false),
13292                ("", 1, false),
13293            ],
13294        ),
13295        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13296    ];
13297
13298    for (input, result) in tests {
13299        assert_eq!(
13300            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13301            result
13302                .iter()
13303                .copied()
13304                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13305                    token,
13306                    grapheme_len,
13307                    is_whitespace,
13308                })
13309                .collect::<Vec<_>>()
13310        );
13311    }
13312}
13313
13314fn wrap_with_prefix(
13315    line_prefix: String,
13316    unwrapped_text: String,
13317    wrap_column: usize,
13318    tab_size: NonZeroU32,
13319) -> String {
13320    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13321    let mut wrapped_text = String::new();
13322    let mut current_line = line_prefix.clone();
13323
13324    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13325    let mut current_line_len = line_prefix_len;
13326    for WordBreakToken {
13327        token,
13328        grapheme_len,
13329        is_whitespace,
13330    } in tokenizer
13331    {
13332        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13333            wrapped_text.push_str(current_line.trim_end());
13334            wrapped_text.push('\n');
13335            current_line.truncate(line_prefix.len());
13336            current_line_len = line_prefix_len;
13337            if !is_whitespace {
13338                current_line.push_str(token);
13339                current_line_len += grapheme_len;
13340            }
13341        } else if !is_whitespace {
13342            current_line.push_str(token);
13343            current_line_len += grapheme_len;
13344        } else if current_line_len != line_prefix_len {
13345            current_line.push(' ');
13346            current_line_len += 1;
13347        }
13348    }
13349
13350    if !current_line.is_empty() {
13351        wrapped_text.push_str(&current_line);
13352    }
13353    wrapped_text
13354}
13355
13356#[test]
13357fn test_wrap_with_prefix() {
13358    assert_eq!(
13359        wrap_with_prefix(
13360            "# ".to_string(),
13361            "abcdefg".to_string(),
13362            4,
13363            NonZeroU32::new(4).unwrap()
13364        ),
13365        "# abcdefg"
13366    );
13367    assert_eq!(
13368        wrap_with_prefix(
13369            "".to_string(),
13370            "\thello world".to_string(),
13371            8,
13372            NonZeroU32::new(4).unwrap()
13373        ),
13374        "hello\nworld"
13375    );
13376    assert_eq!(
13377        wrap_with_prefix(
13378            "// ".to_string(),
13379            "xx \nyy zz aa bb cc".to_string(),
13380            12,
13381            NonZeroU32::new(4).unwrap()
13382        ),
13383        "// xx yy zz\n// aa bb cc"
13384    );
13385    assert_eq!(
13386        wrap_with_prefix(
13387            String::new(),
13388            "这是什么 \n 钢笔".to_string(),
13389            3,
13390            NonZeroU32::new(4).unwrap()
13391        ),
13392        "这是什\n么 钢\n"
13393    );
13394}
13395
13396fn hunks_for_selections(
13397    snapshot: &EditorSnapshot,
13398    selections: &[Selection<Point>],
13399) -> Vec<MultiBufferDiffHunk> {
13400    hunks_for_ranges(
13401        selections.iter().map(|selection| selection.range()),
13402        snapshot,
13403    )
13404}
13405
13406pub fn hunks_for_ranges(
13407    ranges: impl Iterator<Item = Range<Point>>,
13408    snapshot: &EditorSnapshot,
13409) -> Vec<MultiBufferDiffHunk> {
13410    let mut hunks = Vec::new();
13411    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13412        HashMap::default();
13413    for query_range in ranges {
13414        let query_rows =
13415            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13416        for hunk in snapshot.diff_map.diff_hunks_in_range(
13417            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13418            &snapshot.buffer_snapshot,
13419        ) {
13420            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13421            // when the caret is just above or just below the deleted hunk.
13422            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13423            let related_to_selection = if allow_adjacent {
13424                hunk.row_range.overlaps(&query_rows)
13425                    || hunk.row_range.start == query_rows.end
13426                    || hunk.row_range.end == query_rows.start
13427            } else {
13428                hunk.row_range.overlaps(&query_rows)
13429            };
13430            if related_to_selection {
13431                if !processed_buffer_rows
13432                    .entry(hunk.buffer_id)
13433                    .or_default()
13434                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13435                {
13436                    continue;
13437                }
13438                hunks.push(hunk);
13439            }
13440        }
13441    }
13442
13443    hunks
13444}
13445
13446pub trait CollaborationHub {
13447    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13448    fn user_participant_indices<'a>(
13449        &self,
13450        cx: &'a AppContext,
13451    ) -> &'a HashMap<u64, ParticipantIndex>;
13452    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13453}
13454
13455impl CollaborationHub for Model<Project> {
13456    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13457        self.read(cx).collaborators()
13458    }
13459
13460    fn user_participant_indices<'a>(
13461        &self,
13462        cx: &'a AppContext,
13463    ) -> &'a HashMap<u64, ParticipantIndex> {
13464        self.read(cx).user_store().read(cx).participant_indices()
13465    }
13466
13467    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13468        let this = self.read(cx);
13469        let user_ids = this.collaborators().values().map(|c| c.user_id);
13470        this.user_store().read_with(cx, |user_store, cx| {
13471            user_store.participant_names(user_ids, cx)
13472        })
13473    }
13474}
13475
13476pub trait SemanticsProvider {
13477    fn hover(
13478        &self,
13479        buffer: &Model<Buffer>,
13480        position: text::Anchor,
13481        cx: &mut AppContext,
13482    ) -> Option<Task<Vec<project::Hover>>>;
13483
13484    fn inlay_hints(
13485        &self,
13486        buffer_handle: Model<Buffer>,
13487        range: Range<text::Anchor>,
13488        cx: &mut AppContext,
13489    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13490
13491    fn resolve_inlay_hint(
13492        &self,
13493        hint: InlayHint,
13494        buffer_handle: Model<Buffer>,
13495        server_id: LanguageServerId,
13496        cx: &mut AppContext,
13497    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13498
13499    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13500
13501    fn document_highlights(
13502        &self,
13503        buffer: &Model<Buffer>,
13504        position: text::Anchor,
13505        cx: &mut AppContext,
13506    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13507
13508    fn definitions(
13509        &self,
13510        buffer: &Model<Buffer>,
13511        position: text::Anchor,
13512        kind: GotoDefinitionKind,
13513        cx: &mut AppContext,
13514    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13515
13516    fn range_for_rename(
13517        &self,
13518        buffer: &Model<Buffer>,
13519        position: text::Anchor,
13520        cx: &mut AppContext,
13521    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13522
13523    fn perform_rename(
13524        &self,
13525        buffer: &Model<Buffer>,
13526        position: text::Anchor,
13527        new_name: String,
13528        cx: &mut AppContext,
13529    ) -> Option<Task<Result<ProjectTransaction>>>;
13530}
13531
13532pub trait CompletionProvider {
13533    fn completions(
13534        &self,
13535        buffer: &Model<Buffer>,
13536        buffer_position: text::Anchor,
13537        trigger: CompletionContext,
13538        cx: &mut ViewContext<Editor>,
13539    ) -> Task<Result<Vec<Completion>>>;
13540
13541    fn resolve_completions(
13542        &self,
13543        buffer: Model<Buffer>,
13544        completion_indices: Vec<usize>,
13545        completions: Rc<RefCell<Box<[Completion]>>>,
13546        cx: &mut ViewContext<Editor>,
13547    ) -> Task<Result<bool>>;
13548
13549    fn apply_additional_edits_for_completion(
13550        &self,
13551        _buffer: Model<Buffer>,
13552        _completions: Rc<RefCell<Box<[Completion]>>>,
13553        _completion_index: usize,
13554        _push_to_history: bool,
13555        _cx: &mut ViewContext<Editor>,
13556    ) -> Task<Result<Option<language::Transaction>>> {
13557        Task::ready(Ok(None))
13558    }
13559
13560    fn is_completion_trigger(
13561        &self,
13562        buffer: &Model<Buffer>,
13563        position: language::Anchor,
13564        text: &str,
13565        trigger_in_words: bool,
13566        cx: &mut ViewContext<Editor>,
13567    ) -> bool;
13568
13569    fn sort_completions(&self) -> bool {
13570        true
13571    }
13572}
13573
13574pub trait CodeActionProvider {
13575    fn id(&self) -> Arc<str>;
13576
13577    fn code_actions(
13578        &self,
13579        buffer: &Model<Buffer>,
13580        range: Range<text::Anchor>,
13581        cx: &mut WindowContext,
13582    ) -> Task<Result<Vec<CodeAction>>>;
13583
13584    fn apply_code_action(
13585        &self,
13586        buffer_handle: Model<Buffer>,
13587        action: CodeAction,
13588        excerpt_id: ExcerptId,
13589        push_to_history: bool,
13590        cx: &mut WindowContext,
13591    ) -> Task<Result<ProjectTransaction>>;
13592}
13593
13594impl CodeActionProvider for Model<Project> {
13595    fn id(&self) -> Arc<str> {
13596        "project".into()
13597    }
13598
13599    fn code_actions(
13600        &self,
13601        buffer: &Model<Buffer>,
13602        range: Range<text::Anchor>,
13603        cx: &mut WindowContext,
13604    ) -> Task<Result<Vec<CodeAction>>> {
13605        self.update(cx, |project, cx| {
13606            project.code_actions(buffer, range, None, cx)
13607        })
13608    }
13609
13610    fn apply_code_action(
13611        &self,
13612        buffer_handle: Model<Buffer>,
13613        action: CodeAction,
13614        _excerpt_id: ExcerptId,
13615        push_to_history: bool,
13616        cx: &mut WindowContext,
13617    ) -> Task<Result<ProjectTransaction>> {
13618        self.update(cx, |project, cx| {
13619            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13620        })
13621    }
13622}
13623
13624fn snippet_completions(
13625    project: &Project,
13626    buffer: &Model<Buffer>,
13627    buffer_position: text::Anchor,
13628    cx: &mut AppContext,
13629) -> Task<Result<Vec<Completion>>> {
13630    let language = buffer.read(cx).language_at(buffer_position);
13631    let language_name = language.as_ref().map(|language| language.lsp_id());
13632    let snippet_store = project.snippets().read(cx);
13633    let snippets = snippet_store.snippets_for(language_name, cx);
13634
13635    if snippets.is_empty() {
13636        return Task::ready(Ok(vec![]));
13637    }
13638    let snapshot = buffer.read(cx).text_snapshot();
13639    let chars: String = snapshot
13640        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13641        .collect();
13642
13643    let scope = language.map(|language| language.default_scope());
13644    let executor = cx.background_executor().clone();
13645
13646    cx.background_executor().spawn(async move {
13647        let classifier = CharClassifier::new(scope).for_completion(true);
13648        let mut last_word = chars
13649            .chars()
13650            .take_while(|c| classifier.is_word(*c))
13651            .collect::<String>();
13652        last_word = last_word.chars().rev().collect();
13653
13654        if last_word.is_empty() {
13655            return Ok(vec![]);
13656        }
13657
13658        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13659        let to_lsp = |point: &text::Anchor| {
13660            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13661            point_to_lsp(end)
13662        };
13663        let lsp_end = to_lsp(&buffer_position);
13664
13665        let candidates = snippets
13666            .iter()
13667            .enumerate()
13668            .flat_map(|(ix, snippet)| {
13669                snippet
13670                    .prefix
13671                    .iter()
13672                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13673            })
13674            .collect::<Vec<StringMatchCandidate>>();
13675
13676        let mut matches = fuzzy::match_strings(
13677            &candidates,
13678            &last_word,
13679            last_word.chars().any(|c| c.is_uppercase()),
13680            100,
13681            &Default::default(),
13682            executor,
13683        )
13684        .await;
13685
13686        // Remove all candidates where the query's start does not match the start of any word in the candidate
13687        if let Some(query_start) = last_word.chars().next() {
13688            matches.retain(|string_match| {
13689                split_words(&string_match.string).any(|word| {
13690                    // Check that the first codepoint of the word as lowercase matches the first
13691                    // codepoint of the query as lowercase
13692                    word.chars()
13693                        .flat_map(|codepoint| codepoint.to_lowercase())
13694                        .zip(query_start.to_lowercase())
13695                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13696                })
13697            });
13698        }
13699
13700        let matched_strings = matches
13701            .into_iter()
13702            .map(|m| m.string)
13703            .collect::<HashSet<_>>();
13704
13705        let result: Vec<Completion> = snippets
13706            .into_iter()
13707            .filter_map(|snippet| {
13708                let matching_prefix = snippet
13709                    .prefix
13710                    .iter()
13711                    .find(|prefix| matched_strings.contains(*prefix))?;
13712                let start = as_offset - last_word.len();
13713                let start = snapshot.anchor_before(start);
13714                let range = start..buffer_position;
13715                let lsp_start = to_lsp(&start);
13716                let lsp_range = lsp::Range {
13717                    start: lsp_start,
13718                    end: lsp_end,
13719                };
13720                Some(Completion {
13721                    old_range: range,
13722                    new_text: snippet.body.clone(),
13723                    resolved: false,
13724                    label: CodeLabel {
13725                        text: matching_prefix.clone(),
13726                        runs: vec![],
13727                        filter_range: 0..matching_prefix.len(),
13728                    },
13729                    server_id: LanguageServerId(usize::MAX),
13730                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13731                    lsp_completion: lsp::CompletionItem {
13732                        label: snippet.prefix.first().unwrap().clone(),
13733                        kind: Some(CompletionItemKind::SNIPPET),
13734                        label_details: snippet.description.as_ref().map(|description| {
13735                            lsp::CompletionItemLabelDetails {
13736                                detail: Some(description.clone()),
13737                                description: None,
13738                            }
13739                        }),
13740                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13741                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13742                            lsp::InsertReplaceEdit {
13743                                new_text: snippet.body.clone(),
13744                                insert: lsp_range,
13745                                replace: lsp_range,
13746                            },
13747                        )),
13748                        filter_text: Some(snippet.body.clone()),
13749                        sort_text: Some(char::MAX.to_string()),
13750                        ..Default::default()
13751                    },
13752                    confirm: None,
13753                })
13754            })
13755            .collect();
13756
13757        Ok(result)
13758    })
13759}
13760
13761impl CompletionProvider for Model<Project> {
13762    fn completions(
13763        &self,
13764        buffer: &Model<Buffer>,
13765        buffer_position: text::Anchor,
13766        options: CompletionContext,
13767        cx: &mut ViewContext<Editor>,
13768    ) -> Task<Result<Vec<Completion>>> {
13769        self.update(cx, |project, cx| {
13770            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13771            let project_completions = project.completions(buffer, buffer_position, options, cx);
13772            cx.background_executor().spawn(async move {
13773                let mut completions = project_completions.await?;
13774                let snippets_completions = snippets.await?;
13775                completions.extend(snippets_completions);
13776                Ok(completions)
13777            })
13778        })
13779    }
13780
13781    fn resolve_completions(
13782        &self,
13783        buffer: Model<Buffer>,
13784        completion_indices: Vec<usize>,
13785        completions: Rc<RefCell<Box<[Completion]>>>,
13786        cx: &mut ViewContext<Editor>,
13787    ) -> Task<Result<bool>> {
13788        self.update(cx, |project, cx| {
13789            project.lsp_store().update(cx, |lsp_store, cx| {
13790                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
13791            })
13792        })
13793    }
13794
13795    fn apply_additional_edits_for_completion(
13796        &self,
13797        buffer: Model<Buffer>,
13798        completions: Rc<RefCell<Box<[Completion]>>>,
13799        completion_index: usize,
13800        push_to_history: bool,
13801        cx: &mut ViewContext<Editor>,
13802    ) -> Task<Result<Option<language::Transaction>>> {
13803        self.update(cx, |project, cx| {
13804            project.lsp_store().update(cx, |lsp_store, cx| {
13805                lsp_store.apply_additional_edits_for_completion(
13806                    buffer,
13807                    completions,
13808                    completion_index,
13809                    push_to_history,
13810                    cx,
13811                )
13812            })
13813        })
13814    }
13815
13816    fn is_completion_trigger(
13817        &self,
13818        buffer: &Model<Buffer>,
13819        position: language::Anchor,
13820        text: &str,
13821        trigger_in_words: bool,
13822        cx: &mut ViewContext<Editor>,
13823    ) -> bool {
13824        let mut chars = text.chars();
13825        let char = if let Some(char) = chars.next() {
13826            char
13827        } else {
13828            return false;
13829        };
13830        if chars.next().is_some() {
13831            return false;
13832        }
13833
13834        let buffer = buffer.read(cx);
13835        let snapshot = buffer.snapshot();
13836        if !snapshot.settings_at(position, cx).show_completions_on_input {
13837            return false;
13838        }
13839        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13840        if trigger_in_words && classifier.is_word(char) {
13841            return true;
13842        }
13843
13844        buffer.completion_triggers().contains(text)
13845    }
13846}
13847
13848impl SemanticsProvider for Model<Project> {
13849    fn hover(
13850        &self,
13851        buffer: &Model<Buffer>,
13852        position: text::Anchor,
13853        cx: &mut AppContext,
13854    ) -> Option<Task<Vec<project::Hover>>> {
13855        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13856    }
13857
13858    fn document_highlights(
13859        &self,
13860        buffer: &Model<Buffer>,
13861        position: text::Anchor,
13862        cx: &mut AppContext,
13863    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13864        Some(self.update(cx, |project, cx| {
13865            project.document_highlights(buffer, position, cx)
13866        }))
13867    }
13868
13869    fn definitions(
13870        &self,
13871        buffer: &Model<Buffer>,
13872        position: text::Anchor,
13873        kind: GotoDefinitionKind,
13874        cx: &mut AppContext,
13875    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13876        Some(self.update(cx, |project, cx| match kind {
13877            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13878            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13879            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13880            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13881        }))
13882    }
13883
13884    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13885        // TODO: make this work for remote projects
13886        self.read(cx)
13887            .language_servers_for_local_buffer(buffer.read(cx), cx)
13888            .any(
13889                |(_, server)| match server.capabilities().inlay_hint_provider {
13890                    Some(lsp::OneOf::Left(enabled)) => enabled,
13891                    Some(lsp::OneOf::Right(_)) => true,
13892                    None => false,
13893                },
13894            )
13895    }
13896
13897    fn inlay_hints(
13898        &self,
13899        buffer_handle: Model<Buffer>,
13900        range: Range<text::Anchor>,
13901        cx: &mut AppContext,
13902    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13903        Some(self.update(cx, |project, cx| {
13904            project.inlay_hints(buffer_handle, range, cx)
13905        }))
13906    }
13907
13908    fn resolve_inlay_hint(
13909        &self,
13910        hint: InlayHint,
13911        buffer_handle: Model<Buffer>,
13912        server_id: LanguageServerId,
13913        cx: &mut AppContext,
13914    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13915        Some(self.update(cx, |project, cx| {
13916            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13917        }))
13918    }
13919
13920    fn range_for_rename(
13921        &self,
13922        buffer: &Model<Buffer>,
13923        position: text::Anchor,
13924        cx: &mut AppContext,
13925    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13926        Some(self.update(cx, |project, cx| {
13927            project.prepare_rename(buffer.clone(), position, cx)
13928        }))
13929    }
13930
13931    fn perform_rename(
13932        &self,
13933        buffer: &Model<Buffer>,
13934        position: text::Anchor,
13935        new_name: String,
13936        cx: &mut AppContext,
13937    ) -> Option<Task<Result<ProjectTransaction>>> {
13938        Some(self.update(cx, |project, cx| {
13939            project.perform_rename(buffer.clone(), position, new_name, cx)
13940        }))
13941    }
13942}
13943
13944fn inlay_hint_settings(
13945    location: Anchor,
13946    snapshot: &MultiBufferSnapshot,
13947    cx: &mut ViewContext<Editor>,
13948) -> InlayHintSettings {
13949    let file = snapshot.file_at(location);
13950    let language = snapshot.language_at(location).map(|l| l.name());
13951    language_settings(language, file, cx).inlay_hints
13952}
13953
13954fn consume_contiguous_rows(
13955    contiguous_row_selections: &mut Vec<Selection<Point>>,
13956    selection: &Selection<Point>,
13957    display_map: &DisplaySnapshot,
13958    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13959) -> (MultiBufferRow, MultiBufferRow) {
13960    contiguous_row_selections.push(selection.clone());
13961    let start_row = MultiBufferRow(selection.start.row);
13962    let mut end_row = ending_row(selection, display_map);
13963
13964    while let Some(next_selection) = selections.peek() {
13965        if next_selection.start.row <= end_row.0 {
13966            end_row = ending_row(next_selection, display_map);
13967            contiguous_row_selections.push(selections.next().unwrap().clone());
13968        } else {
13969            break;
13970        }
13971    }
13972    (start_row, end_row)
13973}
13974
13975fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13976    if next_selection.end.column > 0 || next_selection.is_empty() {
13977        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13978    } else {
13979        MultiBufferRow(next_selection.end.row)
13980    }
13981}
13982
13983impl EditorSnapshot {
13984    pub fn remote_selections_in_range<'a>(
13985        &'a self,
13986        range: &'a Range<Anchor>,
13987        collaboration_hub: &dyn CollaborationHub,
13988        cx: &'a AppContext,
13989    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13990        let participant_names = collaboration_hub.user_names(cx);
13991        let participant_indices = collaboration_hub.user_participant_indices(cx);
13992        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13993        let collaborators_by_replica_id = collaborators_by_peer_id
13994            .iter()
13995            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13996            .collect::<HashMap<_, _>>();
13997        self.buffer_snapshot
13998            .selections_in_range(range, false)
13999            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
14000                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
14001                let participant_index = participant_indices.get(&collaborator.user_id).copied();
14002                let user_name = participant_names.get(&collaborator.user_id).cloned();
14003                Some(RemoteSelection {
14004                    replica_id,
14005                    selection,
14006                    cursor_shape,
14007                    line_mode,
14008                    participant_index,
14009                    peer_id: collaborator.peer_id,
14010                    user_name,
14011                })
14012            })
14013    }
14014
14015    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
14016        self.display_snapshot.buffer_snapshot.language_at(position)
14017    }
14018
14019    pub fn is_focused(&self) -> bool {
14020        self.is_focused
14021    }
14022
14023    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
14024        self.placeholder_text.as_ref()
14025    }
14026
14027    pub fn scroll_position(&self) -> gpui::Point<f32> {
14028        self.scroll_anchor.scroll_position(&self.display_snapshot)
14029    }
14030
14031    fn gutter_dimensions(
14032        &self,
14033        font_id: FontId,
14034        font_size: Pixels,
14035        em_width: Pixels,
14036        em_advance: Pixels,
14037        max_line_number_width: Pixels,
14038        cx: &AppContext,
14039    ) -> GutterDimensions {
14040        if !self.show_gutter {
14041            return GutterDimensions::default();
14042        }
14043        let descent = cx.text_system().descent(font_id, font_size);
14044
14045        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
14046            matches!(
14047                ProjectSettings::get_global(cx).git.git_gutter,
14048                Some(GitGutterSetting::TrackedFiles)
14049            )
14050        });
14051        let gutter_settings = EditorSettings::get_global(cx).gutter;
14052        let show_line_numbers = self
14053            .show_line_numbers
14054            .unwrap_or(gutter_settings.line_numbers);
14055        let line_gutter_width = if show_line_numbers {
14056            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
14057            let min_width_for_number_on_gutter = em_advance * 4.0;
14058            max_line_number_width.max(min_width_for_number_on_gutter)
14059        } else {
14060            0.0.into()
14061        };
14062
14063        let show_code_actions = self
14064            .show_code_actions
14065            .unwrap_or(gutter_settings.code_actions);
14066
14067        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
14068
14069        let git_blame_entries_width =
14070            self.git_blame_gutter_max_author_length
14071                .map(|max_author_length| {
14072                    // Length of the author name, but also space for the commit hash,
14073                    // the spacing and the timestamp.
14074                    let max_char_count = max_author_length
14075                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
14076                        + 7 // length of commit sha
14077                        + 14 // length of max relative timestamp ("60 minutes ago")
14078                        + 4; // gaps and margins
14079
14080                    em_advance * max_char_count
14081                });
14082
14083        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
14084        left_padding += if show_code_actions || show_runnables {
14085            em_width * 3.0
14086        } else if show_git_gutter && show_line_numbers {
14087            em_width * 2.0
14088        } else if show_git_gutter || show_line_numbers {
14089            em_width
14090        } else {
14091            px(0.)
14092        };
14093
14094        let right_padding = if gutter_settings.folds && show_line_numbers {
14095            em_width * 4.0
14096        } else if gutter_settings.folds {
14097            em_width * 3.0
14098        } else if show_line_numbers {
14099            em_width
14100        } else {
14101            px(0.)
14102        };
14103
14104        GutterDimensions {
14105            left_padding,
14106            right_padding,
14107            width: line_gutter_width + left_padding + right_padding,
14108            margin: -descent,
14109            git_blame_entries_width,
14110        }
14111    }
14112
14113    pub fn render_crease_toggle(
14114        &self,
14115        buffer_row: MultiBufferRow,
14116        row_contains_cursor: bool,
14117        editor: View<Editor>,
14118        cx: &mut WindowContext,
14119    ) -> Option<AnyElement> {
14120        let folded = self.is_line_folded(buffer_row);
14121        let mut is_foldable = false;
14122
14123        if let Some(crease) = self
14124            .crease_snapshot
14125            .query_row(buffer_row, &self.buffer_snapshot)
14126        {
14127            is_foldable = true;
14128            match crease {
14129                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
14130                    if let Some(render_toggle) = render_toggle {
14131                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
14132                            if folded {
14133                                editor.update(cx, |editor, cx| {
14134                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
14135                                });
14136                            } else {
14137                                editor.update(cx, |editor, cx| {
14138                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
14139                                });
14140                            }
14141                        });
14142                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
14143                    }
14144                }
14145            }
14146        }
14147
14148        is_foldable |= self.starts_indent(buffer_row);
14149
14150        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
14151            Some(
14152                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
14153                    .toggle_state(folded)
14154                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
14155                        if folded {
14156                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
14157                        } else {
14158                            this.fold_at(&FoldAt { buffer_row }, cx);
14159                        }
14160                    }))
14161                    .into_any_element(),
14162            )
14163        } else {
14164            None
14165        }
14166    }
14167
14168    pub fn render_crease_trailer(
14169        &self,
14170        buffer_row: MultiBufferRow,
14171        cx: &mut WindowContext,
14172    ) -> Option<AnyElement> {
14173        let folded = self.is_line_folded(buffer_row);
14174        if let Crease::Inline { render_trailer, .. } = self
14175            .crease_snapshot
14176            .query_row(buffer_row, &self.buffer_snapshot)?
14177        {
14178            let render_trailer = render_trailer.as_ref()?;
14179            Some(render_trailer(buffer_row, folded, cx))
14180        } else {
14181            None
14182        }
14183    }
14184}
14185
14186impl Deref for EditorSnapshot {
14187    type Target = DisplaySnapshot;
14188
14189    fn deref(&self) -> &Self::Target {
14190        &self.display_snapshot
14191    }
14192}
14193
14194#[derive(Clone, Debug, PartialEq, Eq)]
14195pub enum EditorEvent {
14196    InputIgnored {
14197        text: Arc<str>,
14198    },
14199    InputHandled {
14200        utf16_range_to_replace: Option<Range<isize>>,
14201        text: Arc<str>,
14202    },
14203    ExcerptsAdded {
14204        buffer: Model<Buffer>,
14205        predecessor: ExcerptId,
14206        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14207    },
14208    ExcerptsRemoved {
14209        ids: Vec<ExcerptId>,
14210    },
14211    BufferFoldToggled {
14212        ids: Vec<ExcerptId>,
14213        folded: bool,
14214    },
14215    ExcerptsEdited {
14216        ids: Vec<ExcerptId>,
14217    },
14218    ExcerptsExpanded {
14219        ids: Vec<ExcerptId>,
14220    },
14221    BufferEdited,
14222    Edited {
14223        transaction_id: clock::Lamport,
14224    },
14225    Reparsed(BufferId),
14226    Focused,
14227    FocusedIn,
14228    Blurred,
14229    DirtyChanged,
14230    Saved,
14231    TitleChanged,
14232    DiffBaseChanged,
14233    SelectionsChanged {
14234        local: bool,
14235    },
14236    ScrollPositionChanged {
14237        local: bool,
14238        autoscroll: bool,
14239    },
14240    Closed,
14241    TransactionUndone {
14242        transaction_id: clock::Lamport,
14243    },
14244    TransactionBegun {
14245        transaction_id: clock::Lamport,
14246    },
14247    Reloaded,
14248    CursorShapeChanged,
14249}
14250
14251impl EventEmitter<EditorEvent> for Editor {}
14252
14253impl FocusableView for Editor {
14254    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14255        self.focus_handle.clone()
14256    }
14257}
14258
14259impl Render for Editor {
14260    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14261        let settings = ThemeSettings::get_global(cx);
14262
14263        let mut text_style = match self.mode {
14264            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14265                color: cx.theme().colors().editor_foreground,
14266                font_family: settings.ui_font.family.clone(),
14267                font_features: settings.ui_font.features.clone(),
14268                font_fallbacks: settings.ui_font.fallbacks.clone(),
14269                font_size: rems(0.875).into(),
14270                font_weight: settings.ui_font.weight,
14271                line_height: relative(settings.buffer_line_height.value()),
14272                ..Default::default()
14273            },
14274            EditorMode::Full => TextStyle {
14275                color: cx.theme().colors().editor_foreground,
14276                font_family: settings.buffer_font.family.clone(),
14277                font_features: settings.buffer_font.features.clone(),
14278                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14279                font_size: settings.buffer_font_size(cx).into(),
14280                font_weight: settings.buffer_font.weight,
14281                line_height: relative(settings.buffer_line_height.value()),
14282                ..Default::default()
14283            },
14284        };
14285        if let Some(text_style_refinement) = &self.text_style_refinement {
14286            text_style.refine(text_style_refinement)
14287        }
14288
14289        let background = match self.mode {
14290            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14291            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14292            EditorMode::Full => cx.theme().colors().editor_background,
14293        };
14294
14295        EditorElement::new(
14296            cx.view(),
14297            EditorStyle {
14298                background,
14299                local_player: cx.theme().players().local(),
14300                text: text_style,
14301                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14302                syntax: cx.theme().syntax().clone(),
14303                status: cx.theme().status().clone(),
14304                inlay_hints_style: make_inlay_hints_style(cx),
14305                inline_completion_styles: make_suggestion_styles(cx),
14306                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14307            },
14308        )
14309    }
14310}
14311
14312impl ViewInputHandler for Editor {
14313    fn text_for_range(
14314        &mut self,
14315        range_utf16: Range<usize>,
14316        adjusted_range: &mut Option<Range<usize>>,
14317        cx: &mut ViewContext<Self>,
14318    ) -> Option<String> {
14319        let snapshot = self.buffer.read(cx).read(cx);
14320        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14321        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14322        if (start.0..end.0) != range_utf16 {
14323            adjusted_range.replace(start.0..end.0);
14324        }
14325        Some(snapshot.text_for_range(start..end).collect())
14326    }
14327
14328    fn selected_text_range(
14329        &mut self,
14330        ignore_disabled_input: bool,
14331        cx: &mut ViewContext<Self>,
14332    ) -> Option<UTF16Selection> {
14333        // Prevent the IME menu from appearing when holding down an alphabetic key
14334        // while input is disabled.
14335        if !ignore_disabled_input && !self.input_enabled {
14336            return None;
14337        }
14338
14339        let selection = self.selections.newest::<OffsetUtf16>(cx);
14340        let range = selection.range();
14341
14342        Some(UTF16Selection {
14343            range: range.start.0..range.end.0,
14344            reversed: selection.reversed,
14345        })
14346    }
14347
14348    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14349        let snapshot = self.buffer.read(cx).read(cx);
14350        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14351        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14352    }
14353
14354    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14355        self.clear_highlights::<InputComposition>(cx);
14356        self.ime_transaction.take();
14357    }
14358
14359    fn replace_text_in_range(
14360        &mut self,
14361        range_utf16: Option<Range<usize>>,
14362        text: &str,
14363        cx: &mut ViewContext<Self>,
14364    ) {
14365        if !self.input_enabled {
14366            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14367            return;
14368        }
14369
14370        self.transact(cx, |this, cx| {
14371            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14372                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14373                Some(this.selection_replacement_ranges(range_utf16, cx))
14374            } else {
14375                this.marked_text_ranges(cx)
14376            };
14377
14378            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14379                let newest_selection_id = this.selections.newest_anchor().id;
14380                this.selections
14381                    .all::<OffsetUtf16>(cx)
14382                    .iter()
14383                    .zip(ranges_to_replace.iter())
14384                    .find_map(|(selection, range)| {
14385                        if selection.id == newest_selection_id {
14386                            Some(
14387                                (range.start.0 as isize - selection.head().0 as isize)
14388                                    ..(range.end.0 as isize - selection.head().0 as isize),
14389                            )
14390                        } else {
14391                            None
14392                        }
14393                    })
14394            });
14395
14396            cx.emit(EditorEvent::InputHandled {
14397                utf16_range_to_replace: range_to_replace,
14398                text: text.into(),
14399            });
14400
14401            if let Some(new_selected_ranges) = new_selected_ranges {
14402                this.change_selections(None, cx, |selections| {
14403                    selections.select_ranges(new_selected_ranges)
14404                });
14405                this.backspace(&Default::default(), cx);
14406            }
14407
14408            this.handle_input(text, cx);
14409        });
14410
14411        if let Some(transaction) = self.ime_transaction {
14412            self.buffer.update(cx, |buffer, cx| {
14413                buffer.group_until_transaction(transaction, cx);
14414            });
14415        }
14416
14417        self.unmark_text(cx);
14418    }
14419
14420    fn replace_and_mark_text_in_range(
14421        &mut self,
14422        range_utf16: Option<Range<usize>>,
14423        text: &str,
14424        new_selected_range_utf16: Option<Range<usize>>,
14425        cx: &mut ViewContext<Self>,
14426    ) {
14427        if !self.input_enabled {
14428            return;
14429        }
14430
14431        let transaction = self.transact(cx, |this, cx| {
14432            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14433                let snapshot = this.buffer.read(cx).read(cx);
14434                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14435                    for marked_range in &mut marked_ranges {
14436                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14437                        marked_range.start.0 += relative_range_utf16.start;
14438                        marked_range.start =
14439                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14440                        marked_range.end =
14441                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14442                    }
14443                }
14444                Some(marked_ranges)
14445            } else if let Some(range_utf16) = range_utf16 {
14446                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14447                Some(this.selection_replacement_ranges(range_utf16, cx))
14448            } else {
14449                None
14450            };
14451
14452            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14453                let newest_selection_id = this.selections.newest_anchor().id;
14454                this.selections
14455                    .all::<OffsetUtf16>(cx)
14456                    .iter()
14457                    .zip(ranges_to_replace.iter())
14458                    .find_map(|(selection, range)| {
14459                        if selection.id == newest_selection_id {
14460                            Some(
14461                                (range.start.0 as isize - selection.head().0 as isize)
14462                                    ..(range.end.0 as isize - selection.head().0 as isize),
14463                            )
14464                        } else {
14465                            None
14466                        }
14467                    })
14468            });
14469
14470            cx.emit(EditorEvent::InputHandled {
14471                utf16_range_to_replace: range_to_replace,
14472                text: text.into(),
14473            });
14474
14475            if let Some(ranges) = ranges_to_replace {
14476                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14477            }
14478
14479            let marked_ranges = {
14480                let snapshot = this.buffer.read(cx).read(cx);
14481                this.selections
14482                    .disjoint_anchors()
14483                    .iter()
14484                    .map(|selection| {
14485                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14486                    })
14487                    .collect::<Vec<_>>()
14488            };
14489
14490            if text.is_empty() {
14491                this.unmark_text(cx);
14492            } else {
14493                this.highlight_text::<InputComposition>(
14494                    marked_ranges.clone(),
14495                    HighlightStyle {
14496                        underline: Some(UnderlineStyle {
14497                            thickness: px(1.),
14498                            color: None,
14499                            wavy: false,
14500                        }),
14501                        ..Default::default()
14502                    },
14503                    cx,
14504                );
14505            }
14506
14507            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14508            let use_autoclose = this.use_autoclose;
14509            let use_auto_surround = this.use_auto_surround;
14510            this.set_use_autoclose(false);
14511            this.set_use_auto_surround(false);
14512            this.handle_input(text, cx);
14513            this.set_use_autoclose(use_autoclose);
14514            this.set_use_auto_surround(use_auto_surround);
14515
14516            if let Some(new_selected_range) = new_selected_range_utf16 {
14517                let snapshot = this.buffer.read(cx).read(cx);
14518                let new_selected_ranges = marked_ranges
14519                    .into_iter()
14520                    .map(|marked_range| {
14521                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14522                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14523                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14524                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14525                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14526                    })
14527                    .collect::<Vec<_>>();
14528
14529                drop(snapshot);
14530                this.change_selections(None, cx, |selections| {
14531                    selections.select_ranges(new_selected_ranges)
14532                });
14533            }
14534        });
14535
14536        self.ime_transaction = self.ime_transaction.or(transaction);
14537        if let Some(transaction) = self.ime_transaction {
14538            self.buffer.update(cx, |buffer, cx| {
14539                buffer.group_until_transaction(transaction, cx);
14540            });
14541        }
14542
14543        if self.text_highlights::<InputComposition>(cx).is_none() {
14544            self.ime_transaction.take();
14545        }
14546    }
14547
14548    fn bounds_for_range(
14549        &mut self,
14550        range_utf16: Range<usize>,
14551        element_bounds: gpui::Bounds<Pixels>,
14552        cx: &mut ViewContext<Self>,
14553    ) -> Option<gpui::Bounds<Pixels>> {
14554        let text_layout_details = self.text_layout_details(cx);
14555        let gpui::Point {
14556            x: em_width,
14557            y: line_height,
14558        } = self.character_size(cx);
14559
14560        let snapshot = self.snapshot(cx);
14561        let scroll_position = snapshot.scroll_position();
14562        let scroll_left = scroll_position.x * em_width;
14563
14564        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14565        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14566            + self.gutter_dimensions.width
14567            + self.gutter_dimensions.margin;
14568        let y = line_height * (start.row().as_f32() - scroll_position.y);
14569
14570        Some(Bounds {
14571            origin: element_bounds.origin + point(x, y),
14572            size: size(em_width, line_height),
14573        })
14574    }
14575}
14576
14577trait SelectionExt {
14578    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14579    fn spanned_rows(
14580        &self,
14581        include_end_if_at_line_start: bool,
14582        map: &DisplaySnapshot,
14583    ) -> Range<MultiBufferRow>;
14584}
14585
14586impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14587    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14588        let start = self
14589            .start
14590            .to_point(&map.buffer_snapshot)
14591            .to_display_point(map);
14592        let end = self
14593            .end
14594            .to_point(&map.buffer_snapshot)
14595            .to_display_point(map);
14596        if self.reversed {
14597            end..start
14598        } else {
14599            start..end
14600        }
14601    }
14602
14603    fn spanned_rows(
14604        &self,
14605        include_end_if_at_line_start: bool,
14606        map: &DisplaySnapshot,
14607    ) -> Range<MultiBufferRow> {
14608        let start = self.start.to_point(&map.buffer_snapshot);
14609        let mut end = self.end.to_point(&map.buffer_snapshot);
14610        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14611            end.row -= 1;
14612        }
14613
14614        let buffer_start = map.prev_line_boundary(start).0;
14615        let buffer_end = map.next_line_boundary(end).0;
14616        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14617    }
14618}
14619
14620impl<T: InvalidationRegion> InvalidationStack<T> {
14621    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14622    where
14623        S: Clone + ToOffset,
14624    {
14625        while let Some(region) = self.last() {
14626            let all_selections_inside_invalidation_ranges =
14627                if selections.len() == region.ranges().len() {
14628                    selections
14629                        .iter()
14630                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14631                        .all(|(selection, invalidation_range)| {
14632                            let head = selection.head().to_offset(buffer);
14633                            invalidation_range.start <= head && invalidation_range.end >= head
14634                        })
14635                } else {
14636                    false
14637                };
14638
14639            if all_selections_inside_invalidation_ranges {
14640                break;
14641            } else {
14642                self.pop();
14643            }
14644        }
14645    }
14646}
14647
14648impl<T> Default for InvalidationStack<T> {
14649    fn default() -> Self {
14650        Self(Default::default())
14651    }
14652}
14653
14654impl<T> Deref for InvalidationStack<T> {
14655    type Target = Vec<T>;
14656
14657    fn deref(&self) -> &Self::Target {
14658        &self.0
14659    }
14660}
14661
14662impl<T> DerefMut for InvalidationStack<T> {
14663    fn deref_mut(&mut self) -> &mut Self::Target {
14664        &mut self.0
14665    }
14666}
14667
14668impl InvalidationRegion for SnippetState {
14669    fn ranges(&self) -> &[Range<Anchor>] {
14670        &self.ranges[self.active_index]
14671    }
14672}
14673
14674pub fn diagnostic_block_renderer(
14675    diagnostic: Diagnostic,
14676    max_message_rows: Option<u8>,
14677    allow_closing: bool,
14678    _is_valid: bool,
14679) -> RenderBlock {
14680    let (text_without_backticks, code_ranges) =
14681        highlight_diagnostic_message(&diagnostic, max_message_rows);
14682
14683    Arc::new(move |cx: &mut BlockContext| {
14684        let group_id: SharedString = cx.block_id.to_string().into();
14685
14686        let mut text_style = cx.text_style().clone();
14687        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14688        let theme_settings = ThemeSettings::get_global(cx);
14689        text_style.font_family = theme_settings.buffer_font.family.clone();
14690        text_style.font_style = theme_settings.buffer_font.style;
14691        text_style.font_features = theme_settings.buffer_font.features.clone();
14692        text_style.font_weight = theme_settings.buffer_font.weight;
14693
14694        let multi_line_diagnostic = diagnostic.message.contains('\n');
14695
14696        let buttons = |diagnostic: &Diagnostic| {
14697            if multi_line_diagnostic {
14698                v_flex()
14699            } else {
14700                h_flex()
14701            }
14702            .when(allow_closing, |div| {
14703                div.children(diagnostic.is_primary.then(|| {
14704                    IconButton::new("close-block", IconName::XCircle)
14705                        .icon_color(Color::Muted)
14706                        .size(ButtonSize::Compact)
14707                        .style(ButtonStyle::Transparent)
14708                        .visible_on_hover(group_id.clone())
14709                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14710                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14711                }))
14712            })
14713            .child(
14714                IconButton::new("copy-block", IconName::Copy)
14715                    .icon_color(Color::Muted)
14716                    .size(ButtonSize::Compact)
14717                    .style(ButtonStyle::Transparent)
14718                    .visible_on_hover(group_id.clone())
14719                    .on_click({
14720                        let message = diagnostic.message.clone();
14721                        move |_click, cx| {
14722                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14723                        }
14724                    })
14725                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14726            )
14727        };
14728
14729        let icon_size = buttons(&diagnostic)
14730            .into_any_element()
14731            .layout_as_root(AvailableSpace::min_size(), cx);
14732
14733        h_flex()
14734            .id(cx.block_id)
14735            .group(group_id.clone())
14736            .relative()
14737            .size_full()
14738            .block_mouse_down()
14739            .pl(cx.gutter_dimensions.width)
14740            .w(cx.max_width - cx.gutter_dimensions.full_width())
14741            .child(
14742                div()
14743                    .flex()
14744                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14745                    .flex_shrink(),
14746            )
14747            .child(buttons(&diagnostic))
14748            .child(div().flex().flex_shrink_0().child(
14749                StyledText::new(text_without_backticks.clone()).with_highlights(
14750                    &text_style,
14751                    code_ranges.iter().map(|range| {
14752                        (
14753                            range.clone(),
14754                            HighlightStyle {
14755                                font_weight: Some(FontWeight::BOLD),
14756                                ..Default::default()
14757                            },
14758                        )
14759                    }),
14760                ),
14761            ))
14762            .into_any_element()
14763    })
14764}
14765
14766fn inline_completion_edit_text(
14767    editor_snapshot: &EditorSnapshot,
14768    edits: &Vec<(Range<Anchor>, String)>,
14769    include_deletions: bool,
14770    cx: &WindowContext,
14771) -> InlineCompletionText {
14772    let edit_start = edits
14773        .first()
14774        .unwrap()
14775        .0
14776        .start
14777        .to_display_point(editor_snapshot);
14778
14779    let mut text = String::new();
14780    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14781    let mut highlights = Vec::new();
14782    for (old_range, new_text) in edits {
14783        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14784        text.extend(
14785            editor_snapshot
14786                .buffer_snapshot
14787                .chunks(offset..old_offset_range.start, false)
14788                .map(|chunk| chunk.text),
14789        );
14790        offset = old_offset_range.end;
14791
14792        let start = text.len();
14793        let color = if include_deletions && new_text.is_empty() {
14794            text.extend(
14795                editor_snapshot
14796                    .buffer_snapshot
14797                    .chunks(old_offset_range.start..offset, false)
14798                    .map(|chunk| chunk.text),
14799            );
14800            cx.theme().status().deleted_background
14801        } else {
14802            text.push_str(new_text);
14803            cx.theme().status().created_background
14804        };
14805        let end = text.len();
14806
14807        highlights.push((
14808            start..end,
14809            HighlightStyle {
14810                background_color: Some(color),
14811                ..Default::default()
14812            },
14813        ));
14814    }
14815
14816    let edit_end = edits
14817        .last()
14818        .unwrap()
14819        .0
14820        .end
14821        .to_display_point(editor_snapshot);
14822    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14823        .to_offset(editor_snapshot, Bias::Right);
14824    text.extend(
14825        editor_snapshot
14826            .buffer_snapshot
14827            .chunks(offset..end_of_line, false)
14828            .map(|chunk| chunk.text),
14829    );
14830
14831    InlineCompletionText::Edit {
14832        text: text.into(),
14833        highlights,
14834    }
14835}
14836
14837pub fn highlight_diagnostic_message(
14838    diagnostic: &Diagnostic,
14839    mut max_message_rows: Option<u8>,
14840) -> (SharedString, Vec<Range<usize>>) {
14841    let mut text_without_backticks = String::new();
14842    let mut code_ranges = Vec::new();
14843
14844    if let Some(source) = &diagnostic.source {
14845        text_without_backticks.push_str(source);
14846        code_ranges.push(0..source.len());
14847        text_without_backticks.push_str(": ");
14848    }
14849
14850    let mut prev_offset = 0;
14851    let mut in_code_block = false;
14852    let has_row_limit = max_message_rows.is_some();
14853    let mut newline_indices = diagnostic
14854        .message
14855        .match_indices('\n')
14856        .filter(|_| has_row_limit)
14857        .map(|(ix, _)| ix)
14858        .fuse()
14859        .peekable();
14860
14861    for (quote_ix, _) in diagnostic
14862        .message
14863        .match_indices('`')
14864        .chain([(diagnostic.message.len(), "")])
14865    {
14866        let mut first_newline_ix = None;
14867        let mut last_newline_ix = None;
14868        while let Some(newline_ix) = newline_indices.peek() {
14869            if *newline_ix < quote_ix {
14870                if first_newline_ix.is_none() {
14871                    first_newline_ix = Some(*newline_ix);
14872                }
14873                last_newline_ix = Some(*newline_ix);
14874
14875                if let Some(rows_left) = &mut max_message_rows {
14876                    if *rows_left == 0 {
14877                        break;
14878                    } else {
14879                        *rows_left -= 1;
14880                    }
14881                }
14882                let _ = newline_indices.next();
14883            } else {
14884                break;
14885            }
14886        }
14887        let prev_len = text_without_backticks.len();
14888        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14889        text_without_backticks.push_str(new_text);
14890        if in_code_block {
14891            code_ranges.push(prev_len..text_without_backticks.len());
14892        }
14893        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14894        in_code_block = !in_code_block;
14895        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14896            text_without_backticks.push_str("...");
14897            break;
14898        }
14899    }
14900
14901    (text_without_backticks.into(), code_ranges)
14902}
14903
14904fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14905    match severity {
14906        DiagnosticSeverity::ERROR => colors.error,
14907        DiagnosticSeverity::WARNING => colors.warning,
14908        DiagnosticSeverity::INFORMATION => colors.info,
14909        DiagnosticSeverity::HINT => colors.info,
14910        _ => colors.ignored,
14911    }
14912}
14913
14914pub fn styled_runs_for_code_label<'a>(
14915    label: &'a CodeLabel,
14916    syntax_theme: &'a theme::SyntaxTheme,
14917) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14918    let fade_out = HighlightStyle {
14919        fade_out: Some(0.35),
14920        ..Default::default()
14921    };
14922
14923    let mut prev_end = label.filter_range.end;
14924    label
14925        .runs
14926        .iter()
14927        .enumerate()
14928        .flat_map(move |(ix, (range, highlight_id))| {
14929            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14930                style
14931            } else {
14932                return Default::default();
14933            };
14934            let mut muted_style = style;
14935            muted_style.highlight(fade_out);
14936
14937            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14938            if range.start >= label.filter_range.end {
14939                if range.start > prev_end {
14940                    runs.push((prev_end..range.start, fade_out));
14941                }
14942                runs.push((range.clone(), muted_style));
14943            } else if range.end <= label.filter_range.end {
14944                runs.push((range.clone(), style));
14945            } else {
14946                runs.push((range.start..label.filter_range.end, style));
14947                runs.push((label.filter_range.end..range.end, muted_style));
14948            }
14949            prev_end = cmp::max(prev_end, range.end);
14950
14951            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14952                runs.push((prev_end..label.text.len(), fade_out));
14953            }
14954
14955            runs
14956        })
14957}
14958
14959pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14960    let mut prev_index = 0;
14961    let mut prev_codepoint: Option<char> = None;
14962    text.char_indices()
14963        .chain([(text.len(), '\0')])
14964        .filter_map(move |(index, codepoint)| {
14965            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14966            let is_boundary = index == text.len()
14967                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14968                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14969            if is_boundary {
14970                let chunk = &text[prev_index..index];
14971                prev_index = index;
14972                Some(chunk)
14973            } else {
14974                None
14975            }
14976        })
14977}
14978
14979pub trait RangeToAnchorExt: Sized {
14980    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14981
14982    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14983        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14984        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14985    }
14986}
14987
14988impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14989    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14990        let start_offset = self.start.to_offset(snapshot);
14991        let end_offset = self.end.to_offset(snapshot);
14992        if start_offset == end_offset {
14993            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14994        } else {
14995            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14996        }
14997    }
14998}
14999
15000pub trait RowExt {
15001    fn as_f32(&self) -> f32;
15002
15003    fn next_row(&self) -> Self;
15004
15005    fn previous_row(&self) -> Self;
15006
15007    fn minus(&self, other: Self) -> u32;
15008}
15009
15010impl RowExt for DisplayRow {
15011    fn as_f32(&self) -> f32 {
15012        self.0 as f32
15013    }
15014
15015    fn next_row(&self) -> Self {
15016        Self(self.0 + 1)
15017    }
15018
15019    fn previous_row(&self) -> Self {
15020        Self(self.0.saturating_sub(1))
15021    }
15022
15023    fn minus(&self, other: Self) -> u32 {
15024        self.0 - other.0
15025    }
15026}
15027
15028impl RowExt for MultiBufferRow {
15029    fn as_f32(&self) -> f32 {
15030        self.0 as f32
15031    }
15032
15033    fn next_row(&self) -> Self {
15034        Self(self.0 + 1)
15035    }
15036
15037    fn previous_row(&self) -> Self {
15038        Self(self.0.saturating_sub(1))
15039    }
15040
15041    fn minus(&self, other: Self) -> u32 {
15042        self.0 - other.0
15043    }
15044}
15045
15046trait RowRangeExt {
15047    type Row;
15048
15049    fn len(&self) -> usize;
15050
15051    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
15052}
15053
15054impl RowRangeExt for Range<MultiBufferRow> {
15055    type Row = MultiBufferRow;
15056
15057    fn len(&self) -> usize {
15058        (self.end.0 - self.start.0) as usize
15059    }
15060
15061    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
15062        (self.start.0..self.end.0).map(MultiBufferRow)
15063    }
15064}
15065
15066impl RowRangeExt for Range<DisplayRow> {
15067    type Row = DisplayRow;
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 = DisplayRow> {
15074        (self.start.0..self.end.0).map(DisplayRow)
15075    }
15076}
15077
15078fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
15079    if hunk.diff_base_byte_range.is_empty() {
15080        DiffHunkStatus::Added
15081    } else if hunk.row_range.is_empty() {
15082        DiffHunkStatus::Removed
15083    } else {
15084        DiffHunkStatus::Modified
15085    }
15086}
15087
15088/// If select range has more than one line, we
15089/// just point the cursor to range.start.
15090fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
15091    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
15092        range
15093    } else {
15094        range.start..range.start
15095    }
15096}
15097
15098pub struct KillRing(ClipboardItem);
15099impl Global for KillRing {}
15100
15101const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);